Martin Prikryl 18 years ago
parent
commit
a2053825d1
93 changed files with 7916 additions and 7662 deletions
  1. 3 3
      Console.bpr
  2. BIN
      Console.res
  3. 0 27
      DScpComp.bpk
  4. BIN
      DScpComp.res
  5. 3 3
      DragExt.bpr
  6. BIN
      DragExt.res
  7. 0 27
      FileZilla.bpr
  8. 0 27
      Putty.bpr
  9. 0 27
      RScpComp.bpr
  10. 0 27
      ScpCore.bpr
  11. 0 27
      ScpForms.bpr
  12. 5 5
      WinSCP.bpr
  13. BIN
      WinSCP.res
  14. 14 1
      core/Common.cpp
  15. 11 1
      core/CoreMain.cpp
  16. 1 1
      core/CoreMain.h
  17. 4 0
      core/FileMasks.cpp
  18. 1 0
      core/FileSystems.h
  19. 36 12
      core/FtpFileSystem.cpp
  20. 7 1
      core/FtpFileSystem.h
  21. 23 9
      core/RemoteFiles.cpp
  22. 180 170
      core/ScpFileSystem.cpp
  23. 1 0
      core/ScpFileSystem.h
  24. 5 1
      core/SecureShell.cpp
  25. 2 0
      core/SecureShell.h
  26. 38 0
      core/SessionData.cpp
  27. 12 0
      core/SessionData.h
  28. 13 1
      core/SessionInfo.cpp
  29. 36 28
      core/SftpFileSystem.cpp
  30. 1 0
      core/SftpFileSystem.h
  31. 88 26
      core/Terminal.cpp
  32. 3 0
      core/Terminal.h
  33. 222 0
      default.bmk
  34. 27 1
      filezilla/ApiLog.cpp
  35. 3 1
      filezilla/ApiLog.h
  36. 6 7
      filezilla/ControlSocket.cpp
  37. 0 1
      filezilla/Crypt.cpp
  38. 1 1
      filezilla/FileZillaApi.cpp
  39. 5 19
      filezilla/FileZillaIntern.cpp
  40. 5172 5174
      filezilla/FtpControlSocket.cpp
  41. 334 334
      filezilla/MainThread.cpp
  42. 9 1
      filezilla/Options.cpp
  43. 1268 1268
      filezilla/TransferSocket.cpp
  44. 4 6
      filezilla/misc/CBase64Coding.cpp
  45. 3 3
      filezilla/misc/CBase64Coding.hpp
  46. 19 0
      forms/About.cpp
  47. 3 3
      forms/CustomScpExplorer.cpp
  48. 1 1
      forms/FileSystemInfo.cpp
  49. 0 1
      forms/LogSettings.cpp
  50. 77 39
      forms/Login.cpp
  51. 6 6
      forms/Login.dfm
  52. 4 0
      forms/Login.h
  53. 0 2
      forms/NonVisual.cpp
  54. 24 1
      forms/Progress.cpp
  55. 1 0
      forms/Progress.h
  56. 20 0
      forms/Synchronize.cpp
  57. 2 0
      forms/Synchronize.h
  58. 32 2
      forms/SynchronizeProgress.cpp
  59. 2 0
      forms/SynchronizeProgress.h
  60. 1 3
      lib.bmk
  61. 17 6
      makefile
  62. 0 27
      packages/DiscMon_B5.bpk
  63. BIN
      packages/DiscMon_B5.res
  64. 0 27
      packages/DragDrop_B5.bpk
  65. BIN
      packages/DragDrop_B5.res
  66. 0 27
      packages/DriveDir_B5.bpk
  67. BIN
      packages/DriveDir_B5.res
  68. 0 27
      packages/Moje_B5.bpk
  69. BIN
      packages/Moje_B5.res
  70. 0 27
      packages/ThemeManagerC6.bpk
  71. BIN
      packages/ThemeManagerC6.res
  72. 0 27
      packages/ThemeManagerC6D.bpk
  73. BIN
      packages/ThemeManagerC6D.res
  74. 0 27
      packages/tb2k_cb6.bpk
  75. 0 27
      packages/tb2kdsgn_cb6.bpk
  76. 0 15
      packages/tbx_cb6.bpk
  77. 0 15
      packages/tbxdsgn_cb6.bpk
  78. 4 2
      readme
  79. 1 1
      release/winscp.isl
  80. 1 1
      release/winscp.u3i
  81. 1 0
      release/winscpsetup.iss
  82. 26 26
      resource/LicencePuTTY.txt
  83. 1 0
      resource/TextsCore.h
  84. 2 1
      resource/TextsCore1.rc
  85. 12 12
      windows/GUIConfiguration.cpp
  86. 5 5
      windows/GUIConfiguration.h
  87. 24 14
      windows/TerminalManager.cpp
  88. 56 41
      windows/UserInterface.cpp
  89. 3 3
      windows/WinConfiguration.cpp
  90. 3 3
      windows/WinConfiguration.h
  91. 16 0
      windows/WinInterface.cpp
  92. 4 0
      windows/WinInterface.h
  93. 7 3
      windows/WinMain.cpp

+ 3 - 3
Console.bpr

@@ -56,7 +56,7 @@ AutoIncBuild=1
 MajorVer=2
 MinorVer=0
 Release=0
-Build=69
+Build=71
 Debug=0
 PreRelease=0
 Special=0
@@ -68,13 +68,13 @@ CodePage=1252
 [Version Info Keys]
 CompanyName=Martin Prikryl
 FileDescription=Console interface for WinSCP
-FileVersion=2.0.0.69
+FileVersion=2.0.0.71
 InternalName=console
 LegalCopyright=(c) 2004-2007 Martin Prikryl
 LegalTrademarks=
 OriginalFilename=winscp.com
 ProductName=WinSCP
-ProductVersion=4.0.0.0
+ProductVersion=4.0.1.0
 Comments=
 WWW=http://winscp.net/
 

BIN
Console.res


+ 0 - 27
DScpComp.bpk

@@ -63,33 +63,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=1
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=1
 LinkDebugVcl=0

BIN
DScpComp.res


+ 3 - 3
DragExt.bpr

@@ -56,7 +56,7 @@ AutoIncBuild=1
 MajorVer=1
 MinorVer=1
 Release=5
-Build=68
+Build=70
 Debug=0
 PreRelease=0
 Special=0
@@ -68,13 +68,13 @@ CodePage=1252
 [Version Info Keys]
 CompanyName=Martin Prikryl
 FileDescription=Drag&amp;Drop shell extension for WinSCP
-FileVersion=1.1.5.68
+FileVersion=1.1.5.70
 InternalName=dragext
 LegalCopyright=(c) 2004-2007 Martin Prikryl
 LegalTrademarks=
 OriginalFilename=dragext.dll
 ProductName=WinSCP
-ProductVersion=4.0.0.0
+ProductVersion=4.0.1.0
 Comments=
 WWW=http://winscp.net/
 

BIN
DragExt.res


+ 0 - 27
FileZilla.bpr

@@ -75,33 +75,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 27
Putty.bpr

@@ -96,33 +96,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 27
RScpComp.bpr

@@ -51,33 +51,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 27
ScpCore.bpr

@@ -83,33 +83,6 @@
   </FILES>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 27
ScpForms.bpr

@@ -110,33 +110,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 5 - 5
WinSCP.bpr

@@ -95,8 +95,8 @@ IncludeVerInfo=1
 AutoIncBuild=1
 MajorVer=4
 MinorVer=0
-Release=0
-Build=341
+Release=1
+Build=343
 Debug=0
 PreRelease=0
 Special=0
@@ -108,13 +108,13 @@ CodePage=1252
 [Version Info Keys]
 CompanyName=Martin Prikryl
 FileDescription=Windows SFTP, FTP and SCP client
-FileVersion=4.0.0.341
+FileVersion=4.0.1.343
 InternalName=winscp
 LegalCopyright=(c) 2000-2007 Martin Prikryl
 LegalTrademarks=
-OriginalFilename=winscp400.exe
+OriginalFilename=winscp401.exe
 ProductName=WinSCP
-ProductVersion=4.0.0.0
+ProductVersion=4.0.1.0
 WWW=http://winscp.net/
 
 [Compiler]

BIN
WinSCP.res


+ 14 - 1
core/Common.cpp

@@ -394,7 +394,20 @@ AnsiString __fastcall ExpandEnvironmentVariables(const AnsiString & Str)
 //---------------------------------------------------------------------------
 bool __fastcall CompareFileName(const AnsiString & Path1, const AnsiString & Path2)
 {
-  return AnsiSameText(ExtractShortPathName(Path1), ExtractShortPathName(Path2));
+  AnsiString ShortPath1 = ExtractShortPathName(Path1);
+  AnsiString ShortPath2 = ExtractShortPathName(Path2);
+
+  bool Result;
+  // ExtractShortPathName returns empty string if file does not exist
+  if (ShortPath1.IsEmpty() || ShortPath2.IsEmpty())
+  {
+    Result = AnsiSameText(Path1, Path2);
+  }
+  else
+  {
+    Result = AnsiSameText(ExtractShortPathName(Path1), ExtractShortPathName(Path2));
+  }
+  return Result;
 }
 //---------------------------------------------------------------------------
 bool __fastcall ComparePaths(const AnsiString & Path1, const AnsiString & Path2)

+ 11 - 1
core/CoreMain.cpp

@@ -8,7 +8,9 @@
 #include "Interface.h"
 #include "Configuration.h"
 #include "PuttyIntf.h"
+#ifndef NO_FILEZILLA
 #include "FileZillaIntf.h"
+#endif
 //---------------------------------------------------------------------------
 #pragma package(smart_init)
 //---------------------------------------------------------------------------
@@ -35,7 +37,9 @@ void CoreInitialize()
   Configuration = CreateConfiguration();
 
   PuttyInitialize();
+  #ifndef NO_FILEZILLA
   TFileZillaIntf::Initialize();
+  #endif
 
   // ... but some pieces of configuration can be initialized only afterwards
   Configuration->Initialize();
@@ -79,12 +83,18 @@ void CoreFinalize()
   delete Configuration;
   Configuration = NULL;
 
+  #ifndef NO_FILEZILLA
   TFileZillaIntf::Finalize();
+  #endif
   PuttyFinalize();
 }
 //---------------------------------------------------------------------------
-void CoreSetResourceModule(HINSTANCE ResourceHandle)
+void CoreSetResourceModule(void * ResourceHandle)
 {
+  #ifndef NO_FILEZILLA
   TFileZillaIntf::SetResourceModule(ResourceHandle);
+  #else
+  USEDPARAM(ResourceHandle);
+  #endif
 }
 //---------------------------------------------------------------------------

+ 1 - 1
core/CoreMain.h

@@ -11,6 +11,6 @@ extern TStoredSessionList *StoredSessions;
 //---------------------------------------------------------------------------
 void CoreInitialize();
 void CoreFinalize();
-void CoreSetResourceModule(HINSTANCE ResourceHandle);
+void CoreSetResourceModule(void * ResourceHandle);
 //---------------------------------------------------------------------------
 #endif

+ 4 - 0
core/FileMasks.cpp

@@ -154,6 +154,10 @@ bool __fastcall TFileMasks::MatchesFileMask(const AnsiString & Filename, const A
   {
     Result = true;
   }
+  else if ((Mask == "*.") && (Filename.Pos(".") == 0))
+  {
+    Result = true;
+  }
   else
   {
     Result = ::MatchesMask(Filename, Mask);

+ 1 - 0
core/FileSystems.h

@@ -78,6 +78,7 @@ public:
   virtual const TFileSystemInfo & __fastcall GetFileSystemInfo(bool Retrieve) = 0;
   virtual bool __fastcall TemporaryTransferFile(const AnsiString & FileName) = 0;
   virtual bool __fastcall GetStoredCredentialsTried() = 0;
+  virtual AnsiString __fastcall GetUserName() = 0;
 
   __property AnsiString CurrentDirectory = { read = GetCurrentDirectory };
 

+ 36 - 12
core/FtpFileSystem.cpp

@@ -2,6 +2,8 @@
 #include <vcl.h>
 #pragma hdrstop
 
+#ifndef NO_FILEZILLA
+//---------------------------------------------------------------------------
 #include <list>
 #include "FtpFileSystem.h"
 #include "FileZillaIntf.h"
@@ -115,9 +117,11 @@ class TMessageQueue : public std::list<std::pair<WPARAM, LPARAM> >
 struct TFileTransferData
 {
   int Params;
+  bool AutoResume;
 };
 //---------------------------------------------------------------------------
-const int tfFirstLevel =   0x01;
+const int tfFirstLevel = 0x01;
+const int tfAutoResume = 0x02;
 //---------------------------------------------------------------------------
 struct TSinkFileParams
 {
@@ -290,6 +294,10 @@ void __fastcall TFTPFileSystem::Open()
       {
         FTerminal->FatalError(NULL, LoadStr(AUTHENTICATION_FAILED));
       }
+      else
+      {
+        FUserName = UserName;
+      }
     }
 
     // ask for username if it was not specified in advance,
@@ -574,10 +582,15 @@ void __fastcall TFTPFileSystem::CalculateFilesChecksum(const AnsiString & /*Alg*
 //---------------------------------------------------------------------------
 bool __fastcall TFTPFileSystem::ConfirmOverwrite(AnsiString & FileName,
   TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
-  const TOverwriteFileParams * FileParams, int Params)
+  const TOverwriteFileParams * FileParams, int Params, bool AutoResume)
 {
   bool Result;
-  if (OperationProgress->NoToAll)
+  if (OperationProgress->YesToAll)
+  {
+    OverwriteMode = omOverwrite;
+    Result = true;
+  }
+  else if (OperationProgress->NoToAll)
   {
     FFileTransferAbort = ftaSkip;
     Result = false;
@@ -589,7 +602,7 @@ bool __fastcall TFTPFileSystem::ConfirmOverwrite(AnsiString & FileName,
     int Answer;
     if (FLAGSET(Params, cpNoConfirmation))
     {
-      Answer = (CanResume ? qaRetry : qaYes);
+      Answer = (CanResume && AutoResume ? qaRetry : qaYes);
     }
     else
     {
@@ -809,8 +822,9 @@ void __fastcall TFTPFileSystem::SinkRobust(const AnsiString FileName,
       assert(File != NULL);
       if (!File->IsDirectory)
       {
-        // prevent overwrite and resume confirmations
+        // prevent overwrite confirmations
         Params |= cpNoConfirmation;
+        Flags |= tfAutoResume;
       }
     }
   }
@@ -868,7 +882,7 @@ void __fastcall TFTPFileSystem::Sink(const AnsiString FileName,
       SinkFileParams.Params = Params;
       SinkFileParams.OperationProgress = OperationProgress;
       SinkFileParams.Skipped = false;
-      SinkFileParams.Flags = Flags & ~tfFirstLevel;
+      SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
 
       FTerminal->ProcessDirectory(FileName, SinkFile, &SinkFileParams);
 
@@ -923,6 +937,7 @@ void __fastcall TFTPFileSystem::Sink(const AnsiString FileName,
       FFileTransferFileName = DestFileName;
       TFileTransferData UserData;
       UserData.Params = Params;
+      UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
       FFileZillaIntf->FileTransfer(DestFullName.c_str(), OnlyFileName.c_str(),
         FilePath.c_str(), true, File->Size, TransferType, &UserData);
       unsigned int Reply = WaitForReply();
@@ -1075,9 +1090,10 @@ void __fastcall TFTPFileSystem::SourceRobust(const AnsiString FileName,
     if (Retry)
     {
       OperationProgress->RollbackTransfer();
-      // prevent overwrite and resume confirmations
+      // prevent overwrite confirmations
       // (should not be set for directories!)
       Params |= cpNoConfirmation;
+      Flags |= tfAutoResume;
     }
   }
   while (Retry);
@@ -1143,12 +1159,13 @@ void __fastcall TFTPFileSystem::Source(const AnsiString FileName,
     FIgnoreFileList = true;
     try
     {
-      // not supports fro uploads anyway
+      // not supports for uploads anyway
       FFileTransferPreserveTime = CopyParam->PreserveTime;
       // not used for uploads
       FFileTransferFileName = DestFileName;
       TFileTransferData UserData;
       UserData.Params = Params;
+      UserData.AutoResume = FLAGSET(Flags, tfAutoResume);
       FFileZillaIntf->FileTransfer(FileName.c_str(), DestFileName.c_str(),
         TargetDir.c_str(), false, Size, TransferType, &UserData);
       unsigned int Reply = WaitForReply();
@@ -1202,7 +1219,7 @@ void __fastcall TFTPFileSystem::DirectorySource(const AnsiString DirectoryName,
       if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
       {
         SourceRobust(FileName, DestFullName, CopyParam, Params, OperationProgress,
-          Flags & ~tfFirstLevel);
+          Flags & ~(tfFirstLevel | tfAutoResume));
       }
     }
     catch (EScpSkipFile &E)
@@ -1590,6 +1607,11 @@ bool __fastcall TFTPFileSystem::GetStoredCredentialsTried()
   return !FTerminal->SessionData->Password.IsEmpty();
 }
 //---------------------------------------------------------------------------
+AnsiString __fastcall TFTPFileSystem::GetUserName()
+{
+  return FUserName;
+}
+//---------------------------------------------------------------------------
 AnsiString __fastcall TFTPFileSystem::GetCurrentDirectory()
 {
   return FCurrentDirectory;
@@ -1722,12 +1744,12 @@ int __fastcall TFTPFileSystem::GetOptionVal(int OptionID) const
       break;
 
     case OPTION_KEEPALIVE:
-      Result = ((Data->PingType != ptOff) ? TRUE : FALSE);
+      Result = ((Data->FtpPingType != ptOff) ? TRUE : FALSE);
       break;
 
     case OPTION_INTERVALLOW:
     case OPTION_INTERVALHIGH:
-      Result = Data->PingInterval;
+      Result = Data->FtpPingInterval;
       break;
 
     case OPTION_VMSALLREVISIONS:
@@ -2229,7 +2251,7 @@ bool __fastcall TFTPFileSystem::HandleAsynchRequestOverwrite(
     }
 
     if (ConfirmOverwrite(FileName, OverwriteMode, OperationProgress,
-          &FileParams, UserData.Params))
+          &FileParams, UserData.Params, UserData.AutoResume))
     {
       switch (OverwriteMode)
       {
@@ -2530,3 +2552,5 @@ bool __fastcall TFTPFileSystem::Unquote(AnsiString & Str)
 
   return (State == DONE);
 }
+//---------------------------------------------------------------------------
+#endif NO_FILEZILLA

+ 7 - 1
core/FtpFileSystem.h

@@ -2,6 +2,8 @@
 #ifndef FtpFileSystemH
 #define FtpFileSystemH
 
+#ifndef NO_FILEZILLA
+//---------------------------------------------------------------------------
 #include <time.h>
 #include <FileSystems.h>
 //---------------------------------------------------------------------------
@@ -73,6 +75,7 @@ public:
   virtual const TFileSystemInfo & __fastcall GetFileSystemInfo(bool Retrieve);
   virtual bool __fastcall TemporaryTransferFile(const AnsiString & FileName);
   virtual bool __fastcall GetStoredCredentialsTried();
+  virtual AnsiString __fastcall GetUserName();
 
 protected:
   enum TOverwriteMode { omOverwrite, omResume };
@@ -138,7 +141,7 @@ protected:
     int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags);
   bool __fastcall ConfirmOverwrite(AnsiString & FileName,
     TOverwriteMode & OverwriteMode, TFileOperationProgressType * OperationProgress,
-    const TOverwriteFileParams * FileParams, int Params);
+    const TOverwriteFileParams * FileParams, int Params, bool AutoResume);
   void __fastcall CheckFileTransferAbort();
   void __fastcall ReadDirectoryProgress(__int64 Bytes);
   void __fastcall ResetFileTransfer();
@@ -190,7 +193,10 @@ private:
   bool FFileTransferPreserveTime;
   bool FAwaitingProgress;
   TCaptureOutputEvent FOnCaptureOutput;
+  AnsiString FUserName;
   mutable AnsiString FOptionScratch;
 };
 //---------------------------------------------------------------------------
+#endif NO_FILEZILLA
+//---------------------------------------------------------------------------
 #endif // FtpFileSystemH

+ 23 - 9
core/RemoteFiles.cpp

@@ -370,7 +370,9 @@ int __fastcall FakeFileImageIndex(AnsiString FileName, unsigned long Attrs,
 
   TSHFileInfo SHFileInfo;
   // On Win2k we get icon of "ZIP drive" for ".." (parent directory)
-  if (FileName == "..")
+  if ((FileName == "..") ||
+      ((FileName.Length() == 2) && (FileName[2] == ':') &&
+       (tolower(FileName[1]) >= 'a') && (tolower(FileName[1]) <= 'z')))
   {
     FileName = "dumb";
   }
@@ -382,14 +384,27 @@ int __fastcall FakeFileImageIndex(AnsiString FileName, unsigned long Attrs,
     FileName.SetLength(FileName.Length() - PartialExtLen);
   }
 
-  SHGetFileInfo(FileName.c_str(),
-    Attrs, &SHFileInfo, sizeof(SHFileInfo),
-    SHGFI_SYSICONINDEX | SHGFI_USEFILEATTRIBUTES | SHGFI_TYPENAME);
-  if (TypeName != NULL)
+  int Icon;
+  if (SHGetFileInfo(FileName.c_str(),
+        Attrs, &SHFileInfo, sizeof(SHFileInfo),
+        SHGFI_SYSICONINDEX | SHGFI_USEFILEATTRIBUTES | SHGFI_TYPENAME) != 0)
   {
-    *TypeName = SHFileInfo.szTypeName;
+    if (TypeName != NULL)
+    {
+      *TypeName = SHFileInfo.szTypeName;
+    }
+    Icon = SHFileInfo.iIcon;
   }
-  return SHFileInfo.iIcon;
+  else
+  {
+    if (TypeName != NULL)
+    {
+      *TypeName = "";
+    }
+    Icon = -1;
+  }
+
+  return Icon;
 }
 //- TRemoteFiles ------------------------------------------------------------
 __fastcall TRemoteFile::TRemoteFile(TRemoteFile * ALinkedByFile):
@@ -469,8 +484,7 @@ void __fastcall TRemoteFile::LoadTypeInfo()
 //---------------------------------------------------------------------------
 Integer __fastcall TRemoteFile::GetIconIndex() const
 {
-  assert(FIconIndex >= -1);
-  if (FIconIndex < 0)
+  if (FIconIndex == -1)
   {
     const_cast<TRemoteFile *>(this)->LoadTypeInfo();
   }

+ 180 - 170
core/ScpFileSystem.cpp

@@ -364,6 +364,11 @@ bool __fastcall TSCPFileSystem::GetStoredCredentialsTried()
   return FSecureShell->GetStoredCredentialsTried();
 }
 //---------------------------------------------------------------------------
+AnsiString __fastcall TSCPFileSystem::GetUserName()
+{
+  return FSecureShell->UserName;
+}
+//---------------------------------------------------------------------------
 void __fastcall TSCPFileSystem::Idle()
 {
   // Keep session alive
@@ -1530,221 +1535,226 @@ void __fastcall TSCPFileSystem::SCPSource(const AnsiString FileName,
   FTerminal->OpenLocalFile(FileName, GENERIC_READ,
     &Attrs, &File, NULL, &MTime, &ATime, &Size);
 
-  bool Dir = FLAGSET(Attrs, faDirectory);
+  try
+  {
+    bool Dir = FLAGSET(Attrs, faDirectory);
 
-  TFileMasks::TParams MaskParams;
-  MaskParams.Size = Size;
+    TFileMasks::TParams MaskParams;
+    MaskParams.Size = Size;
 
-  if (FLAGCLEAR(Params, cpDelete) &&
-      !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
-  {
-    FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
-    THROW_SKIP_FILE_NULL;
-  }
+    if (FLAGCLEAR(Params, cpDelete) &&
+        !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
+    {
+      FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
+      THROW_SKIP_FILE_NULL;
+    }
 
-  if (Dir)
-  {
-    SCPDirectorySource(FileName, CopyParam, Params, OperationProgress, Level);
-  }
+    if (Dir)
+    {
+      SCPDirectorySource(FileName, CopyParam, Params, OperationProgress, Level);
+    }
     else
-  try
-  {
-    assert(File);
+    {
+      assert(File);
 
-    // File is regular file (not directory)
-    FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
+      // File is regular file (not directory)
+      FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
 
-    OperationProgress->SetLocalSize(Size);
+      OperationProgress->SetLocalSize(Size);
 
-    // Suppose same data size to transfer as to read
-    // (not true with ASCII transfer)
-    OperationProgress->SetTransferSize(OperationProgress->LocalSize);
-    OperationProgress->TransferingFile = false;
+      // Suppose same data size to transfer as to read
+      // (not true with ASCII transfer)
+      OperationProgress->SetTransferSize(OperationProgress->LocalSize);
+      OperationProgress->TransferingFile = false;
 
-    // Will we use ASCII of BINARY file tranfer?
-    OperationProgress->SetAsciiTransfer(
-      CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
-    FTerminal->LogEvent(
-      AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
-        " transfer mode selected.");
+      // Will we use ASCII of BINARY file tranfer?
+      OperationProgress->SetAsciiTransfer(
+        CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
+      FTerminal->LogEvent(
+        AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
+          " transfer mode selected.");
 
-    try
-    {
-      // During ASCII transfer we will load whole file to this buffer
-      // than convert EOL and send it at once, because before converting EOL
-      // we can't know its size
-      TFileBuffer AsciiBuf;
-      do
+      try
       {
-        // Buffer for one block of data
-        TFileBuffer BlockBuf;
+        // During ASCII transfer we will load whole file to this buffer
+        // than convert EOL and send it at once, because before converting EOL
+        // we can't know its size
+        TFileBuffer AsciiBuf;
+        do
+        {
+          // Buffer for one block of data
+          TFileBuffer BlockBuf;
 
-        // This is crucial, if it fails during file transfer, it's fatal error
-        FILE_OPERATION_LOOP_EX (!OperationProgress->TransferingFile,
-            FMTLOAD(READ_ERROR, (FileName)),
-          try
-          {
-            BlockBuf.LoadFile(File, OperationProgress->LocalBlockSize(), true);
-          }
-          catch(...)
-          {
-            RaiseLastOSError();
-          }
-        );
+          // This is crucial, if it fails during file transfer, it's fatal error
+          FILE_OPERATION_LOOP_EX (!OperationProgress->TransferingFile,
+              FMTLOAD(READ_ERROR, (FileName)),
+            try
+            {
+              BlockBuf.LoadFile(File, OperationProgress->LocalBlockSize(), true);
+            }
+            catch(...)
+            {
+              RaiseLastOSError();
+            }
+          );
 
-        OperationProgress->AddLocalyUsed(BlockBuf.Size);
+          OperationProgress->AddLocalyUsed(BlockBuf.Size);
 
-        // We do ASCII transfer: convert EOL of current block
-        // (we don't convert whole buffer, cause it would produce
-        // huge memory-transfers while inserting/deleting EOL characters)
-        // Than we add current block to file buffer
-        if (OperationProgress->AsciiTransfer)
-        {
-          BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
-            FTerminal->SessionData->EOLType, cpRemoveCtrlZ);
-          BlockBuf.Memory->Seek(0, soFromBeginning);
-          AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
-          // We don't need it any more
-          BlockBuf.Memory->Clear();
-          // Calculate total size to sent (assume that ratio between
-          // size of source and size of EOL-transformed data would remain same)
-          // First check if file contains anything (div by zero!)
-          if (OperationProgress->LocalyUsed)
+          // We do ASCII transfer: convert EOL of current block
+          // (we don't convert whole buffer, cause it would produce
+          // huge memory-transfers while inserting/deleting EOL characters)
+          // Than we add current block to file buffer
+          if (OperationProgress->AsciiTransfer)
           {
-            __int64 X = OperationProgress->LocalSize;
-            X *= AsciiBuf.Size;
-            X /= OperationProgress->LocalyUsed;
-            OperationProgress->ChangeTransferSize(X);
+            BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
+              FTerminal->SessionData->EOLType, cpRemoveCtrlZ);
+            BlockBuf.Memory->Seek(0, soFromBeginning);
+            AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
+            // We don't need it any more
+            BlockBuf.Memory->Clear();
+            // Calculate total size to sent (assume that ratio between
+            // size of source and size of EOL-transformed data would remain same)
+            // First check if file contains anything (div by zero!)
+            if (OperationProgress->LocalyUsed)
+            {
+              __int64 X = OperationProgress->LocalSize;
+              X *= AsciiBuf.Size;
+              X /= OperationProgress->LocalyUsed;
+              OperationProgress->ChangeTransferSize(X);
+            }
+              else
+            {
+              OperationProgress->ChangeTransferSize(0);
+            }
           }
-            else
+
+          // We send file information on first pass during BINARY transfer
+          // and on last pass during ASCII transfer
+          // BINARY: We succeeded reading first buffer from file, hopefully
+          // we will be able to read whole, so we send file info to remote side
+          // This is done, because when reading fails we can't interrupt sending
+          // (don't know how to tell other side that it failed)
+          if (!OperationProgress->TransferingFile &&
+              (!OperationProgress->AsciiTransfer || OperationProgress->IsLocalyDone()))
           {
-            OperationProgress->ChangeTransferSize(0);
-          }
-        }
+            AnsiString Buf;
 
-        // We send file information on first pass during BINARY transfer
-        // and on last pass during ASCII transfer
-        // BINARY: We succeeded reading first buffer from file, hopefully
-        // we will be able to read whole, so we send file info to remote side
-        // This is done, because when reading fails we can't interrupt sending
-        // (don't know how to tell other side that it failed)
-        if (!OperationProgress->TransferingFile &&
-            (!OperationProgress->AsciiTransfer || OperationProgress->IsLocalyDone()))
-        {
-          AnsiString Buf;
+            if (CopyParam->PreserveTime)
+            {
+              // Send last file access and modification time
+              // TVarRec don't understand 'unsigned int' -> we use sprintf()
+              Buf.sprintf("T%lu 0 %lu 0", static_cast<unsigned long>(MTime),
+                static_cast<unsigned long>(ATime));
+              FSecureShell->SendLine(Buf);
+              SCPResponse();
+            }
 
-          if (CopyParam->PreserveTime)
-          {
-            // Send last file access and modification time
+            // Send file modes (rights), filesize and file name
             // TVarRec don't understand 'unsigned int' -> we use sprintf()
-            Buf.sprintf("T%lu 0 %lu 0", static_cast<unsigned long>(MTime),
-              static_cast<unsigned long>(ATime));
+            Buf.sprintf("C%s %Ld %s",
+              CopyParam->RemoteFileRights(Attrs).Octal.data(),
+              (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
+                OperationProgress->LocalSize),
+              DestFileName.data());
             FSecureShell->SendLine(Buf);
             SCPResponse();
-          }
-
-          // Send file modes (rights), filesize and file name
-          // TVarRec don't understand 'unsigned int' -> we use sprintf()
-          Buf.sprintf("C%s %Ld %s",
-            CopyParam->RemoteFileRights(Attrs).Octal.data(),
-            (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
-              OperationProgress->LocalSize),
-            DestFileName.data());
-          FSecureShell->SendLine(Buf);
-          SCPResponse();
-          // Indicate we started transfering file, we need to finish it
-          // If not, it's fatal error
-          OperationProgress->TransferingFile = true;
+            // Indicate we started transfering file, we need to finish it
+            // If not, it's fatal error
+            OperationProgress->TransferingFile = true;
 
-          // If we're doing ASCII transfer, this is last pass
-          // so we send whole file
-          /* TODO : We can't send file above 32bit size in ASCII mode! */
-          if (OperationProgress->AsciiTransfer)
-          {
-            FTerminal->LogEvent(FORMAT("Sending ASCII data (%u bytes)",
-              (AsciiBuf.Size)));
-            // Should be equal, just in case it's rounded (see above)
-            OperationProgress->ChangeTransferSize(AsciiBuf.Size);
-            while (!OperationProgress->IsTransferDone())
+            // If we're doing ASCII transfer, this is last pass
+            // so we send whole file
+            /* TODO : We can't send file above 32bit size in ASCII mode! */
+            if (OperationProgress->AsciiTransfer)
             {
-              FSecureShell->Send(
-                AsciiBuf.Data + (unsigned int)OperationProgress->TransferedSize,
-                OperationProgress->TransferBlockSize());
-              OperationProgress->AddTransfered(OperationProgress->TransferBlockSize());
-              if (OperationProgress->Cancel == csCancelTransfer)
+              FTerminal->LogEvent(FORMAT("Sending ASCII data (%u bytes)",
+                (AsciiBuf.Size)));
+              // Should be equal, just in case it's rounded (see above)
+              OperationProgress->ChangeTransferSize(AsciiBuf.Size);
+              while (!OperationProgress->IsTransferDone())
               {
-                throw Exception(USER_TERMINATED);
+                FSecureShell->Send(
+                  AsciiBuf.Data + (unsigned int)OperationProgress->TransferedSize,
+                  OperationProgress->TransferBlockSize());
+                OperationProgress->AddTransfered(OperationProgress->TransferBlockSize());
+                if (OperationProgress->Cancel == csCancelTransfer)
+                {
+                  throw Exception(USER_TERMINATED);
+                }
               }
             }
           }
-        }
 
-        // At end of BINARY transfer pass, send current block
-        if (!OperationProgress->AsciiTransfer)
-        {
-          if (!OperationProgress->TransferedSize)
+          // At end of BINARY transfer pass, send current block
+          if (!OperationProgress->AsciiTransfer)
           {
-            FTerminal->LogEvent(FORMAT("Sending BINARY data (first block, %u bytes)",
-              (BlockBuf.Size)));
+            if (!OperationProgress->TransferedSize)
+            {
+              FTerminal->LogEvent(FORMAT("Sending BINARY data (first block, %u bytes)",
+                (BlockBuf.Size)));
+            }
+            else if (FTerminal->Configuration->LogProtocol >= 1)
+            {
+              FTerminal->LogEvent(FORMAT("Sending BINARY data (%u bytes)",
+                (BlockBuf.Size)));
+            }
+            FSecureShell->Send(BlockBuf.Data, BlockBuf.Size);
+            OperationProgress->AddTransfered(BlockBuf.Size);
           }
-          else if (FTerminal->Configuration->LogProtocol >= 1)
+
+          if ((OperationProgress->Cancel == csCancelTransfer) ||
+              (OperationProgress->Cancel == csCancel && !OperationProgress->TransferingFile))
           {
-            FTerminal->LogEvent(FORMAT("Sending BINARY data (%u bytes)",
-              (BlockBuf.Size)));
+            throw Exception(USER_TERMINATED);
           }
-          FSecureShell->Send(BlockBuf.Data, BlockBuf.Size);
-          OperationProgress->AddTransfered(BlockBuf.Size);
         }
+        while (!OperationProgress->IsLocalyDone() || !OperationProgress->IsTransferDone());
 
-        if ((OperationProgress->Cancel == csCancelTransfer) ||
-            (OperationProgress->Cancel == csCancel && !OperationProgress->TransferingFile))
+        FSecureShell->SendNull();
+        try
         {
-          throw Exception(USER_TERMINATED);
+          SCPResponse();
+          // If one of two following exceptions occurs, is means, that remote
+          // side already know, that file transfer finished, even if it failed
+          // so we don't have to throw EFatal
+        }
+        catch (EScp &E)
+        {
+          // SCP protocol fatal error
+          OperationProgress->TransferingFile = false;
+          throw;
+        }
+        catch (EScpFileSkipped &E)
+        {
+          // SCP protocol non-fatal error
+          OperationProgress->TransferingFile = false;
+          throw;
         }
-      }
-      while (!OperationProgress->IsLocalyDone() || !OperationProgress->IsTransferDone());
 
-      FSecureShell->SendNull();
-      try
-      {
-        SCPResponse();
-        // If one of two following exceptions occurs, is means, that remote
-        // side already know, that file transfer finished, even if it failed
-        // so we don't have to throw EFatal
-      }
-      catch (EScp &E)
-      {
-        // SCP protocol fatal error
+        // We succeded transfering file, from now we can handle exceptions
+        // normally -> no fatal error
         OperationProgress->TransferingFile = false;
-        throw;
-      }
-      catch (EScpFileSkipped &E)
-      {
-        // SCP protocol non-fatal error
-        OperationProgress->TransferingFile = false;
-        throw;
-      }
-
-      // We succeded transfering file, from now we can handle exceptions
-      // normally -> no fatal error
-      OperationProgress->TransferingFile = false;
-    }
-    catch (Exception &E)
-    {
-      // Every exception during file transfer is fatal
-      if (OperationProgress->TransferingFile)
-      {
-        FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
       }
-        else
+      catch (Exception &E)
       {
-        throw;
+        // Every exception during file transfer is fatal
+        if (OperationProgress->TransferingFile)
+        {
+          FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
+        }
+          else
+        {
+          throw;
+        }
       }
     }
   }
   __finally
   {
-    CloseHandle(File);
+    if (File != NULL)
+    {
+      CloseHandle(File);
+    }
   }
 
   /* TODO : Delete also read-only files. */

+ 1 - 0
core/ScpFileSystem.h

@@ -66,6 +66,7 @@ public:
   virtual const TFileSystemInfo & __fastcall GetFileSystemInfo(bool Retrieve);
   virtual bool __fastcall TemporaryTransferFile(const AnsiString & FileName);
   virtual bool __fastcall GetStoredCredentialsTried();
+  virtual AnsiString __fastcall GetUserName();
 
 protected:
   __property TStrings * Output = { read = FOutput };

+ 5 - 1
core/SecureShell.cpp

@@ -400,6 +400,10 @@ bool __fastcall TSecureShell::PromptUser(const AnsiString Prompt,
       Result = FUI->PromptUser(FSessionData,
         FMTLOAD(USERNAME_PROMPT, (FSessionData->SessionName)),
         pkPrompt, Response);
+      if (Result)
+      {
+        FUserName = Response;
+      }
     }
   }
   else
@@ -969,7 +973,7 @@ void __fastcall TSecureShell::SocketEventSelect(SOCKET Socket, HANDLE Event, boo
     LogEvent(FORMAT("Selecting events %d for socket %d", (int(Events), int(Socket))));
   }
 
-  if (WSAEventSelect(Socket, (unsigned long)Event, Events) == SOCKET_ERROR)
+  if (WSAEventSelect(Socket, (WSAEVENT)Event, Events) == SOCKET_ERROR)
   {
     if (Configuration->LogProtocol >= 2)
     {

+ 2 - 0
core/SecureShell.h

@@ -53,6 +53,7 @@ private:
   AnsiString FCWriteTemp;
   AnsiString FAuthenticationLog;
   AnsiString FLastTunnelError;
+  AnsiString FUserName;
 
   static TCipher __fastcall FuncToSsh1Cipher(const void * Cipher);
   static TCipher __fastcall FuncToSsh2Cipher(const void * Cipher);
@@ -135,6 +136,7 @@ public:
   __property TCaptureOutputEvent OnCaptureOutput = { read = FOnCaptureOutput, write = FOnCaptureOutput };
   __property TDateTime LastDataSent = { read = FLastDataSent };
   __property AnsiString LastTunnelError = { read = FLastTunnelError };
+  __property AnsiString UserName = { read = FUserName };
 };
 //---------------------------------------------------------------------------
 #endif

+ 38 - 0
core/SessionData.cpp

@@ -138,8 +138,11 @@ void __fastcall TSessionData::Default()
   TunnelLocalPortNumber = 0;
   TunnelPortFwd = "";
 
+  // FTP
   FtpPasvMode = false;
   FtpAccount = "";
+  FtpPingInterval = 30;
+  FtpPingType = ptDummyCommand;
 
   CustomParam1 = "";
   CustomParam2 = "";
@@ -257,6 +260,8 @@ void __fastcall TSessionData::Assign(TPersistent * Source)
 
     DUPL(FtpPasvMode);
     DUPL(FtpAccount);
+    DUPL(FtpPingInterval);
+    DUPL(FtpPingType);
 
     DUPL(CustomParam1);
     DUPL(CustomParam2);
@@ -447,6 +452,8 @@ void __fastcall TSessionData::Load(THierarchicalStorage * Storage)
     // Ftp prefix
     FtpPasvMode = Storage->ReadBool("FtpPasvMode", FtpPasvMode);
     FtpAccount = Storage->ReadString("FtpAccount", FtpAccount);
+    FtpPingInterval = Storage->ReadInteger("FtpPingInterval", FtpPingInterval);
+    FtpPingType = static_cast<TPingType>(Storage->ReadInteger("FtpPingType", FtpPingType));
 
     CustomParam1 = Storage->ReadString("CustomParam1", CustomParam1);
     CustomParam2 = Storage->ReadString("CustomParam2", CustomParam2);
@@ -687,6 +694,8 @@ void __fastcall TSessionData::Save(THierarchicalStorage * Storage,
 
       WRITE_DATA(Bool, FtpPasvMode);
       WRITE_DATA(String, FtpAccount);
+      WRITE_DATA(Integer, FtpPingInterval);
+      WRITE_DATA(Integer, FtpPingType);
 
       WRITE_DATA(String, CustomParam1);
       WRITE_DATA(String, CustomParam2);
@@ -853,6 +862,25 @@ bool __fastcall TSessionData::ParseUrl(AnsiString Url, int Params,
   return Result;
 }
 //---------------------------------------------------------------------
+void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
+{
+  FOrigHostName = HostName;
+  FOrigPortNumber = PortNumber;
+  FOrigProxyMethod = ProxyMethod;
+
+  HostName = "127.0.0.1";
+  PortNumber = APortNumber;
+  // proxy settings is used for tunnel
+  ProxyMethod = pmNone;
+}
+//---------------------------------------------------------------------
+void __fastcall TSessionData::RollbackTunnel()
+{
+  HostName = FOrigHostName;
+  PortNumber = FOrigPortNumber;
+  ProxyMethod = FOrigProxyMethod;
+}
+//---------------------------------------------------------------------
 void __fastcall TSessionData::ValidateName(const AnsiString Name)
 {
   if (Name.LastDelimiter(FInvalidChars) > 0)
@@ -1552,6 +1580,16 @@ void __fastcall TSessionData::SetFtpAccount(AnsiString value)
   SET_SESSION_PROPERTY(FtpAccount);
 }
 //---------------------------------------------------------------------
+void __fastcall TSessionData::SetFtpPingInterval(int value)
+{
+  SET_SESSION_PROPERTY(FtpPingInterval);
+}
+//---------------------------------------------------------------------------
+void __fastcall TSessionData::SetFtpPingType(TPingType value)
+{
+  SET_SESSION_PROPERTY(FtpPingType);
+}
+//---------------------------------------------------------------------
 AnsiString __fastcall TSessionData::GetInfoTip()
 {
   if (UsesSsh)

+ 12 - 0
core/SessionData.h

@@ -126,6 +126,12 @@ private:
   AnsiString FTunnelPortFwd;
   bool FFtpPasvMode;
   AnsiString FFtpAccount;
+  int FFtpPingInterval;
+  TPingType FFtpPingType;
+
+  AnsiString FOrigHostName;
+  int FOrigPortNumber;
+  TProxyMethod FOrigProxyMethod;
 
   void __fastcall SetHostName(AnsiString value);
   void __fastcall SetPortNumber(int value);
@@ -235,6 +241,8 @@ private:
   bool __fastcall GetTunnelAutoassignLocalPortNumber();
   void __fastcall SetFtpPasvMode(bool value);
   void __fastcall SetFtpAccount(AnsiString value);
+  void __fastcall SetFtpPingInterval(int value);
+  void __fastcall SetFtpPingType(TPingType value);
   static AnsiString __fastcall DecodeUrlChars(const AnsiString & S, bool Decode);
 
 public:
@@ -247,6 +255,8 @@ public:
   void __fastcall Remove();
   virtual void __fastcall Assign(TPersistent * Source);
   bool __fastcall ParseUrl(AnsiString Url, int Params, AnsiString * FileName);
+  void __fastcall ConfigureTunnel(int PortNumber);
+  void __fastcall RollbackTunnel();
   static bool __fastcall ParseUrl(AnsiString Url, int Params,
     AnsiString * ConnectInfo, AnsiString * HostName, int * PortNumber,
     AnsiString * UserName, AnsiString * Password, AnsiString * Path,
@@ -349,6 +359,8 @@ public:
   __property AnsiString TunnelPortFwd = { read = FTunnelPortFwd, write = SetTunnelPortFwd };
   __property bool FtpPasvMode = { read = FFtpPasvMode, write = SetFtpPasvMode };
   __property AnsiString FtpAccount = { read = FFtpAccount, write = SetFtpAccount };
+  __property int FtpPingInterval  = { read=FFtpPingInterval, write=SetFtpPingInterval };
+  __property TPingType FtpPingType = { read = FFtpPingType, write = SetFtpPingType };
   __property AnsiString StorageKey = { read = GetStorageKey };
 };
 //---------------------------------------------------------------------------

+ 13 - 1
core/SessionInfo.cpp

@@ -371,8 +371,20 @@ void __fastcall TSessionLog::DoAddStartupInfo(TSessionData * Data)
     }
     ADF("Transfer Protocol: %s", (Data->FSProtocolStr));
     char * PingTypes = "-NC";
+    TPingType PingType;
+    int PingInterval;
+    if (Data->FSProtocol == fsFTP)
+    {
+      PingType = Data->FtpPingType;
+      PingInterval = Data->FtpPingInterval;
+    }
+    else
+    {
+      PingType = Data->PingType;
+      PingInterval = Data->PingInterval;
+    }
     ADF("Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
-      (AnsiString(PingTypes[Data->PingType]), Data->PingInterval, Data->Timeout));
+      (AnsiString(PingTypes[PingType]), PingInterval, Data->Timeout));
     ADF("Proxy: %s", (ProxyMethodList[Data->ProxyMethod]));
     if (Data->ProxyMethod != pmNone)
     {

+ 36 - 28
core/SftpFileSystem.cpp

@@ -1200,13 +1200,13 @@ protected:
   // event handler for incoming data
   void __fastcall ReceiveHandler(TObject * /*Sender*/)
   {
-    while (FFileSystem->PeekPacket())
+    while (FFileSystem->PeekPacket() && ReceivePacketAsynchronously())
     {
-      ReceivePacketAsynchronously();
+      // loop
     }
   }
 
-  virtual void __fastcall ReceivePacketAsynchronously() = 0;
+  virtual bool __fastcall ReceivePacketAsynchronously() = 0;
 
   // sends as many requests as allowed by implementation
   virtual bool SendRequests()
@@ -1355,13 +1355,15 @@ protected:
     OperationProgress->AddTransfered(FLastBlockSize);
   }
 
-  virtual void __fastcall ReceivePacketAsynchronously()
+  virtual bool __fastcall ReceivePacketAsynchronously()
   {
     // do not read response to close request
-    if (FRequests->Count > 0)
+    bool Result = (FRequests->Count > 0);
+    if (Result)
     {
       ReceivePacket(NULL, SSH_FXP_STATUS);
     }
+    return Result;
   }
 
   inline int __fastcall GetBlockSize()
@@ -1515,7 +1517,7 @@ protected:
         Request->AddString(FAlg);
         Request->AddInt64(0); // offset
         Request->AddInt64(0); // length (0 = till end)
-        Request->AddInt64(0); // block size (0 = no blocks or "one block")
+        Request->AddCardinal(0); // block size (0 = no blocks or "one block")
 
         Request->Token = File;
       }
@@ -1704,6 +1706,11 @@ bool __fastcall TSFTPFileSystem::GetStoredCredentialsTried()
   return FSecureShell->GetStoredCredentialsTried();
 }
 //---------------------------------------------------------------------------
+AnsiString __fastcall TSFTPFileSystem::GetUserName()
+{
+  return FSecureShell->UserName;
+}
+//---------------------------------------------------------------------------
 void __fastcall TSFTPFileSystem::Idle()
 {
   // Keep session alive
@@ -3415,10 +3422,8 @@ void __fastcall TSFTPFileSystem::DoCalculateFilesChecksum(const AnsiString & Alg
           OperationProgress->SetFile(File->FileName);
 
           Alg = Packet.GetString();
-          Checksum = StrToHex(Packet.GetString());
+          Checksum = StrToHex(AnsiString(Packet.GetNextData(Packet.RemainingLength), Packet.RemainingLength));
           OnCalculatedChecksum(File->FileName, Alg, Checksum);
-          //assert(false); // TODO
-          //Checksum = Packet.GetString();
 
           Success = true;
         }
@@ -3806,26 +3811,26 @@ void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
   FTerminal->OpenLocalFile(FileName, GENERIC_READ, &OpenParams.LocalFileAttrs,
     &File, NULL, &MTime, &ATime, &Size);
 
-  bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
+  try
+  {
+    bool Dir = FLAGSET(OpenParams.LocalFileAttrs, faDirectory);
 
-  TFileMasks::TParams MaskParams;
-  MaskParams.Size = Size;
+    TFileMasks::TParams MaskParams;
+    MaskParams.Size = Size;
 
-  if (FLAGCLEAR(Params, cpDelete) &&
-      !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
-  {
-    FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
-    THROW_SKIP_FILE_NULL;
-  }
+    if (FLAGCLEAR(Params, cpDelete) &&
+        !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
+    {
+      FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
+      THROW_SKIP_FILE_NULL;
+    }
 
-  if (Dir)
-  {
-    SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
-      OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
-  }
-  else
-  {
-    try
+    if (Dir)
+    {
+      SFTPDirectorySource(IncludeTrailingBackslash(FileName), TargetDir,
+        OpenParams.LocalFileAttrs, CopyParam, Params, OperationProgress, Flags);
+    }
+    else
     {
       // File is regular file (not directory)
       assert(File);
@@ -3875,7 +3880,7 @@ void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
         if (FLAGCLEAR(Flags, tfNewDirectory))
         {
           FTerminal->LogEvent("Checking existence of file.");
-          TRemoteFile * File = new TRemoteFile();
+          TRemoteFile * File = NULL;
           DestFileExists = RemoteFileExists(DestFullName, &File);
           if (DestFileExists)
           {
@@ -4099,7 +4104,10 @@ void __fastcall TSFTPFileSystem::SFTPSource(const AnsiString FileName,
         );
       }
     }
-    __finally
+  }
+  __finally
+  {
+    if (File != NULL)
     {
       CloseHandle(File);
     }

+ 1 - 0
core/SftpFileSystem.h

@@ -78,6 +78,7 @@ public:
   virtual const TFileSystemInfo & __fastcall GetFileSystemInfo(bool Retrieve);
   virtual bool __fastcall TemporaryTransferFile(const AnsiString & FileName);
   virtual bool __fastcall GetStoredCredentialsTried();
+  virtual AnsiString __fastcall GetUserName();
 
 protected:
   TSecureShell * FSecureShell;

+ 88 - 26
core/Terminal.cpp

@@ -16,7 +16,9 @@
 #include "SecureShell.h"
 #include "ScpFileSystem.h"
 #include "SftpFileSystem.h"
+#ifndef NO_FILEZILLA
 #include "FtpFileSystem.h"
+#endif
 #include "TextsCore.h"
 #include "HelpCore.h"
 #include "Security.h"
@@ -324,9 +326,11 @@ __fastcall TTerminal::TTerminal(TSessionData * SessionData,
   FReadCurrentDirectoryPending = false;
   FReadDirectoryPending = false;
   FUsersGroupsLookedup = False;
+  FTunnelLocalPortNumber = 0;
   FGroups = new TUsersGroupsList();
   FUsers = new TUsersGroupsList();
   FFileSystem = NULL;
+  FSecureShell = NULL;
   FOnProgress = NULL;
   FOnFinished = NULL;
   FOnDeleteLocalFile = NULL;
@@ -454,6 +458,7 @@ void __fastcall TTerminal::Close()
 //---------------------------------------------------------------------------
 void __fastcall TTerminal::ResetConnection()
 {
+  FAnyInformation = false;
   // used to be called from Reopen(), why?
   FTunnelError = "";
 
@@ -473,9 +478,6 @@ void __fastcall TTerminal::Open()
       ResetConnection();
       FStatus = ssOpening;
 
-      AnsiString OrigHostName = FSessionData->HostName;
-      int OrigPortNumber = FSessionData->PortNumber;
-
       try
       {
         if (FFileSystem == NULL)
@@ -491,37 +493,46 @@ void __fastcall TTerminal::Open()
           OpenTunnel();
           Log->AddSeparator();
 
-          FSessionData->HostName = "127.0.0.1";
-          FSessionData->PortNumber = FTunnelLocalPortNumber;
+          FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
+
           DoInformation(LoadStr(USING_TUNNEL), false);
           LogEvent(FORMAT("Connecting via tunnel interface %s:%d.",
             (FSessionData->HostName, FSessionData->PortNumber)));
         }
+        else
+        {
+          FTunnelLocalPortNumber = 0;
+        }
 
         if (FFileSystem == NULL)
         {
           if (SessionData->FSProtocol == fsFTP)
           {
+            #ifdef NO_FILEZILLA
+            LogEvent("FTP protocol is not supported by this build.");
+            FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
+            #else
             FFSProtocol = cfsFTP;
             FFileSystem = new TFTPFileSystem(this);
             FFileSystem->Open();
             Log->AddSeparator();
             LogEvent("Using FTP protocol.");
+            #endif
           }
           else
           {
-            TSecureShell * SecureShell = NULL;
+            assert(FSecureShell == NULL);
             try
             {
-              SecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
+              FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
               try
               {
-                SecureShell->Open();
+                FSecureShell->Open();
               }
               catch(Exception & E)
               {
-                assert(!SecureShell->Active);
-                if (!SecureShell->Active && !FTunnelError.IsEmpty())
+                assert(!FSecureShell->Active);
+                if (!FSecureShell->Active && !FTunnelError.IsEmpty())
                 {
                   // the only case where we expect this to happen
                   assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
@@ -536,24 +547,25 @@ void __fastcall TTerminal::Open()
               Log->AddSeparator();
 
               if ((SessionData->FSProtocol == fsSCPonly) ||
-                  (SessionData->FSProtocol == fsSFTP && SecureShell->SshFallbackCmd()))
+                  (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
               {
                 FFSProtocol = cfsSCP;
-                FFileSystem = new TSCPFileSystem(this, SecureShell);
-                SecureShell = NULL; // ownership passed
+                FFileSystem = new TSCPFileSystem(this, FSecureShell);
+                FSecureShell = NULL; // ownership passed
                 LogEvent("Using SCP protocol.");
               }
               else
               {
                 FFSProtocol = cfsSFTP;
-                FFileSystem = new TSFTPFileSystem(this, SecureShell);
-                SecureShell = NULL; // ownership passed
+                FFileSystem = new TSFTPFileSystem(this, FSecureShell);
+                FSecureShell = NULL; // ownership passed
                 LogEvent("Using SFTP protocol.");
               }
             }
             __finally
             {
-              delete SecureShell;
+              delete FSecureShell;
+              FSecureShell = NULL;
             }
           }
         }
@@ -564,8 +576,10 @@ void __fastcall TTerminal::Open()
       }
       __finally
       {
-        FSessionData->HostName = OrigHostName;
-        FSessionData->PortNumber = OrigPortNumber;
+        if (FSessionData->Tunnel)
+        {
+          FSessionData->RollbackTunnel();
+        }
       }
 
       if (SessionData->CacheDirectoryChanges)
@@ -597,7 +611,12 @@ void __fastcall TTerminal::Open()
   }
   __finally
   {
-    DoInformation("", true, false);
+    // Prevent calling Information with active=false unless there was at least
+    // one call with active=true
+    if (FAnyInformation)
+    {
+      DoInformation("", true, false);
+    }
   }
 }
 //---------------------------------------------------------------------------
@@ -634,6 +653,14 @@ void __fastcall TTerminal::OpenTunnel()
     FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
     FTunnelData->TunnelPortFwd = FORMAT("L%d\t%s:%d",
       (FTunnelLocalPortNumber, FSessionData->HostName, FSessionData->PortNumber));
+    FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
+    FTunnelData->ProxyHost = FSessionData->ProxyHost;
+    FTunnelData->ProxyPort = FSessionData->ProxyPort;
+    FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
+    FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
+    FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
+    FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
+    FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
 
     FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
     FTunnelLog->Parent = FLog;
@@ -825,6 +852,11 @@ void __fastcall TTerminal::ShowExtendedException(Exception * E)
 void __fastcall TTerminal::DoInformation(const AnsiString & Str, bool Status,
   bool Active)
 {
+  if (Active)
+  {
+    FAnyInformation = true;
+  }
+
   if (OnInformation)
   {
     OnInformation(this, Str, Status, Active);
@@ -1234,8 +1266,15 @@ TUsersGroupsList * __fastcall TTerminal::GetUsers()
 //---------------------------------------------------------------------------
 AnsiString __fastcall TTerminal::GetUserName() const
 {
-  // in future might be implemented to detect username similar to GetUserGroups
-  return SessionData->UserName;
+  // in future might also be implemented to detect username similar to GetUserGroups
+  assert(FFileSystem != NULL);
+  AnsiString Result = FFileSystem->GetUserName();
+  // Is empty also when stored password was used
+  if (Result.IsEmpty())
+  {
+    Result = SessionData->UserName;
+  }
+  return Result;
 }
 //---------------------------------------------------------------------------
 bool __fastcall TTerminal::GetAreCachesEmpty() const
@@ -3760,13 +3799,32 @@ const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
 //---------------------------------------------------------------------
 AnsiString __fastcall TTerminal::GetPassword()
 {
-  return (FPassword.IsEmpty() ? AnsiString() :
-    DecryptPassword(FPassword, SessionData->SessionName));
+  AnsiString Result;
+  // FPassword is empty also when stored password was used
+  if (FPassword.IsEmpty())
+  {
+    Result = SessionData->Password;
+  }
+  else
+  {
+    Result = DecryptPassword(FPassword, SessionData->SessionName);
+  }
+  return Result;
 }
 //---------------------------------------------------------------------
 bool __fastcall TTerminal::GetStoredCredentialsTried()
 {
-  return FFileSystem->GetStoredCredentialsTried();
+  bool Result;
+  if (FFileSystem != NULL)
+  {
+    Result = FFileSystem->GetStoredCredentialsTried();
+  }
+  else
+  {
+    assert(FSecureShell != NULL);
+    Result = FSecureShell->GetStoredCredentialsTried();
+  }
+  return Result;
 }
 //---------------------------------------------------------------------------
 bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
@@ -3957,8 +4015,8 @@ bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
 }
 //---------------------------------------------------------------------------
 __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
-  TSessionData * SessionData, TConfiguration * Configuration, const AnsiString & Name) :
-  TTerminal(SessionData, Configuration),
+  TSessionData * ASessionData, TConfiguration * Configuration, const AnsiString & Name) :
+  TTerminal(ASessionData, Configuration),
   FMainTerminal(MainTerminal), FMasterPasswordTried(false)
 {
   Log->Parent = FMainTerminal->Log;
@@ -3966,6 +4024,10 @@ __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
 
   SessionData->NonPersistant();
   assert(FMainTerminal != NULL);
+  if (!FMainTerminal->UserName.IsEmpty())
+  {
+    SessionData->UserName = FMainTerminal->UserName;
+  }
 }
 //---------------------------------------------------------------------------
 void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)

+ 3 - 0
core/Terminal.h

@@ -166,6 +166,7 @@ private:
   TRemoteDirectoryCache * FDirectoryCache;
   TRemoteDirectoryChangesCache * FDirectoryChangesCache;
   TCustomFileSystem * FFileSystem;
+  TSecureShell * FSecureShell;
   AnsiString FLastDirectoryChange;
   TCurrentFSProtocol FFSProtocol;
   TTerminal * FCommandSession;
@@ -187,6 +188,7 @@ private:
   TExtendedExceptionEvent FOnShowExtendedException;
   TInformationEvent FOnInformation;
   TNotifyEvent FOnClose;
+  bool FAnyInformation;
   void __fastcall CommandError(Exception * E, const AnsiString Msg);
   int __fastcall CommandError(Exception * E, const AnsiString Msg, int Answers);
   AnsiString __fastcall PeekCurrentDirectory();
@@ -435,6 +437,7 @@ public:
   __property TExtendedExceptionEvent OnShowExtendedException = { read = FOnShowExtendedException, write = FOnShowExtendedException };
   __property TInformationEvent OnInformation = { read = FOnInformation, write = FOnInformation };
   __property TNotifyEvent OnClose = { read = FOnClose, write = FOnClose };
+  __property int TunnelLocalPortNumber = { read = FTunnelLocalPortNumber };
 };
 //---------------------------------------------------------------------------
 class TSecondaryTerminal : public TTerminal

+ 222 - 0
default.bmk

@@ -0,0 +1,222 @@
+# ---------------------------------------------------------------------------
+!if !$d(BCB)
+BCB = $(MAKEDIR)\..
+!endif
+
+# ---------------------------------------------------------------------------
+# IDE SECTION
+# ---------------------------------------------------------------------------
+# The following section of the project makefile is managed by the BCB IDE.
+# It is recommended to use the IDE to change any of the values in this
+# section.
+# ---------------------------------------------------------------------------
+
+VERSION = %VERSION%
+# ---------------------------------------------------------------------------
+PROJECT = %PROJECT%
+OBJFILES = %OBJFILES%
+RESFILES = %RESFILES%
+MAINSOURCE = %MAINSOURCE%
+RESDEPEN = %RESDEPEN%
+LIBFILES = %LIBFILES%
+IDLFILES = %IDLFILES%
+IDLGENFILES = %IDLGENFILES%
+LIBRARIES = %LIBRARIES%
+PACKAGES = %PACKAGES%
+SPARELIBS = %SPARELIBS%
+DEFFILE = %DEFFILE%
+OTHERFILES = %OTHERFILES%
+# ---------------------------------------------------------------------------
+DEBUGLIBPATH = %DEBUGLIBPATH%
+RELEASELIBPATH = %RELEASELIBPATH%
+USERDEFINES = $(EXTERNALDEFINES)%USERDEFINES%
+SYSDEFINES = %SYSDEFINES%
+INCLUDEPATH = %INCLUDEPATH%
+LIBPATH = %LIBPATH%
+WARNINGS= %WARNINGS%
+PATHCPP = %PATHCPP%
+PATHASM = %PATHASM%
+PATHPAS = %PATHPAS%
+PATHRC = %PATHRC%
+PATHOBJ = .;$(LIBPATH)
+# ---------------------------------------------------------------------------
+CFLAG1 = %CFLAG1%
+IDLCFLAGS = %IDLCFLAGS%
+PFLAGS = %PFLAGS%
+RFLAGS = %RFLAGS%
+AFLAGS = %AFLAGS%
+LFLAGS = %LFLAGS%
+# ---------------------------------------------------------------------------
+ALLOBJ = %ALLOBJ%
+ALLRES = %ALLRES%
+ALLLIB = %ALLLIB%
+# ---------------------------------------------------------------------------
+!ifdef IDEOPTIONS
+
+[Version Info]
+IncludeVerInfo=0
+AutoIncBuild=0
+MajorVer=1
+MinorVer=0
+Release=0
+Build=0
+Debug=0
+PreRelease=0
+Special=0
+Private=0
+DLL=0
+
+[Version Info Keys]
+CompanyName=
+FileDescription=
+FileVersion=1.0.0.0
+InternalName=
+LegalCopyright=
+LegalTrademarks=
+OriginalFilename=
+ProductName=
+ProductVersion=1.0.0.0
+Comments=
+
+[Debugging]
+DebugSourceDirs=$(BCB)\source\vcl
+
+!endif
+%FILE:.c.cpp.cc:.obj:OBJFILES%
+%TARGET%: %DEPENDENCY%
+  $(BCB)\BIN\$(BCC32) $(CFLAG1) %CFLAG1% %WARNOPTSTR% [-I]%INCLUDEPATH%?$(INCLUDEPATH) [-D]%USERDEFINES%?$(USERDEFINES) -D$(SYSDEFINES) -n$(@D) {$** }
+
+%END FILE%
+%FILE:idl2cpp%
+%TOOL%
+!if !$d(IDL2CPP)
+IDL2CPP = idl2cpp
+!endif
+
+%END TOOL%
+!if "$(USERDEFINES)" !=  ""
+DUSERDEFINES = -D$(USERDEFINES:;= -D)
+!else
+DUSERDEFINES =
+!endif
+!if "$(SYSDEFINES)" !=  ""
+DSYSDEFINES = -D$(SYSDEFINES:;= -D)
+!else
+DSYSDEFINES =
+!endif
+%DEPENDENTS%: %DEPENDENCY%
+  $(IDL2CPP) $(IDLCFLAGS) %IDLCFLAGS% %IDLROOTDIR% $(DUSERDEFINES) $(DSYSDEFINES) $?
+
+%END FILE%
+%FILE:.asm:.obj:OBJFILES%
+%TARGET%: %DEPENDENCY%
+  $(BCB)\BIN\$(TASM32) $(AFLAGS) %AFLAGS% [-i]%INCLUDEPATH:;= -i%?$(INCLUDEPATH:;= -i) [-d]%USERDEFINES:;= -d%?$(USERDEFINES:;= -d) -d$(SYSDEFINES:;= -d) $**, $@
+
+%END FILE%
+%FILE:.rc:.res:RESFILES%
+%TARGET%: %DEPENDENCY%
+  $(BCB)\BIN\$(BRCC32) $(RFLAGS) %RFLAGS% [-i]%INCLUDEPATH%?$(INCLUDEPATH) [-d]%USERDEFINES%?$(USERDEFINES) -d$(SYSDEFINES:;= -d) -fo$@ $**
+
+%END FILE%
+
+# ---------------------------------------------------------------------------
+# MAKE SECTION
+# ---------------------------------------------------------------------------
+# This section of the project file is not used by the BCB IDE.  It is for
+# the benefit of building from the command-line using the MAKE utility.
+# ---------------------------------------------------------------------------
+
+.autodepend
+# ---------------------------------------------------------------------------
+!if "$(USERDEFINES)" != ""
+AUSERDEFINES = -d$(USERDEFINES:;= -d)
+!else
+AUSERDEFINES =
+!endif
+
+!if !$d(BCC32)
+BCC32 = bcc32
+!endif
+
+!if !$d(CPP32)
+CPP32 = cpp32
+!endif
+
+!if !$d(DCC32)
+DCC32 = dcc32
+!endif
+
+!if !$d(TASM32)
+TASM32 = tasm32
+!endif
+
+!if !$d(LINKER)
+LINKER = ilink32
+!endif
+
+!if !$d(BRCC32)
+BRCC32 = brcc32
+!endif
+
+%TOOLS%
+# ---------------------------------------------------------------------------
+!if $d(PATHCPP)
+.PATH.CPP = $(PATHCPP)
+.PATH.C   = $(PATHCPP)
+!endif
+
+!if $d(PATHPAS)
+.PATH.PAS = $(PATHPAS)
+!endif
+
+!if $d(PATHASM)
+.PATH.ASM = $(PATHASM)
+!endif
+
+!if $d(PATHRC)
+.PATH.RC  = $(PATHRC)
+!endif
+
+!if $d(PATHOBJ)
+.PATH.OBJ  = $(PATHOBJ)
+!endif
+# ---------------------------------------------------------------------------
+$(PROJECT): $(OTHERFILES) $(IDLGENFILES) $(OBJFILES) $(RESDEPEN) $(DEFFILE)
+    $(BCB)\BIN\$(LINKER) @&&!
+    $(LFLAGS) -L$(LIBPATH) +
+    $(ALLOBJ), +
+    $(PROJECT),, +
+    $(ALLLIB), +
+    $(DEFFILE), +
+    $(ALLRES)
+!
+# ---------------------------------------------------------------------------
+.pas.hpp:
+    $(BCB)\BIN\$(DCC32) $(PFLAGS) -U$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -O$(INCLUDEPATH) --BCB {$< }
+
+.pas.obj:
+    $(BCB)\BIN\$(DCC32) $(PFLAGS) -U$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -O$(INCLUDEPATH) --BCB {$< }
+
+.cpp.obj:
+    $(BCB)\BIN\$(BCC32) $(CFLAG1) $(WARNINGS) -I$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -n$(@D) {$< }
+
+.c.obj:
+    $(BCB)\BIN\$(BCC32) $(CFLAG1) $(WARNINGS) -I$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -n$(@D) {$< }
+
+.c.i:
+    $(BCB)\BIN\$(CPP32) $(CFLAG1) $(WARNINGS) -I$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -n. {$< }
+
+.cpp.i:
+    $(BCB)\BIN\$(CPP32) $(CFLAG1) $(WARNINGS) -I$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -n. {$< }
+
+.asm.obj:
+    $(BCB)\BIN\$(TASM32) $(AFLAGS) -i$(INCLUDEPATH:;= -i) $(AUSERDEFINES) -d$(SYSDEFINES:;= -d) $<, $@
+
+.rc.res:
+    $(BCB)\BIN\$(BRCC32) $(RFLAGS) -I$(INCLUDEPATH) -D$(USERDEFINES);$(SYSDEFINES) -fo$@ $<
+
+%BUILDTOOLS%
+
+# ---------------------------------------------------------------------------
+
+%FILES%

+ 27 - 1
filezilla/ApiLog.cpp

@@ -83,6 +83,16 @@ void CApiLog::LogMessage(int nMessageType, LPCTSTR pMsgFormat, ...) const
 	SendLogMessage(nMessageType, text);
 }
 
+void CApiLog::LogMessageRaw(int nMessageType, LPCTSTR pMsg) const
+{
+	ASSERT(nMessageType>=0 || nMessageType<=8);
+	ASSERT(m_hTargetWnd || m_pApiLogParent);
+	if (nMessageType>=FZ_LOG_APIERROR && (nMessageType-FZ_LOG_APIERROR)>=m_pApiLogParent->m_nDebugLevel)
+		return;
+	
+	SendLogMessage(nMessageType, pMsg);
+}
+
 void CApiLog::LogMessage(int nMessageType, UINT nFormatID, ...) const
 {
 	ASSERT(nMessageType>=0 || nMessageType<=8);
@@ -132,7 +142,23 @@ BOOL CApiLog::PostMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) con
 {
 	return m_pApiLogParent->PostMessage(hWnd, Msg, wParam, lParam);
 }
-#endif  
+#endif
+
+void CApiLog::LogMessageRaw(CString SourceFile, int nSourceLine, void *pInstance, int nMessageType, LPCTSTR pMsg) const
+{
+	ASSERT(nMessageType>=4 || nMessageType<=8);
+	ASSERT(m_hTargetWnd || m_pApiLogParent);
+	ASSERT(nSourceLine>0);
+
+	int pos=SourceFile.ReverseFind('\\');
+	if (pos!=-1)
+		SourceFile=SourceFile.Mid(pos+1);
+	
+	CString msg;
+	msg.Format(_T("%s(%d): %s   caller=0x%08x"), SourceFile, nSourceLine, pMsg, (int)this);
+	
+	SendLogMessage(nMessageType, msg);
+}
 
 void CApiLog::SendLogMessage(int nMessageType, LPCTSTR pMsg) const
 {

+ 3 - 1
filezilla/ApiLog.h

@@ -37,15 +37,17 @@ public:
 	BOOL InitLog(CApiLog *pParent);
 
 	void LogMessage(int nMessageType, LPCTSTR pMsgFormat, ...) const;
+	void LogMessageRaw(int nMessageType, LPCTSTR pMsg) const;
 	void LogMessage(int nMessageType, UINT nFormatID, ...) const;
 	void LogMessage(CString SourceFile, int nSourceLine, void *pInstance, int nMessageType, LPCTSTR pMsgFormat, ...) const;
+	void LogMessageRaw(CString SourceFile, int nSourceLine, void *pInstance, int nMessageType, LPCTSTR pMsg) const;
 
 	BOOL SetDebugLevel(int nLogLevel);
 	int GetDebugLevel();
 protected:
 #ifdef MPEXT
 	virtual BOOL PostMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) const;
-#endif  
+#endif
 	void SendLogMessage(int nMessageType, LPCTSTR pMsg) const;
 	int m_nDebugLevel;
 	CApiLog *m_pApiLogParent; //Pointer to topmost parent

+ 6 - 7
filezilla/ControlSocket.cpp

@@ -125,8 +125,7 @@ void CControlSocket::ShowStatus(CString status, int type) const
 		for (int i=0;i<len;i++)
 			status+="*";
 	}
-	status.Replace(_T("%"), _T("%%"));
-	LogMessage(type, (LPCTSTR)status);
+	LogMessageRaw(type, (LPCTSTR)status);
 }
 
 
@@ -216,7 +215,7 @@ int CControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
 #ifndef MPEXT_NO_GSS
 			else if (iter->pLayer == m_pGssLayer)
 				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pGssLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
-#endif        
+#endif
 			else
 				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %d to %d"), iter->pLayer, iter->nParam2, iter->nParam1);
 		}
@@ -256,10 +255,10 @@ int CControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
 				switch (iter->nParam1)
 				{
 				case GSS_INFO:
-					LogMessage(FZ_LOG_INFO, A2CT(iter->str));
+					LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
 					break;
 				case GSS_ERROR:
-					LogMessage(FZ_LOG_APIERROR, A2CT(iter->str));
+					LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
 					break;
 				case GSS_COMMAND:
 					ShowStatus(A2CT(iter->str), 2);
@@ -269,7 +268,7 @@ int CControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
 					break;
 				}
 			}
-#endif      
+#endif
 		}
 
 		delete [] iter->str;
@@ -487,7 +486,7 @@ CString CControlSocket::ConvertDomainName(CString domain)
 
 	char *output = 0;
 #ifdef MPEXT
-  output = strdup(utf8); 
+	output = strdup(utf8);
 #else
 	if (idna_to_ascii_8z(utf8, &output, IDNA_ALLOW_UNASSIGNED))
 	{

+ 0 - 1
filezilla/Crypt.cpp

@@ -79,4 +79,3 @@ CString CCrypt::decrypt(CString str)
 	}
 	return ret;
 }
-

+ 1 - 1
filezilla/FileZillaApi.cpp

@@ -153,7 +153,7 @@ int CFileZillaApi::Connect(const t_server &server)
 	}
 	if (!bUseGSS && server.user == "")
 		return FZ_REPLY_INVALIDPARAM;
-#endif    
+#endif
 		
 	if (!(server.nServerType&FZ_SERVERTYPE_HIGHMASK))
 		return FZ_REPLY_INVALIDPARAM;

+ 5 - 19
filezilla/FileZillaIntern.cpp

@@ -1,4 +1,3 @@
-//!!!
 //---------------------------------------------------------------------------
 #include "stdafx.h"
 //---------------------------------------------------------------------------
@@ -22,26 +21,13 @@ BOOL TFileZillaIntern::PostMessage(HWND hWnd, UINT Msg, WPARAM wParam,
 
   bool Result;
   unsigned int MessageID = FZ_MSG_ID(wParam);
-  
+
   switch (MessageID)
   {
-    // TODO !!! separated temporarily to ease debugging  
     case FZ_MSG_STATUS:
-      Result = FOwner->PostMessage(wParam, lParam);
-      break;
-
-    case FZ_MSG_ASYNCREQUEST:  
-      Result = FOwner->PostMessage(wParam, lParam);
-      break;
-
+    case FZ_MSG_ASYNCREQUEST:
     case FZ_MSG_LISTDATA:
-      Result = FOwner->PostMessage(wParam, lParam);
-      break;
-
-    case FZ_MSG_TRANSFERSTATUS:  
-      Result = FOwner->PostMessage(wParam, lParam);
-      break;
-
+    case FZ_MSG_TRANSFERSTATUS:
     case FZ_MSG_REPLY:
       Result = FOwner->PostMessage(wParam, lParam);
       break;
@@ -57,7 +43,7 @@ BOOL TFileZillaIntern::PostMessage(HWND hWnd, UINT Msg, WPARAM wParam,
       ASSERT(lParam == 0);
       Result = false;
       break;
-    
+
     // should never get here, call compiled out in filezilla code
     case FZ_MSG_QUITCOMPLETE:
     default:
@@ -65,7 +51,7 @@ BOOL TFileZillaIntern::PostMessage(HWND hWnd, UINT Msg, WPARAM wParam,
       Result = false;
       break;
   }
-      
+
   return (Result ? TRUE : FALSE);
 }
 //---------------------------------------------------------------------------

+ 5172 - 5174
filezilla/FtpControlSocket.cpp

@@ -46,88 +46,88 @@ static char THIS_FILE[] = __FILE__;
 class CFtpControlSocket::CFileTransferData : public CFtpControlSocket::t_operation::COpData
 {
 public:
-    CFileTransferData()
-    {
-        pDirectoryListing=0;
-        nGotTransferEndReply=0;
-        nWaitNextOpState=0;
-        nMKDOpState=-1;
-        pFileTime=0;
-        pFileSize=0;
-        bUseAbsolutePaths = FALSE;
-        bTriedPortPasvOnce = FALSE;
-        askOnResumeFail = false;
-    };
-    ~CFileTransferData()
-    {
-        if (pDirectoryListing)
-            delete pDirectoryListing;
-        pDirectoryListing=0;
-        delete pFileSize;
-        delete pFileTime;
-    };
-    CString rawpwd;
-    t_transferfile transferfile;
-    t_transferdata transferdata;
-    CString host;
-    int port;
-    BOOL bPasv;
-    int nGotTransferEndReply;
-    t_directory *pDirectoryListing;
-    int nWaitNextOpState;
-    CServerPath MKDCurrent;
-    std::list<CString> MKDSegments;
-    int nMKDOpState;
-    CTime ListStartTime;
-    CTime *pFileTime; //Used when downloading and OPTION_PRESERVEDOWNLOADFILETIME is set or when LIST fails
-    _int64 *pFileSize; //Used when LIST failes
-    BOOL bUseAbsolutePaths;
-    BOOL bTriedPortPasvOnce;
+	CFileTransferData()
+	{
+		pDirectoryListing=0;
+		nGotTransferEndReply=0;
+		nWaitNextOpState=0;
+		nMKDOpState=-1;
+		pFileTime=0;
+		pFileSize=0;
+		bUseAbsolutePaths = FALSE;
+		bTriedPortPasvOnce = FALSE;
+		askOnResumeFail = false;
+	};
+	~CFileTransferData()
+	{
+		if (pDirectoryListing)
+			delete pDirectoryListing;
+		pDirectoryListing=0;
+		delete pFileSize;
+		delete pFileTime;
+	};
+	CString rawpwd;
+	t_transferfile transferfile;
+	t_transferdata transferdata;
+	CString host;
+	int port;
+	BOOL bPasv;
+	int nGotTransferEndReply;
+	t_directory *pDirectoryListing;
+	int nWaitNextOpState;
+	CServerPath MKDCurrent;
+	std::list<CString> MKDSegments;
+	int nMKDOpState;
+	CTime ListStartTime;
+	CTime *pFileTime; //Used when downloading and OPTION_PRESERVEDOWNLOADFILETIME is set or when LIST fails
+	_int64 *pFileSize; //Used when LIST failes
+	BOOL bUseAbsolutePaths;
+	BOOL bTriedPortPasvOnce;
 #ifndef MPEXT_NO_ZLIB
-    int newZlibLevel;
+	int newZlibLevel;
 #endif
-    bool askOnResumeFail;
+	bool askOnResumeFail;
 };
 
 class CFtpControlSocket::CListData:public CFtpControlSocket::t_operation::COpData
 {
 public:
-    CListData()
-    {
-        pDirectoryListing = 0;
-        bTriedPortPasvOnce = FALSE;
-        lastCmdSentCDUP = false;
-    }
-    virtual ~CListData()
-    {
-        if (pDirectoryListing)
-            delete pDirectoryListing;
-    }
-    CString rawpwd;
-    CServerPath path;
-    CString subdir;
-    int nListMode;
-    BOOL bPasv;
-    CString host;
-    UINT port;
-    int nFinish;
-    t_directory *pDirectoryListing;
-    CTime ListStartTime;
-    BOOL bTriedPortPasvOnce;
+	CListData()
+	{
+		pDirectoryListing = 0;
+		bTriedPortPasvOnce = FALSE;
+		lastCmdSentCDUP = false;
+	}
+	virtual ~CListData()
+	{
+		if (pDirectoryListing)
+			delete pDirectoryListing;
+	}
+	CString rawpwd;
+	CServerPath path;
+	CString subdir;
+	int nListMode;
+	BOOL bPasv;
+	CString host;
+	UINT port;
+	int nFinish;
+	t_directory *pDirectoryListing;
+	CTime ListStartTime;
+	BOOL bTriedPortPasvOnce;
 #ifndef MPEXT_NO_ZLIB
-    int newZlibLevel;
+	int newZlibLevel;
 #endif
-    bool lastCmdSentCDUP;
+	bool lastCmdSentCDUP;
 };
 
 class CFtpControlSocket::CMakeDirData : public CFtpControlSocket::t_operation::COpData
 {
 public:
-    CMakeDirData() {}
-    virtual ~CMakeDirData() {}
-    CServerPath path;
-    CServerPath Current;
-    std::list<CString> Segments;
+	CMakeDirData() {}
+	virtual ~CMakeDirData() {}
+	CServerPath path;
+	CServerPath Current;
+	std::list<CString> Segments;
 };
 
 #define MKD_INIT -1
@@ -140,57 +140,57 @@ public:
 
 CFtpControlSocket::CFtpControlSocket(CMainThread *pMainThread) : CControlSocket(pMainThread)
 {
-    ASSERT(pMainThread);
-    m_Operation.nOpMode=0;
-    m_Operation.nOpState=-1;
-    m_Operation.pData=0;
-    m_pTransferSocket=0;
-    m_pDataFile=0;
-    m_pDirectoryListing=0;
-    m_pOwner=pMainThread;
-    srand( (unsigned)time( NULL ) );
-    m_bKeepAliveActive=FALSE;
-    m_bCheckForTimeout=TRUE;
+	ASSERT(pMainThread);
+	m_Operation.nOpMode=0;
+	m_Operation.nOpState=-1;
+	m_Operation.pData=0;
+	m_pTransferSocket=0;
+	m_pDataFile=0;
+	m_pDirectoryListing=0;
+	m_pOwner=pMainThread;
+	srand( (unsigned)time( NULL ) );
+	m_bKeepAliveActive=FALSE;
+	m_bCheckForTimeout=TRUE;
 #ifndef MPEXT_NO_SSL
-    m_bDidRejectCertificate = FALSE;
+	m_bDidRejectCertificate = FALSE;
 #endif
 
 #ifndef MPEXT_NO_ZLIB
-    m_useZlib = false;
-    m_zlibSupported = false;
-    m_zlibLevel = 8;
+	m_useZlib = false;
+	m_zlibSupported = false;
+	m_zlibLevel = 8;
 #endif
 
-    m_bUTF8 = true;
-    m_hasClntCmd = false;
+	m_bUTF8 = true;
+	m_hasClntCmd = false;
 
-    m_awaitsReply = false;
-    m_skipReply = false;
+	m_awaitsReply = false;
+	m_skipReply = false;
 
-    m_sendBuffer = 0;
-    m_sendBufferLen = 0;
+	m_sendBuffer = 0;
+	m_sendBufferLen = 0;
 
-    m_bProtP = false;
+	m_bProtP = false;
 
-    m_mayBeMvsFilesystem = false;
-    m_mayBeBS2000Filesystem = false;
+	m_mayBeMvsFilesystem = false;
+	m_mayBeBS2000Filesystem = false;
 }
 
 CFtpControlSocket::~CFtpControlSocket()
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("~CFtpControlSocket()"));
-    DoClose();
-    if (m_pTransferSocket)
-    {
-        m_pTransferSocket->Close();
-        delete m_pTransferSocket;
-        m_pTransferSocket=0;
-    }
-    if (m_pDataFile)
-    {
-        delete m_pDataFile;
-        m_pDataFile=0;
-    }
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("~CFtpControlSocket()"));
+	DoClose();
+	if (m_pTransferSocket)
+	{
+		m_pTransferSocket->Close();
+		delete m_pTransferSocket;
+		m_pTransferSocket=0;
+	}
+	if (m_pDataFile)
+	{
+		delete m_pDataFile;
+		m_pDataFile=0;
+	}
 }
 
 /////////////////////////////////////////////////////////////////////////////
@@ -218,5496 +218,5494 @@ CFtpControlSocket::~CFtpControlSocket()
 
 bool CFtpControlSocket::InitConnect()
 {
-    USES_CONVERSION;
-
-    // Reset detected capabilities
-    m_bAnnouncesUTF8 = false;
-    m_hasClntCmd = false;
-    m_isFileZilla = false;
-
-    if (m_CurrentServer.nUTF8 == 2)
-        m_bUTF8 = false;
-    else
-        m_bUTF8 = true;
-
-    // Some sanity checks
-    if (m_pOwner->IsConnected())
-    {
-        ShowStatus(_T("Internal error: Connect called while still connected"), 1);
-        if (!m_Operation.nOpMode)
-            m_Operation.nOpMode = CSMODE_CONNECT;
-        DoClose(FZ_REPLY_CRITICALERROR);
-        return false;
-    }
+	USES_CONVERSION;
+
+	// Reset detected capabilities
+	m_bAnnouncesUTF8 = false;
+	m_hasClntCmd = false;
+	m_isFileZilla = false;
+
+	if (m_CurrentServer.nUTF8 == 2)
+		m_bUTF8 = false;
+	else
+		m_bUTF8 = true;
+
+	// Some sanity checks
+	if (m_pOwner->IsConnected())
+	{
+		ShowStatus(_T("Internal error: Connect called while still connected"), 1);
+		if (!m_Operation.nOpMode)
+			m_Operation.nOpMode = CSMODE_CONNECT;
+		DoClose(FZ_REPLY_CRITICALERROR);
+		return false;
+	}
 
 #ifndef MPEXT_NO_SSL
-    if (m_pSslLayer)
-    {
-        ShowStatus(_T("Internal error: m_pSslLayer not zero in Connect"), 1);
-        DoClose(FZ_REPLY_CRITICALERROR);
-        return false;
-    }
+	if (m_pSslLayer)
+	{
+		ShowStatus(_T("Internal error: m_pSslLayer not zero in Connect"), 1);
+		DoClose(FZ_REPLY_CRITICALERROR);
+		return false;
+	}
 #endif
-    if (m_pProxyLayer)
-    {
-        ShowStatus(_T("Internal error: m_pProxyLayer not zero in Connect"), 1);
-        DoClose(FZ_REPLY_CRITICALERROR);
-        return false;
-    }
+	if (m_pProxyLayer)
+	{
+		ShowStatus(_T("Internal error: m_pProxyLayer not zero in Connect"), 1);
+		DoClose(FZ_REPLY_CRITICALERROR);
+		return false;
+	}
 
 #ifndef MPEXT_NO_SSL
-    if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT ||
-        m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT ||
-        m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_TLS_EXPLICIT)
-    {
-        m_pSslLayer = new CAsyncSslSocketLayer;
-        AddLayer(m_pSslLayer);
-        TCHAR buffer[1000];
-        GetModuleFileName(NULL, buffer, 1000);
-        CString filename = buffer;
-        int pos = filename.ReverseFind('\\');
-        if (pos != -1)
-        {
-            filename = filename.Left(pos + 1);
-            filename += _T("cacert.pem");
-            m_pSslLayer->SetCertStorage(filename);
-        }
-        else
-            filename = "cacert.pem";
-    }
+	if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT ||
+		m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT ||
+		m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_TLS_EXPLICIT)
+	{
+		m_pSslLayer = new CAsyncSslSocketLayer;
+		AddLayer(m_pSslLayer);
+		TCHAR buffer[1000];
+		GetModuleFileName(NULL, buffer, 1000);
+		CString filename = buffer;
+		int pos = filename.ReverseFind('\\');
+		if (pos != -1)
+		{
+			filename = filename.Left(pos + 1);
+			filename += _T("cacert.pem");
+			m_pSslLayer->SetCertStorage(filename);
+		}
+		else
+			filename = "cacert.pem";
+	}
 #endif
 
-    if (!m_CurrentServer.fwbypass)
-    {
-        int nProxyType = COptions::GetOptionVal(OPTION_PROXYTYPE);
-        if (nProxyType != PROXYTYPE_NOPROXY)
-        {
-            m_pProxyLayer = new CAsyncProxySocketLayer;
-            if (nProxyType == PROXYTYPE_SOCKS4)
-                m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
-            else if (nProxyType==PROXYTYPE_SOCKS4A)
-                m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(COptions::GetOption(OPTION_PROXYHOST)),COptions::GetOptionVal(OPTION_PROXYPORT));
-            else if (nProxyType==PROXYTYPE_SOCKS5)
-                if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
-                    m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
-                                            COptions::GetOptionVal(OPTION_PROXYPORT),
-                                            T2CA(COptions::GetOption(OPTION_PROXYUSER)),
-                                            T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
-                else
-                    m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
-                                            COptions::GetOptionVal(OPTION_PROXYPORT));
-            else if (nProxyType==PROXYTYPE_HTTP11)
-                if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
-                    m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
-                                            COptions::GetOptionVal(OPTION_PROXYPORT),
-                                            T2CA(COptions::GetOption(OPTION_PROXYUSER)),
-                                            T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
-                else
-                    m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)) ,COptions::GetOptionVal(OPTION_PROXYPORT));
-            else
-                ASSERT(FALSE);
-            AddLayer(m_pProxyLayer);
-        }
-    }
+	if (!m_CurrentServer.fwbypass)
+	{
+		int nProxyType = COptions::GetOptionVal(OPTION_PROXYTYPE);
+		if (nProxyType != PROXYTYPE_NOPROXY)
+		{
+			m_pProxyLayer = new CAsyncProxySocketLayer;
+			if (nProxyType == PROXYTYPE_SOCKS4)
+				m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
+			else if (nProxyType==PROXYTYPE_SOCKS4A)
+				m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(COptions::GetOption(OPTION_PROXYHOST)),COptions::GetOptionVal(OPTION_PROXYPORT));
+			else if (nProxyType==PROXYTYPE_SOCKS5)
+				if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
+					m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
+											COptions::GetOptionVal(OPTION_PROXYPORT),
+											T2CA(COptions::GetOption(OPTION_PROXYUSER)),
+											T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
+				else
+					m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
+											COptions::GetOptionVal(OPTION_PROXYPORT));
+			else if (nProxyType==PROXYTYPE_HTTP11)
+				if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
+					m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
+											COptions::GetOptionVal(OPTION_PROXYPORT),
+											T2CA(COptions::GetOption(OPTION_PROXYUSER)),
+											T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
+				else
+					m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)) ,COptions::GetOptionVal(OPTION_PROXYPORT));
+			else
+				ASSERT(FALSE);
+			AddLayer(m_pProxyLayer);
+		}
+	}
 
 #ifndef MPEXT_NO_GSS
-    BOOL bUseGSS = FALSE;
-    if (COptions::GetOptionVal(OPTION_USEGSS)
+	BOOL bUseGSS = FALSE;
+	if (COptions::GetOptionVal(OPTION_USEGSS)
 #ifndef MPEXT_NO_SSL
-        && !m_pSslLayer
+		&& !m_pSslLayer
 #endif
-  )
-    {
-        CString GssServers=COptions::GetOption(OPTION_GSSSERVERS);
-        LPCSTR lpszAscii=T2CA(m_CurrentServer.host);
-        hostent *fullname=gethostbyname(lpszAscii);
-        CString host;
-        if (fullname)
-            host=fullname->h_name;
-        else
-            host=m_CurrentServer.host;
-        host.MakeLower();
-        int i;
-        while ((i=GssServers.Find(_T(";")))!=-1)
-        {
-            if (("."+GssServers.Left(i))==host.Right(GssServers.Left(i).GetLength()+1) || GssServers.Left(i)==host)
-            {
-                bUseGSS=TRUE;
-                break;
-            }
-            GssServers=GssServers.Mid(i+1);
-        }
-    }
-    if (bUseGSS)
-    {
-        m_pGssLayer = new CAsyncGssSocketLayer;
-        AddLayer(m_pGssLayer);
-        if (!m_pGssLayer->InitGSS())
-        {
-            ShowStatus(_T("Unable to initialize GSS api"), 1);
-            DoClose(FZ_REPLY_CRITICALERROR);
-            return false;
-        }
-    }
+	)
+	{
+		CString GssServers=COptions::GetOption(OPTION_GSSSERVERS);
+		LPCSTR lpszAscii=T2CA(m_CurrentServer.host);
+		hostent *fullname=gethostbyname(lpszAscii);
+		CString host;
+		if (fullname)
+			host=fullname->h_name;
+		else
+			host=m_CurrentServer.host;
+		host.MakeLower();
+		int i;
+		while ((i=GssServers.Find(_T(";")))!=-1)
+		{
+			if (("."+GssServers.Left(i))==host.Right(GssServers.Left(i).GetLength()+1) || GssServers.Left(i)==host)
+			{
+				bUseGSS=TRUE;
+				break;
+			}
+			GssServers=GssServers.Mid(i+1);
+		}
+	}
+	if (bUseGSS)
+	{
+		m_pGssLayer = new CAsyncGssSocketLayer;
+		AddLayer(m_pGssLayer);
+		if (!m_pGssLayer->InitGSS())
+		{
+			ShowStatus(_T("Unable to initialize GSS api"), 1);
+			DoClose(FZ_REPLY_CRITICALERROR);
+			return false;
+		}
+	}
 #endif
 
-    return true;
+	return true;
 }
 
 void CFtpControlSocket::Connect(t_server &server)
 {
-    USES_CONVERSION;
-
-    if (m_Operation.nOpMode)
-    {
-        ShowStatus(_T("Internal error: m_Operation.nOpMode not zero in Connect"), 1);
-        m_Operation.nOpMode = CSMODE_CONNECT;
-        DoClose(FZ_REPLY_CRITICALERROR);
-        return;
-    }
-
-    m_Operation.nOpMode = CSMODE_CONNECT;
-
-    m_CurrentServer = server;
-    if (!InitConnect())
-        return;
-
-    if (!Create())
-    {
-        DoClose();
-        return;
-    }
-    AsyncSelect();
-
-    m_Operation.nOpState =
+	USES_CONVERSION;
+
+	if (m_Operation.nOpMode)
+	{
+		ShowStatus(_T("Internal error: m_Operation.nOpMode not zero in Connect"), 1);
+		m_Operation.nOpMode = CSMODE_CONNECT;
+		DoClose(FZ_REPLY_CRITICALERROR);
+		return;
+	}
+
+	m_Operation.nOpMode = CSMODE_CONNECT;
+
+	m_CurrentServer = server;
+	if (!InitConnect())
+		return;
+	
+	if (!Create())
+	{
+		DoClose();
+		return;
+	}
+	AsyncSelect();
+
+	m_Operation.nOpState =
 #ifndef MPEXT_NO_GSS
-    m_pGssLayer ? CONNECT_GSS_INIT :
+	m_pGssLayer ? CONNECT_GSS_INIT :
 #endif
-    CONNECT_INIT;
+	CONNECT_INIT;
 
 #ifndef MPEXT_NO_SSL
-    if (server.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT)
-    {
-        if (!m_pSslLayer)
-        {
-            ShowStatus(_T("Internal error: m_pSslLayer not initialized"), 1);
-            DoClose(FZ_REPLY_CRITICALERROR);
-            return;
-        }
-        int res = m_pSslLayer->InitSSLConnection(true);
-        if (res == SSL_FAILURE_LOADDLLS)
-            ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
-        else if (res == SSL_FAILURE_INITSSL)
-            ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
-        if (!res)
-            PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, 1), 0);
-        else
-        {
-            DoClose();
-            return;
-        }
-    }
+	if (server.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT)
+	{
+		if (!m_pSslLayer)
+		{
+			ShowStatus(_T("Internal error: m_pSslLayer not initialized"), 1);
+			DoClose(FZ_REPLY_CRITICALERROR);
+			return;
+		}
+		int res = m_pSslLayer->InitSSLConnection(true);
+		if (res == SSL_FAILURE_LOADDLLS)
+			ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
+		else if (res == SSL_FAILURE_INITSSL)
+			ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
+		if (!res)
+			PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, 1), 0);
+		else
+		{
+			DoClose();
+			return;
+		}
+	}
 #endif
 
-    int logontype = COptions::GetOptionVal(OPTION_LOGONTYPE);
-    int port;
-    CString buf,temp;
-    if (server.fwbypass)
-        logontype=0;
-
-    // are we connecting directly to the host (logon type 0) or via a firewall? (logon type>0)
-    CString fwhost;
-    int fwport;
-    if(!logontype)
-    {
-        temp=server.host;
-        port=server.port;
-    }
-    else
-    {
-        fwhost=COptions::GetOption(OPTION_FWHOST);
-        fwport=COptions::GetOptionVal(OPTION_FWPORT);
-        temp=fwhost;
-        port=fwport;
-        if(fwport!=21)
-            fwhost.Format( _T("%s:%d"), fwhost, fwport); // add port to fwhost (only if port is not 21)
-    }
-
-    CString hostname = server.host;
-    if(server.port!=21)
-        hostname.Format( _T("%s:%d"), hostname, server.port); // add port to hostname (only if port is not 21)
-    CString str;
-    str.Format(IDS_STATUSMSG_CONNECTING, hostname);
-    ShowStatus(str, 0);
+	int logontype = COptions::GetOptionVal(OPTION_LOGONTYPE);
+	int port;
+	CString buf,temp;
+	if (server.fwbypass)
+		logontype=0;
+
+	// are we connecting directly to the host (logon type 0) or via a firewall? (logon type>0)
+	CString fwhost;
+	int fwport;
+	if(!logontype)
+	{
+		temp=server.host;
+		port=server.port;
+	}
+	else
+	{
+		fwhost=COptions::GetOption(OPTION_FWHOST);
+		fwport=COptions::GetOptionVal(OPTION_FWPORT);
+		temp=fwhost;
+		port=fwport;
+		if(fwport!=21)
+			fwhost.Format( _T("%s:%d"), fwhost, fwport); // add port to fwhost (only if port is not 21)
+	}
+
+	CString hostname = server.host;
+	if(server.port!=21)
+		hostname.Format( _T("%s:%d"), hostname, server.port); // add port to hostname (only if port is not 21)
+	CString str;
+	str.Format(IDS_STATUSMSG_CONNECTING, hostname);
+	ShowStatus(str, 0);
 
 #ifndef MPEXT_NO_SSL
-    if ((server.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
-        m_Operation.nOpState = CONNECT_SSL_INIT;
+	if ((server.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
+		m_Operation.nOpState = CONNECT_SSL_INIT;
 #endif
 
-    if (!CControlSocket::Connect(temp, port))
-    {
-        if (WSAGetLastError() != WSAEWOULDBLOCK)
-        {
-            DoClose();
-            return;
-        }
-    }
-    m_ServerName = logontype?fwhost:hostname;
-    m_LastRecvTime = m_LastSendTime = CTime::GetCurrentTime();
+	if (!CControlSocket::Connect(temp, port))
+	{
+		if (WSAGetLastError() != WSAEWOULDBLOCK)
+		{
+			DoClose();
+			return;
+		}
+	}
+	m_ServerName = logontype?fwhost:hostname;
+	m_LastRecvTime = m_LastSendTime = CTime::GetCurrentTime();
 }
 
 void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/)
 {
-    int logontype =
+	int logontype =
 #ifndef MPEXT_NO_GSS
-    m_pGssLayer ? 0 :
+	m_pGssLayer ? 0 :
 #endif
-    COptions::GetOptionVal(OPTION_LOGONTYPE);
-    const int LO = -2, ER = -1;
-    CString buf, temp;
-    const int NUMLOGIN = 9; // currently supports 9 different login sequences
-    int logonseq[NUMLOGIN][20] = {
-        // this array stores all of the logon sequences for the various firewalls
-        // in blocks of 3 nums. 1st num is command to send, 2nd num is next point in logon sequence array
-        // if 200 series response is rec'd from server as the result of the command, 3rd num is next
-        // point in logon sequence if 300 series rec'd
-        {0,LO,3, 1,LO,6,  12,LO,ER}, // no firewall
-        {3,6,3,  4,6,ER, 5,9,9, 0,LO,12, 1,LO,15, 12,LO,ER}, // SITE hostname
-        {3,6,3,  4,6,ER, 6,LO,9, 1,LO,12, 12,LO,ER}, // USER after logon
-        {7,3,3,  0,LO,6, 1,LO,9, 12,LO,ER}, //proxy OPEN
-        {3,6,3,  4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, // Transparent
-        {6,LO,3, 1,LO,6, 12,LO,ER}, // USER remoteID@remotehost
-        {8,6,3,  4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, //USER fireID@remotehost
-        {9,ER,3, 1,LO,6, 2,LO,ER}, //USER remoteID@remotehost fireID
-        {10,LO,3,11,LO,6,2,LO,ER} // USER remoteID@fireID@remotehost
-    };
-    if (m_CurrentServer.fwbypass)
-        logontype = 0;
+	COptions::GetOptionVal(OPTION_LOGONTYPE);
+	const int LO = -2, ER = -1;
+	CString buf, temp;
+	const int NUMLOGIN = 9; // currently supports 9 different login sequences
+	int logonseq[NUMLOGIN][20] = {
+		// this array stores all of the logon sequences for the various firewalls
+		// in blocks of 3 nums. 1st num is command to send, 2nd num is next point in logon sequence array
+		// if 200 series response is rec'd from server as the result of the command, 3rd num is next
+		// point in logon sequence if 300 series rec'd
+		{0,LO,3, 1,LO,6,  12,LO,ER}, // no firewall
+		{3,6,3,  4,6,ER, 5,9,9, 0,LO,12, 1,LO,15, 12,LO,ER}, // SITE hostname
+		{3,6,3,  4,6,ER, 6,LO,9, 1,LO,12, 12,LO,ER}, // USER after logon
+		{7,3,3,  0,LO,6, 1,LO,9, 12,LO,ER}, //proxy OPEN
+		{3,6,3,  4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, // Transparent
+		{6,LO,3, 1,LO,6, 12,LO,ER}, // USER remoteID@remotehost
+		{8,6,3,  4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, //USER fireID@remotehost
+		{9,ER,3, 1,LO,6, 2,LO,ER}, //USER remoteID@remotehost fireID
+		{10,LO,3,11,LO,6,2,LO,ER} // USER remoteID@fireID@remotehost
+	};
+	if (m_CurrentServer.fwbypass)
+		logontype = 0;
 
 #ifndef MPEXT_NO_SSL
-    if (m_Operation.nOpState == CONNECT_SSL_INIT)
-    {
-        if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT)
-        {
-            if (!Send("AUTH SSL"))
-                return;
-        }
-        else
-        {
-            if (!Send("AUTH TLS"))
-                return;
-        }
-        m_Operation.nOpState = CONNECT_SSL_NEGOTIATE;
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_SSL_NEGOTIATE)
-    {
-        int res = GetReplyCode();
-        if (res!=2 && res!=3)
-        {
-            DoClose();
-            return;
-        }
-        else
-        {
-            if (!m_pSslLayer)
-            {
-                ShowStatus(_T("Internal error: m_pSslLayer not initialized"), 1);
-                DoClose(FZ_REPLY_CRITICALERROR);
-                return;
-            }
-            int res = m_pSslLayer->InitSSLConnection(true);
-            if (res == SSL_FAILURE_LOADDLLS)
-                ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
-            else if (res == SSL_FAILURE_INITSSL)
-                ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
-            if (res)
-            {
-                DoClose();
-                return;
-            }
-        }
-        m_Operation.nOpState = CONNECT_SSL_WAITDONE;
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
-    {
-        m_Operation.nOpState = CONNECT_INIT;
-    }
-    else if (m_Operation.nOpState == CONNECT_SSL_PBSZ)
-    {
-        if (!Send("PROT P"))
-            return;
-        m_Operation.nOpState = CONNECT_SSL_PROT;
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_SSL_PROT)
-    {
-        int code = GetReplyCode();
-        if (code == 2 || code == 3)
-            m_bProtP = true;
-
-        ShowStatus(IDS_STATUSMSG_CONNECTED, 0);
-        m_pOwner->SetConnected(TRUE);
-        ResetOperation(FZ_REPLY_OK);
-        return;
-    }
+	if (m_Operation.nOpState == CONNECT_SSL_INIT)
+	{
+		if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT)
+		{
+			if (!Send("AUTH SSL"))
+				return;
+		}
+		else
+		{
+			if (!Send("AUTH TLS"))
+				return;
+		}
+		m_Operation.nOpState = CONNECT_SSL_NEGOTIATE;
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_SSL_NEGOTIATE)
+	{
+		int res = GetReplyCode();
+		if (res!=2 && res!=3)
+		{
+			DoClose();
+			return;
+		}
+		else
+		{
+			if (!m_pSslLayer)
+			{
+				ShowStatus(_T("Internal error: m_pSslLayer not initialized"), 1);
+				DoClose(FZ_REPLY_CRITICALERROR);
+				return;
+			}
+			int res = m_pSslLayer->InitSSLConnection(true);
+			if (res == SSL_FAILURE_LOADDLLS)
+				ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
+			else if (res == SSL_FAILURE_INITSSL)
+				ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
+			if (res)
+			{
+				DoClose();
+				return;
+			}
+		}
+		m_Operation.nOpState = CONNECT_SSL_WAITDONE;
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
+	{
+		m_Operation.nOpState = CONNECT_INIT;
+	}
+	else if (m_Operation.nOpState == CONNECT_SSL_PBSZ)
+	{
+		if (!Send("PROT P"))
+			return;
+		m_Operation.nOpState = CONNECT_SSL_PROT;
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_SSL_PROT)
+	{
+		int code = GetReplyCode();
+		if (code == 2 || code == 3)
+			m_bProtP = true;
+
+		ShowStatus(IDS_STATUSMSG_CONNECTED, 0);
+		m_pOwner->SetConnected(TRUE);
+		ResetOperation(FZ_REPLY_OK);
+		return;
+	}
 #ifndef MPEXT_NO_GSS
-    else
+	else
 #endif
 #endif
 #ifndef MPEXT_NO_GSS
-    if (m_Operation.nOpState==CONNECT_GSS_FAILED ||
-             m_Operation.nOpState == CONNECT_GSS_NEEDPASS ||
-             m_Operation.nOpState == CONNECT_GSS_NEEDUSER)
-    {
-        if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
-        {
-            //Incoming reply from server during async is not allowed
-            DoClose();
-            return;
-        }
-    }
+	if (m_Operation.nOpState==CONNECT_GSS_FAILED ||
+			 m_Operation.nOpState == CONNECT_GSS_NEEDPASS ||
+			 m_Operation.nOpState == CONNECT_GSS_NEEDUSER)
+	{
+		if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
+		{
+			//Incoming reply from server during async is not allowed
+			DoClose();
+			return;
+		}
+	}
 #endif
-    else if (m_Operation.nOpState == CONNECT_FEAT)
-    {
-        if (!m_bAnnouncesUTF8 && !m_CurrentServer.nUTF8)
-            m_bUTF8 = false;
-        if (m_bUTF8 && m_hasClntCmd && !m_isFileZilla)
-        {
-            // Some servers refuse to enable UTF8 if client does not send CLNT command
-            // to fix compatibility with Internet Explorer, but in the process breaking
-            // compatibility with other clients.
-            // Rather than forcing MS to fix Internet Explorer, letting other clients
-            // suffer is a questionable decision in my opinion.
-            if (Send("CLNT FileZilla"))
-                m_Operation.nOpState = CONNECT_CLNT;
-            return;
-        }
-        if (m_bUTF8 && !m_isFileZilla)
-        {
-            // Handle servers that disobey RFC 2640 that have UTF8 in the FEAT
-            // response but do not use UTF8 unless OPTS UTF8 ON gets send.
-            // However these servers obey a conflicting ietf draft:
-            // http://www.ietf.org/proceedings/02nov/I-D/draft-ietf-ftpext-utf-8-option-00.txt
-            // servers are, amongst others, G6 FTP Server and RaidenFTPd.
-            if (Send("OPTS UTF8 ON"))
-                m_Operation.nOpState = CONNECT_OPTSUTF8;
-            return;
-        }
+	else if (m_Operation.nOpState == CONNECT_FEAT)
+	{
+		if (!m_bAnnouncesUTF8 && !m_CurrentServer.nUTF8)
+			m_bUTF8 = false;
+		if (m_bUTF8 && m_hasClntCmd && !m_isFileZilla)
+		{
+			// Some servers refuse to enable UTF8 if client does not send CLNT command
+			// to fix compatibility with Internet Explorer, but in the process breaking
+			// compatibility with other clients.
+			// Rather than forcing MS to fix Internet Explorer, letting other clients
+			// suffer is a questionable decision in my opinion.
+			if (Send("CLNT FileZilla"))
+				m_Operation.nOpState = CONNECT_CLNT;
+			return;
+		}
+		if (m_bUTF8 && !m_isFileZilla)
+		{
+			// Handle servers that disobey RFC 2640 that have UTF8 in the FEAT
+			// response but do not use UTF8 unless OPTS UTF8 ON gets send.
+			// However these servers obey a conflicting ietf draft:
+			// http://www.ietf.org/proceedings/02nov/I-D/draft-ietf-ftpext-utf-8-option-00.txt
+			// servers are, amongst others, G6 FTP Server and RaidenFTPd.
+			if (Send("OPTS UTF8 ON"))
+				m_Operation.nOpState = CONNECT_OPTSUTF8;
+			return;
+		}
 
 #ifndef MPEXT_NO_SSL
-        if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
-        {
-            m_Operation.nOpState = CONNECT_SSL_PBSZ;
-            Send("PBSZ 0");
-            return;
-        }
+		if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
+		{
+			m_Operation.nOpState = CONNECT_SSL_PBSZ;
+			Send("PBSZ 0");
+			return;
+		}
 #endif
 
-        ShowStatus(IDS_STATUSMSG_CONNECTED, 0);
-        m_pOwner->SetConnected(TRUE);
-        ResetOperation(FZ_REPLY_OK);
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_CLNT)
-    {
-        // See above why we send this command
-        if (Send("OPTS UTF8 ON"))
-            m_Operation.nOpState = CONNECT_OPTSUTF8;
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_OPTSUTF8)
-    {
+		ShowStatus(IDS_STATUSMSG_CONNECTED, 0);
+		m_pOwner->SetConnected(TRUE);
+		ResetOperation(FZ_REPLY_OK);
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_CLNT)
+	{
+		// See above why we send this command
+		if (Send("OPTS UTF8 ON"))
+			m_Operation.nOpState = CONNECT_OPTSUTF8;
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_OPTSUTF8)
+	{
 #ifndef MPEXT_NO_SSL
-        if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
-        {
-            m_Operation.nOpState = CONNECT_SSL_PBSZ;
-            Send("PBSZ 0");
-            return;
-        }
+		if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
+		{
+			m_Operation.nOpState = CONNECT_SSL_PBSZ;
+			Send("PBSZ 0");
+			return;
+		}
 #endif
 
-        ShowStatus(IDS_STATUSMSG_CONNECTED, 0);
-        m_pOwner->SetConnected(TRUE);
-        ResetOperation(FZ_REPLY_OK);
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_SYST)
-    {
-        if (GetReplyCode() == 2)
-        {
-            const CString reply = m_RecvBuffer.front();
-            if (reply.GetLength() > 7 && reply.Mid(3, 4) == " MVS")
-                m_mayBeMvsFilesystem = true;
-            else if (reply.GetLength() >= 11 && reply.Mid(3, 8) == " BS-2000")
-                m_mayBeBS2000Filesystem = true;
-
-            if (reply.Find(_T("FileZilla")) != -1)
-                m_isFileZilla = true;
-        }
-
-        if (Send("FEAT"))
-            m_Operation.nOpState = CONNECT_FEAT;
-        return;
-    }
-    else if (!bSkipReply)
-    {
-        int res = GetReplyCode();
-        if (res != 2 && res != 3 && m_Operation.nOpState >= 0) // get initial connect msg off server
-        {
-            int nError = 0;
-            if (m_bUTF8 && m_CurrentServer.nUTF8 != 1)
-            {
-                // Fall back to local charset for the case that the server might not
-                // support UTF8 and the login data contains non-ascii characters.
-                bool asciiOnly = true;
-                for (int i = 0; i < m_CurrentServer.user.GetLength(); i++)
-                    if (m_CurrentServer.user.GetAt(i) > 127)
-                        asciiOnly = false;
-                for (int i = 0; i < m_CurrentServer.pass.GetLength(); i++)
-                    if (m_CurrentServer.pass.GetAt(i) > 127)
-                        asciiOnly = false;
-                for (int i = 0; i < m_CurrentServer.account.GetLength(); i++)
-                    if (m_CurrentServer.account.GetAt(i) > 127)
-                        asciiOnly = false;
-                if (!asciiOnly)
-                {
-                    ShowStatus(_T("Login data contains non-ascii characters and server might not be UTF-8 aware. Trying local charset."), 0);
-                    m_bUTF8 = false;
-                    m_Operation.nOpState = CONNECT_INIT;
-                }
-                else
-                    nError = FZ_REPLY_ERROR;
-            }
-            else
-                nError = FZ_REPLY_ERROR;
-
-            if (nError)
-            {
-                if (res==5 && logonseq[logontype][m_Operation.nOpState]==1)
-                    nError|=FZ_REPLY_CRITICALERROR;
-
-                DoClose(nError);
-                return;
-            }
-        }
-    }
-    CString hostname = m_CurrentServer.host;
-    if (m_CurrentServer.port != 21)
-        hostname.Format(hostname+  ":%d", m_CurrentServer.port); // add port to hostname (only if port is not 21)
-
-    USES_CONVERSION;
+		ShowStatus(IDS_STATUSMSG_CONNECTED, 0);
+		m_pOwner->SetConnected(TRUE);
+		ResetOperation(FZ_REPLY_OK);
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_SYST)
+	{
+		if (GetReplyCode() == 2)
+		{
+			const CString reply = m_RecvBuffer.front();
+			if (reply.GetLength() > 7 && reply.Mid(3, 4) == " MVS")
+				m_mayBeMvsFilesystem = true;
+			else if (reply.GetLength() >= 11 && reply.Mid(3, 8) == " BS-2000")
+				m_mayBeBS2000Filesystem = true;
+
+			if (reply.Find(_T("FileZilla")) != -1)
+				m_isFileZilla = true;
+		}
+
+		if (Send("FEAT"))
+			m_Operation.nOpState = CONNECT_FEAT;
+		return;
+	}
+	else if (!bSkipReply)
+	{
+		int res = GetReplyCode();
+		if (res != 2 && res != 3 && m_Operation.nOpState >= 0) // get initial connect msg off server
+		{
+			int nError = 0;
+			if (m_bUTF8 && m_CurrentServer.nUTF8 != 1)
+			{
+				// Fall back to local charset for the case that the server might not
+				// support UTF8 and the login data contains non-ascii characters.
+				bool asciiOnly = true;
+				for (int i = 0; i < m_CurrentServer.user.GetLength(); i++)
+					if (m_CurrentServer.user.GetAt(i) > 127)
+						asciiOnly = false;
+				for (int i = 0; i < m_CurrentServer.pass.GetLength(); i++)
+					if (m_CurrentServer.pass.GetAt(i) > 127)
+						asciiOnly = false;
+				for (int i = 0; i < m_CurrentServer.account.GetLength(); i++)
+					if (m_CurrentServer.account.GetAt(i) > 127)
+						asciiOnly = false;
+				if (!asciiOnly)
+				{
+					ShowStatus(_T("Login data contains non-ascii characters and server might not be UTF-8 aware. Trying local charset."), 0);
+					m_bUTF8 = false;
+					m_Operation.nOpState = CONNECT_INIT;
+				}
+				else
+					nError = FZ_REPLY_ERROR;
+			}
+			else
+				nError = FZ_REPLY_ERROR;
+
+			if (nError)
+			{
+				if (res==5 && logonseq[logontype][m_Operation.nOpState]==1)
+					nError|=FZ_REPLY_CRITICALERROR;
+
+				DoClose(nError);
+				return;
+			}
+		}
+	}
+	CString hostname = m_CurrentServer.host;
+	if (m_CurrentServer.port != 21)
+		hostname.Format(hostname+  ":%d", m_CurrentServer.port); // add port to hostname (only if port is not 21)
+
+	USES_CONVERSION;
 #ifndef MPEXT_NO_GSS
-    //**** GSS Authentication ****
-    if (m_Operation.nOpState==CONNECT_GSS_INIT)  //authenticate
-    {
-        int i = m_pGssLayer->GetClientAuth(T2CA(m_CurrentServer.host));
-        if (i==-1)
-            m_Operation.nOpState = CONNECT_GSS_AUTHDONE;
-        else if (i != GSSAPI_AUTHENTICATION_SUCCEEDED)
-        {
-            m_Operation.nOpState = CONNECT_GSS_FAILED;
-            CAsyncRequestData *pData=new CAsyncRequestData;
-            pData->nRequestType=FZ_ASYNCREQUEST_GSS_AUTHFAILED;
-            pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
-            if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
-                delete pData;
-        }
-        else
-        {
-            // we got authentication, we need to check whether we have forwardable tickets
-            //ShowStatus(IDS_STATUSMSG_GSSAUTH, 0);
-            PostMessage(m_pOwner->m_hOwnerWnd,m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, TRUE), 0);
-            if (Send("CWD ."))
-                m_Operation.nOpState = CONNECT_GSS_CWD;
-        }
-        return;
-    }
-    else if (m_Operation.nOpState == CONNECT_GSS_AUTHDONE)
-    {
-        if (!m_pGssLayer->AuthSuccessful())
-        {
-            m_Operation.nOpState = CONNECT_GSS_FAILED;
-            CAsyncRequestData *pData=new CAsyncRequestData;
-            pData->nRequestType = FZ_ASYNCREQUEST_GSS_AUTHFAILED;
-            pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
-            if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
-                delete pData;
-            return;
-        }
-        else
-        {
-            // we got authentication, we need to check whether we have forwardable tickets
-            //ShowStatus(IDS_STATUSMSG_GSSAUTH, 0);
-            PostMessage(m_pOwner->m_hOwnerWnd,m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, TRUE), 0);
-            if (Send("CWD ."))
-                m_Operation.nOpState = CONNECT_GSS_CWD;
-            return;
-        }
-    }
-    else if (m_Operation.nOpState == CONNECT_GSS_CWD)
-    { // authentication succeeded, we're now get the response to the CWD command
-        if (GetReplyCode() == 2) // we're logged on
-        {
-            if (Send("SYST"))
-                m_Operation.nOpState = CONNECT_SYST;
-            return;
-        }
-        else
-            //GSS authentication complete but we still have to go through the standard logon procedure
-            m_Operation.nOpState = CONNECT_INIT;
-    }
+	//**** GSS Authentication ****
+	if (m_Operation.nOpState==CONNECT_GSS_INIT)  //authenticate
+	{
+		int	i = m_pGssLayer->GetClientAuth(T2CA(m_CurrentServer.host));
+		if (i==-1)
+			m_Operation.nOpState = CONNECT_GSS_AUTHDONE;
+		else if (i != GSSAPI_AUTHENTICATION_SUCCEEDED)
+		{
+			m_Operation.nOpState = CONNECT_GSS_FAILED;
+			CAsyncRequestData *pData=new CAsyncRequestData;
+			pData->nRequestType=FZ_ASYNCREQUEST_GSS_AUTHFAILED;
+			pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
+			if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
+				delete pData;
+		}
+		else
+		{
+			// we got authentication, we need to check whether we have forwardable tickets
+			//ShowStatus(IDS_STATUSMSG_GSSAUTH, 0);
+			PostMessage(m_pOwner->m_hOwnerWnd,m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, TRUE), 0);
+			if (Send("CWD ."))
+				m_Operation.nOpState = CONNECT_GSS_CWD;
+		}
+		return;
+	}
+	else if (m_Operation.nOpState == CONNECT_GSS_AUTHDONE)
+	{
+		if (!m_pGssLayer->AuthSuccessful())
+		{
+			m_Operation.nOpState = CONNECT_GSS_FAILED;
+			CAsyncRequestData *pData=new CAsyncRequestData;
+			pData->nRequestType = FZ_ASYNCREQUEST_GSS_AUTHFAILED;
+			pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
+			if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
+				delete pData;
+			return;
+		}
+		else
+		{
+			// we got authentication, we need to check whether we have forwardable tickets
+			//ShowStatus(IDS_STATUSMSG_GSSAUTH, 0);
+			PostMessage(m_pOwner->m_hOwnerWnd,m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, TRUE), 0);
+			if (Send("CWD ."))
+				m_Operation.nOpState = CONNECT_GSS_CWD;
+			return;
+		}
+	}
+	else if (m_Operation.nOpState == CONNECT_GSS_CWD)
+	{ // authentication succeeded, we're now get the response to the CWD command
+		if (GetReplyCode() == 2) // we're logged on
+		{
+			if (Send("SYST"))
+				m_Operation.nOpState = CONNECT_SYST;
+			return;
+		}
+		else
+			//GSS authentication complete but we still have to go through the standard logon procedure
+			m_Operation.nOpState = CONNECT_INIT;
+	}
 #endif
 
-    if (m_Operation.nOpState==CONNECT_INIT)
-    {
-        if (logontype)
-        {
-
-            CString str;
-            str.Format(IDS_STATUSMSG_FWCONNECT,hostname);
-            ShowStatus(str,0);
-        }
-        m_Operation.nOpState++;
-    }
-    else if (m_Operation.nOpState >= 0 && !bSkipReply)
-    {
-        m_Operation.nOpState=logonseq[logontype][m_Operation.nOpState+GetReplyCode()-1]; //get next command from array
-        switch(m_Operation.nOpState)
-        {
-        case ER: // ER means summat has gone wrong
-            DoClose();
-            return;
-        case LO: //LO means we are logged on
-            if (Send("SYST"))
-                m_Operation.nOpState = CONNECT_SYST;
-            return;
-        }
-    }
-
-    // go through appropriate logon procedure
+	if (m_Operation.nOpState==CONNECT_INIT)
+	{
+		if (logontype)
+		{
+
+			CString str;
+			str.Format(IDS_STATUSMSG_FWCONNECT,hostname);
+			ShowStatus(str,0);
+		}
+		m_Operation.nOpState++;
+	}
+	else if (m_Operation.nOpState >= 0 && !bSkipReply)
+	{
+		m_Operation.nOpState=logonseq[logontype][m_Operation.nOpState+GetReplyCode()-1]; //get next command from array
+		switch(m_Operation.nOpState)
+		{
+		case ER: // ER means summat has gone wrong
+			DoClose();
+			return;
+		case LO: //LO means we are logged on
+			if (Send("SYST"))
+				m_Operation.nOpState = CONNECT_SYST;
+			return;
+		}
+	}
+
+	// go through appropriate logon procedure
 #ifndef MPEXT_NO_GSS
-    int i = logonseq[logontype][m_Operation.nOpState];
-    if (m_pGssLayer)
-    {
-        if ((i == 0 || i == 6 || i == 9 || i == 10) &&
-            (m_CurrentServer.user == "anonymous" || m_CurrentServer.user == ""))
-        {
-            //Extract user from kerberos ticket
-            char str[256];
-            if (m_pGssLayer->GetUserFromKrbTicket(str))
-                m_CurrentServer.user = str;
-            if (m_CurrentServer.user == "")
-            {
-                CGssNeedUserRequestData *pData = new CGssNeedUserRequestData;
-                pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
-                pData->nOldOpState = m_Operation.nOpState;
-                m_Operation.nOpState = CONNECT_GSS_NEEDUSER;
-                if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), (LPARAM)pData))
-                    delete pData;
-                return;
-            }
-        }
-        else if ((i == 1 || i == 11) && (m_CurrentServer.pass == COptions::GetOption(OPTION_ANONPWD) || m_CurrentServer.pass == ""))
-        {
-            CGssNeedPassRequestData *pData=new CGssNeedPassRequestData;
-            pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
-            pData->nOldOpState = m_Operation.nOpState;
-            m_Operation.nOpState = CONNECT_GSS_NEEDPASS;
-            if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), (LPARAM)pData))
-                delete pData;
-            return;
-        }
-    }
+	int i = logonseq[logontype][m_Operation.nOpState];
+	if (m_pGssLayer)
+	{
+		if ((i == 0 || i == 6 || i == 9 || i == 10) &&
+			(m_CurrentServer.user == "anonymous" || m_CurrentServer.user == ""))
+		{
+			//Extract user from kerberos ticket
+			char str[256];
+			if (m_pGssLayer->GetUserFromKrbTicket(str))
+				m_CurrentServer.user = str;
+			if (m_CurrentServer.user == "")
+			{
+				CGssNeedUserRequestData *pData = new CGssNeedUserRequestData;
+				pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
+				pData->nOldOpState = m_Operation.nOpState;
+				m_Operation.nOpState = CONNECT_GSS_NEEDUSER;
+				if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), (LPARAM)pData))
+					delete pData;
+				return;
+			}
+		}
+		else if ((i == 1 || i == 11) && (m_CurrentServer.pass == COptions::GetOption(OPTION_ANONPWD) || m_CurrentServer.pass == ""))
+		{
+			CGssNeedPassRequestData *pData=new CGssNeedPassRequestData;
+			pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
+			pData->nOldOpState = m_Operation.nOpState;
+			m_Operation.nOpState = CONNECT_GSS_NEEDPASS;
+			if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), (LPARAM)pData))
+				delete pData;
+			return;
+		}
+	}
 #endif
-    switch(logonseq[logontype][m_Operation.nOpState])
-    {
-        case 0:
-            temp="USER "+m_CurrentServer.user;
-            break;
-        case 1:
-            temp="PASS "+m_CurrentServer.pass;
-            break;
-        case 2:
-            temp="ACCT "+CCrypt::decrypt(COptions::GetOption(OPTION_FWPASS));
-            break;
-        case 3:
-            temp="USER "+COptions::GetOption(OPTION_FWUSER);
-            break;
-        case 4:
-            temp="PASS "+CCrypt::decrypt(COptions::GetOption(OPTION_FWPASS));
-            break;
-        case 5:
-            temp="SITE "+hostname;
-            break;
-        case 6:
-            temp="USER "+m_CurrentServer.user+"@"+hostname;
-            break;
-        case 7:
-            temp="OPEN "+hostname;
-            break;
-        case 8:
-            temp="USER "+COptions::GetOption(OPTION_FWUSER)+"@"+hostname;
-            break;
-        case 9:
-            temp="USER "+m_CurrentServer.user+"@"+hostname+" "+COptions::GetOption(OPTION_FWUSER);
-            break;
-        case 10:
-            temp="USER "+m_CurrentServer.user+"@"+COptions::GetOption(OPTION_FWUSER)+"@"+hostname;
-            break;
-        case 11:
-            temp="PASS "+m_CurrentServer.pass+"@"+CCrypt::decrypt(COptions::GetOption(OPTION_FWPASS));
-            break;
-        case 12:
-            if (m_CurrentServer.account == _T(""))
-                temp = _T("ACCT default");
-            else
-                temp = _T("ACCT ") + m_CurrentServer.account;
-            break;
-    }
-    // send command, get response
-    if(!Send(temp))
-        return;
+	switch(logonseq[logontype][m_Operation.nOpState])
+	{
+		case 0:
+			temp="USER "+m_CurrentServer.user;
+			break;
+		case 1:
+			temp="PASS "+m_CurrentServer.pass;
+			break;
+		case 2:
+			temp="ACCT "+CCrypt::decrypt(COptions::GetOption(OPTION_FWPASS));
+			break;
+		case 3:
+			temp="USER "+COptions::GetOption(OPTION_FWUSER);
+			break;
+		case 4:
+			temp="PASS "+CCrypt::decrypt(COptions::GetOption(OPTION_FWPASS));
+			break;
+		case 5:
+			temp="SITE "+hostname;
+			break;
+		case 6:
+			temp="USER "+m_CurrentServer.user+"@"+hostname;
+			break;
+		case 7:
+			temp="OPEN "+hostname;
+			break;
+		case 8:
+			temp="USER "+COptions::GetOption(OPTION_FWUSER)+"@"+hostname;
+			break;
+		case 9:
+			temp="USER "+m_CurrentServer.user+"@"+hostname+" "+COptions::GetOption(OPTION_FWUSER);
+			break;
+		case 10:
+			temp="USER "+m_CurrentServer.user+"@"+COptions::GetOption(OPTION_FWUSER)+"@"+hostname;
+			break;
+		case 11:
+			temp="PASS "+m_CurrentServer.pass+"@"+CCrypt::decrypt(COptions::GetOption(OPTION_FWPASS));
+			break;
+		case 12:
+			if (m_CurrentServer.account == _T(""))
+				temp = _T("ACCT default");
+			else
+				temp = _T("ACCT ") + m_CurrentServer.account;
+			break;
+	}
+	// send command, get response
+	if(!Send(temp))
+		return;
 }
 
 #define BUFFERSIZE 4096
 void CFtpControlSocket::OnReceive(int nErrorCode)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnReceive(%d)  OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
-
-    m_LastRecvTime = CTime::GetCurrentTime();
-    PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_RECV), 0);
-
-    if (!m_pOwner->IsConnected())
-    {
-        if (!m_Operation.nOpMode)
-        {
-            LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Socket has been closed, don't process receive") );
-            return;
-        }
-        m_MultiLine = "";
-        CString str;
-        str.Format(IDS_STATUSMSG_CONNECTEDWITH, m_ServerName);
-        ShowStatus(str, 0);
-        m_pOwner->SetConnected(TRUE);
-    }
-    char *buffer = new char[BUFFERSIZE];
-    int numread = Receive(buffer, BUFFERSIZE);
-
-    if (numread == SOCKET_ERROR)
-    {
-        delete [] buffer;
-        if (GetLastError() != WSAEWOULDBLOCK)
-        {
-            ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
-            DoClose();
-        }
-        return;
-    }
-    if (!numread)
-    {
-        delete [] buffer;
-        ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
-        DoClose();
-    }
-
-    for (int i=0; i < numread; i++)
-    {
-        if ((buffer[i] == '\r') || (buffer[i] == '\n') || (buffer[i] == 0))
-        {
-            if (!m_RecvBuffer.empty() && m_RecvBuffer.back() != "")
-            {
-                USES_CONVERSION;
-                if (m_bUTF8)
-                {
-                    // convert from UTF-8 to ANSI
-                    LPCSTR utf8 = (LPCSTR)m_RecvBuffer.back();
-                    if (!utf8_valid((const unsigned char*)utf8, strlen(utf8)))
-                    {
-                        if (m_CurrentServer.nUTF8 != 1)
-                        {
-                            LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Server does not send proper UTF-8, falling back to local charset"));
-                            m_bUTF8 = false;
-                        }
-                        ShowStatus(A2CT(utf8), 3);
-                    }
-                    else
-                    {
-                        int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
-                        if (!len)
-                            m_RecvBuffer.back() = "";
-                        else
-                        {
-                            LPWSTR p1 = new WCHAR[len + 1];
-                            MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
-                            ShowStatus(W2CT(p1), 3);
-                            delete [] p1;
-                        }
-                    }
-                }
-                else
-                    ShowStatus(A2CT(m_RecvBuffer.back()), 3);
-                //Check for multi-line responses
-                if (m_RecvBuffer.back().GetLength() > 3)
-                {
-                    if (m_MultiLine != "")
-                    {
-                        if (m_RecvBuffer.back().Left(4) != m_MultiLine)
-                        {
-                            DiscardLine(m_RecvBuffer.back());
-                            m_RecvBuffer.pop_back();
-                        }
-                        else // end of multi-line found
-                        {
-                            m_MultiLine = "";
-                            m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, 0);
-                        }
-                    }
-                    // start of new multi-line
-                    else if (m_RecvBuffer.back()[3] == '-')
-                    {
-                        // DDD<SP> is the end of a multi-line response
-                        m_MultiLine = m_RecvBuffer.back().Left(3) + ' ';
-                        m_RecvBuffer.pop_back();
-                    }
-                    else
-                        m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, 0);
-                }
-                else
-                    m_RecvBuffer.pop_back();
-                m_RecvBuffer.push_back("");
-            }
-        }
-        else
-        {
-            //The command may only be 2000 chars long. This ensures that a malicious user can't
-            //send extremely large commands to fill the memory of the server
-            if (m_RecvBuffer.empty())
-                m_RecvBuffer.push_back("");
-            if (m_RecvBuffer.back().GetLength() < 2000)
-                m_RecvBuffer.back() += buffer[i];
-        }
-    }
-
-    delete [] buffer;
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnReceive(%d)  OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
+
+	m_LastRecvTime = CTime::GetCurrentTime();
+	PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_RECV), 0);
+
+	if (!m_pOwner->IsConnected())
+	{
+		if (!m_Operation.nOpMode)
+		{
+			LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Socket has been closed, don't process receive") );
+			return;
+		}
+		m_MultiLine = "";
+		CString str;
+		str.Format(IDS_STATUSMSG_CONNECTEDWITH, m_ServerName);
+		ShowStatus(str, 0);
+		m_pOwner->SetConnected(TRUE);
+	}
+	char *buffer = new char[BUFFERSIZE];
+	int numread = Receive(buffer, BUFFERSIZE);
+
+	if (numread == SOCKET_ERROR)
+	{
+		delete [] buffer;
+		if (GetLastError() != WSAEWOULDBLOCK)
+		{
+			ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
+			DoClose();
+		}
+		return;
+	}
+	if (!numread)
+	{
+		delete [] buffer;
+		ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
+		DoClose();
+	}
+
+	for (int i=0; i < numread; i++)
+	{
+		if ((buffer[i] == '\r') || (buffer[i] == '\n') || (buffer[i] == 0))
+		{
+			if (!m_RecvBuffer.empty() && m_RecvBuffer.back() != "")
+			{
+				USES_CONVERSION;
+				if (m_bUTF8)
+				{
+					// convert from UTF-8 to ANSI
+					LPCSTR utf8 = (LPCSTR)m_RecvBuffer.back();
+					if (!utf8_valid((const unsigned char*)utf8, strlen(utf8)))
+					{
+						if (m_CurrentServer.nUTF8 != 1)
+						{
+							LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Server does not send proper UTF-8, falling back to local charset"));
+							m_bUTF8 = false;
+						}
+						ShowStatus(A2CT(utf8), 3);
+					}
+					else
+					{
+						int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
+						if (!len)
+							m_RecvBuffer.back() = "";
+						else
+						{
+							LPWSTR p1 = new WCHAR[len + 1];
+							MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
+							ShowStatus(W2CT(p1), 3);
+							delete [] p1;
+						}
+					}
+				}
+				else
+					ShowStatus(A2CT(m_RecvBuffer.back()), 3);
+				//Check for multi-line responses
+				if (m_RecvBuffer.back().GetLength() > 3)
+				{
+					if (m_MultiLine != "")
+					{
+						if (m_RecvBuffer.back().Left(4) != m_MultiLine)
+						{
+							DiscardLine(m_RecvBuffer.back());
+ 							m_RecvBuffer.pop_back();
+						}
+						else // end of multi-line found
+						{
+							m_MultiLine = "";
+							m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, 0);
+						}
+					}
+					// start of new multi-line
+					else if (m_RecvBuffer.back()[3] == '-')
+					{
+						// DDD<SP> is the end of a multi-line response
+						m_MultiLine = m_RecvBuffer.back().Left(3) + ' ';
+						m_RecvBuffer.pop_back();
+					}
+					else
+						m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, 0);
+				}
+				else
+					m_RecvBuffer.pop_back();
+				m_RecvBuffer.push_back("");
+			}
+		}
+		else
+		{
+			//The command may only be 2000 chars long. This ensures that a malicious user can't
+			//send extremely large commands to fill the memory of the server
+			if (m_RecvBuffer.empty())
+				m_RecvBuffer.push_back("");
+			if (m_RecvBuffer.back().GetLength() < 2000)
+				m_RecvBuffer.back() += buffer[i];
+		}
+	}
+
+	delete [] buffer;
 }
 
 void CFtpControlSocket::ProcessReply()
 {
-    if (m_RecvBuffer.empty())
-        return;
-
-    if (m_awaitsReply)
-    {
-        if (m_sendBuffer)
-            TriggerEvent(FD_WRITE);
-        m_awaitsReply = false;
-    }
-
-    CString reply = GetReply();
-    if ( reply == _T("") )
-        return;
-
-    // After Cancel, we might have to skip a reply
-    if (m_skipReply)
-    {
-        m_skipReply = false;
-        m_RecvBuffer.pop_front();
-        return;
-    }
-
-    if (m_bKeepAliveActive)
-    {
-        m_bKeepAliveActive = FALSE;
-        m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID,FZAPI_THREADMSG_POSTKEEPALIVE,0);
-    }
-    else if (m_Operation.nOpMode&CSMODE_CONNECT)
-        LogOnToServer();
-    else if (m_Operation.nOpMode& (CSMODE_COMMAND|CSMODE_CHMOD) )
-    {
-        if (GetReplyCode()== 2 || GetReplyCode()== 3)
-            ResetOperation(FZ_REPLY_OK);
-        else
-            ResetOperation(FZ_REPLY_ERROR);
-    }
-    else if (m_Operation.nOpMode&CSMODE_TRANSFER)
-    {
-        FileTransfer(0);
-    }
-    else if (m_Operation.nOpMode&CSMODE_LIST)
-        List(FALSE);
-    else if (m_Operation.nOpMode&CSMODE_DELETE)
-        Delete( _T(""),CServerPath());
-    else if (m_Operation.nOpMode&CSMODE_RMDIR)
-        RemoveDir( _T(""),CServerPath());
-    else if (m_Operation.nOpMode&CSMODE_MKDIR)
-        MakeDir(CServerPath());
-    else if (m_Operation.nOpMode&CSMODE_RENAME)
-        Rename(_T(""), _T(""), CServerPath(), CServerPath());
-
-    if (!m_RecvBuffer.empty())
-        m_RecvBuffer.pop_front();
+	if (m_RecvBuffer.empty())
+		return;
+
+	if (m_awaitsReply)
+	{
+		if (m_sendBuffer)
+			TriggerEvent(FD_WRITE);
+		m_awaitsReply = false;
+	}
+
+	CString reply = GetReply();
+	if ( reply == _T("") )
+		return;
+
+	// After Cancel, we might have to skip a reply
+	if (m_skipReply)
+	{
+		m_skipReply = false;
+		m_RecvBuffer.pop_front();
+		return;
+	}
+
+	if (m_bKeepAliveActive)
+	{
+		m_bKeepAliveActive = FALSE;
+		m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID,FZAPI_THREADMSG_POSTKEEPALIVE,0);
+	}
+	else if (m_Operation.nOpMode&CSMODE_CONNECT)
+		LogOnToServer();
+	else if (m_Operation.nOpMode& (CSMODE_COMMAND|CSMODE_CHMOD) )
+	{
+		if (GetReplyCode()== 2 || GetReplyCode()== 3)
+			ResetOperation(FZ_REPLY_OK);
+		else
+			ResetOperation(FZ_REPLY_ERROR);
+	}
+	else if (m_Operation.nOpMode&CSMODE_TRANSFER)
+	{
+		FileTransfer(0);
+	}
+	else if (m_Operation.nOpMode&CSMODE_LIST)
+		List(FALSE);
+	else if (m_Operation.nOpMode&CSMODE_DELETE)
+		Delete( _T(""),CServerPath());
+	else if (m_Operation.nOpMode&CSMODE_RMDIR)
+		RemoveDir( _T(""),CServerPath());
+	else if (m_Operation.nOpMode&CSMODE_MKDIR)
+		MakeDir(CServerPath());
+	else if (m_Operation.nOpMode&CSMODE_RENAME)
+		Rename(_T(""), _T(""), CServerPath(), CServerPath());
+
+	if (!m_RecvBuffer.empty())
+		m_RecvBuffer.pop_front();
 }
 
 void CFtpControlSocket::OnConnect(int nErrorCode)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnConnect(%d)  OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
-
-    if (!m_Operation.nOpMode)
-    {
-        if (!m_pOwner->IsConnected())
-            DoClose();
-        return;
-    }
-    if (!nErrorCode)
-    {
-        if (!m_pOwner->IsConnected())
-        {
-            m_MultiLine = "";
-            m_pOwner->SetConnected(TRUE);
-            CString str;
-            str.Format(
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnConnect(%d)  OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
+
+	if (!m_Operation.nOpMode)
+	{
+		if (!m_pOwner->IsConnected())
+			DoClose();
+		return;
+	}
+	if (!nErrorCode)
+	{
+		if (!m_pOwner->IsConnected())
+		{
+			m_MultiLine = "";
+			m_pOwner->SetConnected(TRUE);
+			CString str;
+			str.Format(
 #ifndef MPEXT_NO_SSL
-      m_pSslLayer ? IDS_STATUSMSG_CONNECTEDWITHSSL :
+				m_pSslLayer ? IDS_STATUSMSG_CONNECTEDWITHSSL :
 #endif
-      IDS_STATUSMSG_CONNECTEDWITH, m_ServerName);
-            ShowStatus(str,0);
-        }
-    }
-    else
-    {
-        if (nErrorCode == WSAHOST_NOT_FOUND)
-            ShowStatus(IDS_ERRORMSG_CANTRESOLVEHOST, 1);
-        DoClose();
-    }
+				IDS_STATUSMSG_CONNECTEDWITH, m_ServerName);
+			ShowStatus(str,0);
+		}
+	}
+	else
+	{
+		if (nErrorCode == WSAHOST_NOT_FOUND)
+			ShowStatus(IDS_ERRORMSG_CANTRESOLVEHOST, 1);
+		DoClose();
+	}
 }
 
 BOOL CFtpControlSocket::Send(CString str)
 {
-    USES_CONVERSION;
-
-    ShowStatus(str, 2);
-    str += "\r\n";
-    int res = 0;
-    if (m_bUTF8)
-    {
-        LPCWSTR unicode = T2CW(str);
-        int len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, 0, 0, 0, 0);
-        if (!len)
-        {
-            ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
-            DoClose();
-            return FALSE;
-        }
-        char* utf8 = new char[len + 1];
-        WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len + 1, 0, 0);
-
-        int sendLen = strlen(utf8);
-        if (!m_awaitsReply && !m_sendBuffer)
-            res = CAsyncSocketEx::Send(utf8, strlen(utf8));
-        else
-            res = -2;
-        if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
-        {
-            delete [] utf8;
-            ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
-            DoClose();
-            return FALSE;
-        }
-        if (res != sendLen)
-        {
-            if (res == -2)
-                res = 0;
-            if (!m_sendBuffer)
-            {
-                m_sendBuffer = new char[sendLen - res];
-                memcpy(m_sendBuffer, utf8 + res, sendLen - res);
-                m_sendBufferLen = sendLen - res;
-            }
-            else
-            {
-                char* tmp = new char[m_sendBufferLen + sendLen - res];
-                memcpy(tmp, m_sendBuffer, m_sendBufferLen);
-                memcpy(tmp + m_sendBufferLen, utf8 + res, sendLen - res);
-                delete [] m_sendBuffer;
-                m_sendBuffer = tmp;
-                m_sendBufferLen += sendLen - res;
-            }
-        }
-        delete [] utf8;
-    }
-    else
-    {
-        LPCSTR lpszAsciiSend = T2CA(str);
-
-        int sendLen = strlen(lpszAsciiSend);
-        if (!m_awaitsReply && !m_sendBuffer)
-            res = CAsyncSocketEx::Send(lpszAsciiSend, strlen(lpszAsciiSend));
-        else
-            res = -2;
-        if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
-        {
-            ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
-            DoClose();
-            return FALSE;
-        }
-        if (res != sendLen)
-        {
-            if (res == -2)
-                res = 0;
-            if (!m_sendBuffer)
-            {
-                m_sendBuffer = new char[sendLen - res];
-                memcpy(m_sendBuffer, lpszAsciiSend, sendLen - res);
-                m_sendBufferLen = sendLen - res;
-            }
-            else
-            {
-                char* tmp = new char[m_sendBufferLen + sendLen - res];
-                memcpy(tmp, m_sendBuffer, m_sendBufferLen);
-                memcpy(tmp + m_sendBufferLen, lpszAsciiSend + res, sendLen - res);
-                delete [] m_sendBuffer;
-                m_sendBuffer = tmp;
-                m_sendBufferLen += sendLen - res;
-            }
-        }
-    }
-    if (res > 0)
-    {
-        m_awaitsReply = true;
-        m_LastSendTime = CTime::GetCurrentTime();
-        PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
-    }
-    return TRUE;
+	USES_CONVERSION;
+
+	ShowStatus(str, 2);
+	str += "\r\n";
+	int res = 0;
+	if (m_bUTF8)
+	{
+		LPCWSTR unicode = T2CW(str);
+		int len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, 0, 0, 0, 0);
+		if (!len)
+		{
+			ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
+			DoClose();
+			return FALSE;
+		}
+		char* utf8 = new char[len + 1];
+		WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len + 1, 0, 0);
+
+		int sendLen = strlen(utf8);
+		if (!m_awaitsReply && !m_sendBuffer)
+			res = CAsyncSocketEx::Send(utf8, strlen(utf8));
+		else
+			res = -2;
+		if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
+		{
+			delete [] utf8;
+			ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
+			DoClose();
+			return FALSE;
+		}
+		if (res != sendLen)
+		{
+			if (res == -2)
+				res = 0;
+			if (!m_sendBuffer)
+			{
+				m_sendBuffer = new char[sendLen - res];
+				memcpy(m_sendBuffer, utf8 + res, sendLen - res);
+				m_sendBufferLen = sendLen - res;
+			}
+			else
+			{
+				char* tmp = new char[m_sendBufferLen + sendLen - res];
+				memcpy(tmp, m_sendBuffer, m_sendBufferLen);
+				memcpy(tmp + m_sendBufferLen, utf8 + res, sendLen - res);
+				delete [] m_sendBuffer;
+				m_sendBuffer = tmp;
+				m_sendBufferLen += sendLen - res;
+			}
+		}
+		delete [] utf8;
+	}
+	else
+	{
+		LPCSTR lpszAsciiSend = T2CA(str);
+
+		int sendLen = strlen(lpszAsciiSend);
+		if (!m_awaitsReply && !m_sendBuffer)
+			res = CAsyncSocketEx::Send(lpszAsciiSend, strlen(lpszAsciiSend));
+		else
+			res = -2;
+		if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
+		{
+			ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
+			DoClose();
+			return FALSE;
+		}
+		if (res != sendLen)
+		{
+			if (res == -2)
+				res = 0;
+			if (!m_sendBuffer)
+			{
+				m_sendBuffer = new char[sendLen - res];
+				memcpy(m_sendBuffer, lpszAsciiSend, sendLen - res);
+				m_sendBufferLen = sendLen - res;
+			}
+			else
+			{
+				char* tmp = new char[m_sendBufferLen + sendLen - res];
+				memcpy(tmp, m_sendBuffer, m_sendBufferLen);
+				memcpy(tmp + m_sendBufferLen, lpszAsciiSend + res, sendLen - res);
+				delete [] m_sendBuffer;
+				m_sendBuffer = tmp;
+				m_sendBufferLen += sendLen - res;
+			}
+		}
+	}
+	if (res > 0)
+	{
+		m_awaitsReply = true;
+		m_LastSendTime = CTime::GetCurrentTime();
+		PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
+	}
+	return TRUE;
 }
 
 int CFtpControlSocket::GetReplyCode()
 {
-    if (m_RecvBuffer.empty())
-        return 0;
-    CStringA str = m_RecvBuffer.front();
-    if (str == "")
-        return 0;
-    else
-        return str[0]-'0';
+	if (m_RecvBuffer.empty())
+		return 0;
+	CStringA str = m_RecvBuffer.front();
+	if (str == "")
+		return 0;
+	else
+		return str[0]-'0';
 }
 
 void CFtpControlSocket::DoClose(int nError /*=0*/)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("DoClose(%d)  OpMode=%d OpState=%d"), nError, m_Operation.nOpMode, m_Operation.nOpState);
-
-    m_bCheckForTimeout=TRUE;
-    m_pOwner->SetConnected(FALSE);
-    m_bKeepAliveActive=FALSE;
-    PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, FALSE), 0);
-    if (nError & FZ_REPLY_CRITICALERROR)
-        nError |= FZ_REPLY_ERROR;
-    ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED|nError);
-    m_RecvBuffer.clear();
-    m_MultiLine = "";
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("DoClose(%d)  OpMode=%d OpState=%d"), nError, m_Operation.nOpMode, m_Operation.nOpState);
+
+	m_bCheckForTimeout=TRUE;
+	m_pOwner->SetConnected(FALSE);
+	m_bKeepAliveActive=FALSE;
+	PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, FALSE), 0);
+	if (nError & FZ_REPLY_CRITICALERROR)
+		nError |= FZ_REPLY_ERROR;
+	ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED|nError);
+	m_RecvBuffer.clear();
+	m_MultiLine = "";
 #ifndef MPEXT_NO_SSL
-    m_bDidRejectCertificate = FALSE;
+	m_bDidRejectCertificate = FALSE;
 #endif
 
 #ifndef MPEXT_NO_ZLIB
-    m_useZlib = false;
-    m_zlibSupported = false;
-    m_zlibLevel = 0;
+	m_useZlib = false;
+	m_zlibSupported = false;
+	m_zlibLevel = 0;
 #endif
 
-    m_bUTF8 = false;
-    m_hasClntCmd = false;
+	m_bUTF8 = false;
+	m_hasClntCmd = false;
 
-    m_awaitsReply = false;
-    m_skipReply = false;
+	m_awaitsReply = false;
+	m_skipReply = false;
 
-    delete [] m_sendBuffer;
-    m_sendBuffer = 0;
-    m_sendBufferLen = 0;
+	delete [] m_sendBuffer;
+	m_sendBuffer = 0;
+	m_sendBufferLen = 0;
 
-    m_bProtP = false;
+	m_bProtP = false;
 
-    m_mayBeMvsFilesystem = false;
-    m_mayBeBS2000Filesystem = false;
+	m_mayBeMvsFilesystem = false;
+	m_mayBeBS2000Filesystem = false;
 
-    CControlSocket::Close();
+	CControlSocket::Close();
 }
 
 void CFtpControlSocket::Disconnect()
 {
-    ASSERT(!m_Operation.nOpMode);
-    m_Operation.nOpMode=CSMODE_DISCONNECT;
-    DoClose();
-    ShowStatus(IDS_STATUSMSG_DISCONNECTED,0); //Send the disconnected message to the message log
+	ASSERT(!m_Operation.nOpMode);
+	m_Operation.nOpMode=CSMODE_DISCONNECT;
+	DoClose();
+	ShowStatus(IDS_STATUSMSG_DISCONNECTED,0); //Send the disconnected message to the message log
 }
 
 void CFtpControlSocket::CheckForTimeout()
 {
-    if (!m_Operation.nOpMode && !m_bKeepAliveActive)
-        return;
-    if (!m_bCheckForTimeout)
-        return;
-    int delay=COptions::GetOptionVal(OPTION_TIMEOUTLENGTH);
-    if (m_pTransferSocket)
-    {
-        int res=m_pTransferSocket->CheckForTimeout(delay);
-        if (res)
-            return;
-    }
-    CTimeSpan span=CTime::GetCurrentTime()-m_LastRecvTime;
-    if (span.GetTotalSeconds()>=delay)
-    {
-        ShowStatus(IDS_ERRORMSG_TIMEOUT, 1);
-        DoClose();
-    }
+	if (!m_Operation.nOpMode && !m_bKeepAliveActive)
+		return;
+	if (!m_bCheckForTimeout)
+		return;
+	int delay=COptions::GetOptionVal(OPTION_TIMEOUTLENGTH);
+	if (m_pTransferSocket)
+	{
+		int res=m_pTransferSocket->CheckForTimeout(delay);
+		if (res)
+			return;
+	}
+	CTimeSpan span=CTime::GetCurrentTime()-m_LastRecvTime;
+	if (span.GetTotalSeconds()>=delay)
+	{
+		ShowStatus(IDS_ERRORMSG_TIMEOUT, 1);
+		DoClose();
+	}
 }
 
 void CFtpControlSocket::FtpCommand(LPCTSTR pCommand)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("FtpCommand(%s)  OpMode=%d OpState=%d"), pCommand, m_Operation.nOpMode, m_Operation.nOpState);
-    m_Operation.nOpMode=CSMODE_COMMAND;
-    Send(pCommand);
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("FtpCommand(%s)  OpMode=%d OpState=%d"), pCommand, m_Operation.nOpMode, m_Operation.nOpState);
+	m_Operation.nOpMode=CSMODE_COMMAND;
+	Send(pCommand);
 }
 
 void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath path /*=CServerPath()*/, CString subdir /*=""*/,int nListMode/*=0*/)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("List(%s,%d,\"%s\",\"%s\",%d)  OpMode=%d OpState=%d"), bFinish?_T("TRUE"):_T("FALSE"), nError, path.GetPath(), subdir, nListMode,
-                m_Operation.nOpMode, m_Operation.nOpState);
-
-    USES_CONVERSION;
-
-    #define LIST_INIT   -1
-    #define LIST_PWD    0
-    #define LIST_CWD    1
-    #define LIST_PWD2   2
-    #define LIST_CWD2   3
-    #define LIST_PWD3   4
-    #define LIST_MODE   5
-    #define LIST_OPTS   6
-    #define LIST_PORT_PASV  7
-    #define LIST_TYPE   8
-    #define LIST_LIST   9
-    #define LIST_WAITFINISH 10
-
-    ASSERT(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LIST);
-
-    m_Operation.nOpMode|=CSMODE_LIST;
-
-    if (!m_pOwner->IsConnected())
-    {
-        ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
-        return;
-    }
-
-    if (bFinish || nError)
-        if (m_Operation.nOpMode!=CSMODE_LIST)
-            return; //Old message coming in
-
-    if (nError)
-    {
-        delete m_pTransferSocket;
-        m_pTransferSocket=0;
-        if (nError&CSMODE_TRANSFERTIMEOUT)
-            DoClose();
-        else
-            ResetOperation(FZ_REPLY_ERROR);
-        return;
-    }
-
-    CListData *pData = static_cast<CListData *>(m_Operation.pData);
-
-    if (bFinish)
-    {
-        if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
-        {
-            delete m_pDirectoryListing;
-            m_pDirectoryListing = 0;
-            delete m_pTransferSocket;
-            m_pTransferSocket = 0;
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-
-        int num = 0;
-        pData->pDirectoryListing = new t_directory;
-        if (COptions::GetOptionVal(OPTION_DEBUGSHOWLISTING))
-            m_pTransferSocket->m_pListResult->SendToMessageLog(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID);
-        pData->pDirectoryListing->direntry = m_pTransferSocket->m_pListResult->getList(num, pData->ListStartTime);
-        pData->pDirectoryListing->num = num;
-        if (m_pTransferSocket->m_pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
-            m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
-
-        pData->pDirectoryListing->server = m_CurrentServer;
-        pData->pDirectoryListing->path.SetServer(pData->pDirectoryListing->server);
-        if (pData->rawpwd != "")
-        {
-            if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
-            {
-                delete m_pDirectoryListing;
-                m_pDirectoryListing=0;
-                delete m_pTransferSocket;
-                m_pTransferSocket=0;
-                ResetOperation(FZ_REPLY_ERROR);
-                return;
-            }
-            m_pOwner->SetCurrentPath(pData->pDirectoryListing->path);
-        }
-        else
-            pData->pDirectoryListing->path = m_pOwner->GetCurrentPath();
-
-        if (m_Operation.nOpState!=LIST_WAITFINISH)
-            return;
-        else
-        {
-            delete m_pTransferSocket;
-            m_pTransferSocket=0;
-        }
-    }
-
-    if (m_Operation.nOpState==LIST_WAITFINISH)
-    {
-        if (!bFinish)
-        {
-            if (pData->nFinish==-1)
-            {
-                int code=GetReplyCode();
-                if (code== 2)
-                {
-                    pData->nFinish=1;
-                }
-                else
-                    pData->nFinish=0;
-            }
-        }
-        else
-        {
-            if (m_pTransferSocket)
-                delete m_pTransferSocket;
-            m_pTransferSocket=0;
-        }
-        if (pData->nFinish==0)
-        {
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        else if (pData->pDirectoryListing && pData->nFinish==1)
-        {
-            ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,0);
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("List(%s,%d,\"%s\",\"%s\",%d)  OpMode=%d OpState=%d"), bFinish?_T("TRUE"):_T("FALSE"), nError, path.GetPath(), subdir, nListMode,
+				m_Operation.nOpMode, m_Operation.nOpState);
+
+	USES_CONVERSION;
+
+	#define LIST_INIT	-1
+	#define LIST_PWD	0
+	#define LIST_CWD	1
+	#define LIST_PWD2	2
+	#define LIST_CWD2	3
+	#define LIST_PWD3	4
+	#define LIST_MODE	5
+	#define LIST_OPTS	6
+	#define LIST_PORT_PASV	7
+	#define LIST_TYPE	8
+	#define LIST_LIST	9
+	#define LIST_WAITFINISH	10
+
+	ASSERT(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LIST);
+
+	m_Operation.nOpMode|=CSMODE_LIST;
+
+	if (!m_pOwner->IsConnected())
+	{
+		ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
+		return;
+	}
+
+	if (bFinish || nError)
+		if (m_Operation.nOpMode!=CSMODE_LIST)
+			return; //Old message coming in
+
+	if (nError)
+	{
+		delete m_pTransferSocket;
+		m_pTransferSocket=0;
+		if (nError&CSMODE_TRANSFERTIMEOUT)
+			DoClose();
+		else
+			ResetOperation(FZ_REPLY_ERROR);
+		return;
+	}
+
+	CListData *pData = static_cast<CListData *>(m_Operation.pData);
+
+	if (bFinish)
+	{
+		if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
+		{
+			delete m_pDirectoryListing;
+			m_pDirectoryListing = 0;
+			delete m_pTransferSocket;
+			m_pTransferSocket = 0;
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+
+		int num = 0;
+		pData->pDirectoryListing = new t_directory;
+		if (COptions::GetOptionVal(OPTION_DEBUGSHOWLISTING))
+			m_pTransferSocket->m_pListResult->SendToMessageLog(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID);
+		pData->pDirectoryListing->direntry = m_pTransferSocket->m_pListResult->getList(num, pData->ListStartTime);
+		pData->pDirectoryListing->num = num;
+		if (m_pTransferSocket->m_pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
+			m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
+
+		pData->pDirectoryListing->server = m_CurrentServer;
+		pData->pDirectoryListing->path.SetServer(pData->pDirectoryListing->server);
+		if (pData->rawpwd != "")
+		{
+			if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
+			{
+				delete m_pDirectoryListing;
+				m_pDirectoryListing=0;
+				delete m_pTransferSocket;
+				m_pTransferSocket=0;
+				ResetOperation(FZ_REPLY_ERROR);
+				return;
+			}
+			m_pOwner->SetCurrentPath(pData->pDirectoryListing->path);
+		}
+		else
+			pData->pDirectoryListing->path = m_pOwner->GetCurrentPath();
+
+		if (m_Operation.nOpState!=LIST_WAITFINISH)
+			return;
+		else
+		{
+			delete m_pTransferSocket;
+			m_pTransferSocket=0;
+		}
+	}
+
+	if (m_Operation.nOpState==LIST_WAITFINISH)
+	{
+		if (!bFinish)
+		{
+			if (pData->nFinish==-1)
+			{
+				int code=GetReplyCode();
+				if (code== 2)
+				{
+					pData->nFinish=1;
+				}
+				else
+					pData->nFinish=0;
+			}
+		}
+		else
+		{
+			if (m_pTransferSocket)
+				delete m_pTransferSocket;
+			m_pTransferSocket=0;
+		}
+		if (pData->nFinish==0)
+		{
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		else if (pData->pDirectoryListing && pData->nFinish==1)
+		{
+			ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,0);
 #ifndef MPEXT_NO_CACHE
-            CDirectoryCache cache;
-            cache.Lock();
-            t_directory dir;
-            if (!pData->path.IsEmpty() && pData->subdir!="")
-            {
-                if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir))
-                    pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
-                cache.Store(*pData->pDirectoryListing,pData->path,pData->subdir);
-            }
-            else
-            {
-                if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir))
-                    pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
-                cache.Store(*pData->pDirectoryListing);
-            }
-            cache.Unlock();
+			CDirectoryCache cache;
+			cache.Lock();
+			t_directory dir;
+			if (!pData->path.IsEmpty() && pData->subdir!="")
+			{
+				if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir))
+					pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
+				cache.Store(*pData->pDirectoryListing,pData->path,pData->subdir);
+			}
+			else
+			{
+				if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir))
+					pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
+				cache.Store(*pData->pDirectoryListing);
+			}
+			cache.Unlock();
 #endif
-            SetDirectoryListing(pData->pDirectoryListing);
-            ResetOperation(FZ_REPLY_OK);
-            return;
-        }
-        return;
-    }
-    else if (m_Operation.nOpState != LIST_INIT)
-    {
-        CString retmsg = GetReply();
-        BOOL error = FALSE;
-        int code = GetReplyCode();
-        switch (m_Operation.nOpState)
-        {
-        case LIST_PWD: //Reply to PWD command
-            if (code != 2 && code !=3 )
-            {
-                error = TRUE;
-                break;
-            }
-
-            pData->rawpwd = retmsg;
-            if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
-                pData->rawpwd[0] != '/')
-            {
-                m_mayBeMvsFilesystem = false;
-                m_mayBeBS2000Filesystem = false;
-                if (m_mayBeBS2000Filesystem)
-                    m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
-                else
-                    m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
-
-                if (!pData->path.IsEmpty())
-                    pData->path.SetServer(m_CurrentServer);
-            }
-            if (!ParsePwdReply(pData->rawpwd))
-                return;
-            if (pData->path.IsEmpty() || pData->path == m_pOwner->GetCurrentPath())
-            {
+			SetDirectoryListing(pData->pDirectoryListing);
+			ResetOperation(FZ_REPLY_OK);
+			return;
+		}
+		return;
+	}
+	else if (m_Operation.nOpState != LIST_INIT)
+	{
+		CString retmsg = GetReply();
+		BOOL error = FALSE;
+		int code = GetReplyCode();
+		switch (m_Operation.nOpState)
+		{
+		case LIST_PWD: //Reply to PWD command
+			if (code != 2 && code !=3 )
+			{
+				error = TRUE;
+				break;
+			}
+
+			pData->rawpwd = retmsg;
+			if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
+				pData->rawpwd[0] != '/')
+			{
+				m_mayBeMvsFilesystem = false;
+				m_mayBeBS2000Filesystem = false;
+				if (m_mayBeBS2000Filesystem)
+					m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
+				else
+					m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
+
+				if (!pData->path.IsEmpty())
+					pData->path.SetServer(m_CurrentServer);
+			}
+			if (!ParsePwdReply(pData->rawpwd))
+				return;
+			if (pData->path.IsEmpty() || pData->path == m_pOwner->GetCurrentPath())
+			{
 #ifndef MPEXT_NO_CACHE
-                if (pData->nListMode & FZ_LIST_USECACHE)
-                {
-                    t_directory dir;
-                    CDirectoryCache cache;
-                    BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
-                    if (res)
-                    {
-                        BOOL bExact = TRUE;
-                        if (pData->nListMode & FZ_LIST_EXACT)
-                            for (int i=0; i<dir.num; i++)
-                                if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
-                                {
-                                    bExact = FALSE;
-                                    break;
-                                }
-                        if (bExact)
-                        {
-                            ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
-                            SetDirectoryListing(&dir);
-                            ResetOperation(FZ_REPLY_OK);
-                            return;
-                        }
-                    }
-                }
+				if (pData->nListMode & FZ_LIST_USECACHE)
+				{
+					t_directory dir;
+					CDirectoryCache cache;
+					BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
+					if (res)
+					{
+						BOOL bExact = TRUE;
+						if (pData->nListMode & FZ_LIST_EXACT)
+							for (int i=0; i<dir.num; i++)
+								if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
+								{
+									bExact = FALSE;
+									break;
+								}
+						if (bExact)
+						{
+							ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
+							SetDirectoryListing(&dir);
+							ResetOperation(FZ_REPLY_OK);
+							return;
+						}
+					}
+				}
 #endif
-                m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
-            }
-            else
-                m_Operation.nOpState = LIST_CWD;
-            break;
-        case LIST_CWD:
-            if (code != 2 && code != 3)
-                error = TRUE;
-            m_Operation.nOpState = LIST_PWD2;
-            break;
-        case LIST_PWD2: //Reply to PWD command
-            if (code !=2 && code != 3)
-                error = TRUE;
-            else
-            {
-                pData->rawpwd = retmsg;
-                if (!ParsePwdReply(pData->rawpwd))
-                    return;
-            }
-            if (pData->subdir != "")
-            {
-                if (pData->path != m_pOwner->GetCurrentPath())
-                {
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-                m_Operation.nOpState = LIST_CWD2;
-            }
-            else
-            {
+				m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
+			}
+			else
+				m_Operation.nOpState = LIST_CWD;
+			break;
+		case LIST_CWD:
+			if (code != 2 && code != 3)
+				error = TRUE;
+			m_Operation.nOpState = LIST_PWD2;
+			break;
+		case LIST_PWD2: //Reply to PWD command
+			if (code !=2 && code != 3)
+				error = TRUE;
+			else
+			{
+				pData->rawpwd = retmsg;
+				if (!ParsePwdReply(pData->rawpwd))
+					return;
+			}
+			if (pData->subdir != "")
+			{
+				if (pData->path != m_pOwner->GetCurrentPath())
+				{
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+				m_Operation.nOpState = LIST_CWD2;
+			}
+			else
+			{
 #ifndef MPEXT_NO_CACHE
-                if (pData->nListMode & FZ_LIST_USECACHE)
-                {
-                    t_directory dir;
-                    CDirectoryCache cache;
-                    BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
-                    if (res)
-                    {
-                        BOOL bExact = TRUE;
-                        if (pData->nListMode & FZ_LIST_EXACT)
-                            for (int i=0; i<dir.num; i++)
-                                if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
-                                {
-                                    bExact = FALSE;
-                                    break;
-                                }
-                        if (bExact)
-                        {
-                            ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
-                            SetDirectoryListing(&dir);
-                            ResetOperation(FZ_REPLY_OK);
-                            return;
-                        }
-                    }
-                }
+				if (pData->nListMode & FZ_LIST_USECACHE)
+				{
+					t_directory dir;
+					CDirectoryCache cache;
+					BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
+					if (res)
+					{
+						BOOL bExact = TRUE;
+						if (pData->nListMode & FZ_LIST_EXACT)
+							for (int i=0; i<dir.num; i++)
+								if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
+								{
+									bExact = FALSE;
+									break;
+								}
+						if (bExact)
+						{
+							ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
+							SetDirectoryListing(&dir);
+							ResetOperation(FZ_REPLY_OK);
+							return;
+						}
+					}
+				}
 #endif
-                m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
-            }
-            break;
-        case LIST_CWD2:
-            if (pData->lastCmdSentCDUP)
-            {
-                CString reply = GetReply().Left(3);
-                int replycode = _ttoi(reply);
-                if (replycode >= 500 && replycode < 505)
-                    break;
-                pData->lastCmdSentCDUP = false;
-            }
-            if (code != 2 && code != 3)
-                error = TRUE;
-            m_Operation.nOpState = LIST_PWD3;
-            break;
-        case LIST_PWD3: //Reply to PWD command
-            if (code != 2 && code != 3)
-                error = TRUE;
-            else
-            {
-                pData->rawpwd = retmsg;
-                if (!ParsePwdReply(pData->rawpwd))
-                    return;
+				m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
+			}
+			break;
+		case LIST_CWD2:
+			if (pData->lastCmdSentCDUP)
+			{
+				CString reply = GetReply().Left(3);
+				int replycode = _ttoi(reply);
+				if (replycode >= 500 && replycode < 505)
+					break;
+				pData->lastCmdSentCDUP = false;
+			}
+			if (code != 2 && code != 3)
+				error = TRUE;
+			m_Operation.nOpState = LIST_PWD3;
+			break;
+		case LIST_PWD3: //Reply to PWD command
+			if (code != 2 && code != 3)
+				error = TRUE;
+			else
+			{
+				pData->rawpwd = retmsg;
+				if (!ParsePwdReply(pData->rawpwd))
+					return;
 #ifndef MPEXT_NO_CACHE
-                if (pData->nListMode & FZ_LIST_USECACHE)
-                {
-                    t_directory dir;
-                    CDirectoryCache cache;
-                    BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
-                    if (res)
-                    {
-                        BOOL bExact = TRUE;
-                        if (pData->nListMode & FZ_LIST_EXACT)
-                            for (int i=0; i<dir.num; i++)
-                                if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
-                                {
-                                    bExact = FALSE;
-                                    break;
-                                }
-                        if (bExact)
-                        {
-                            ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
-                            SetDirectoryListing(&dir);
-                            ResetOperation(FZ_REPLY_OK);
-                            return;
-                        }
-                    }
-                }
+				if (pData->nListMode & FZ_LIST_USECACHE)
+				{
+					t_directory dir;
+					CDirectoryCache cache;
+					BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
+					if (res)
+					{
+						BOOL bExact = TRUE;
+						if (pData->nListMode & FZ_LIST_EXACT)
+							for (int i=0; i<dir.num; i++)
+								if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
+								{
+									bExact = FALSE;
+									break;
+								}
+						if (bExact)
+						{
+							ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
+							SetDirectoryListing(&dir);
+							ResetOperation(FZ_REPLY_OK);
+							return;
+						}
+					}
+				}
 #endif
-            }
-            m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
-            break;
-        case LIST_MODE:
+			}
+			m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
+			break;
+		case LIST_MODE:
 #ifndef MPEXT_NO_ZLIB
-            if (code == 2 || code == 3)
-                m_useZlib = !m_useZlib;
+			if (code == 2 || code == 3)
+				m_useZlib = !m_useZlib;
 #endif
-            m_Operation.nOpState = NeedOptsCommand() ? LIST_OPTS : LIST_TYPE;
-            break;
-        case LIST_OPTS:
+			m_Operation.nOpState = NeedOptsCommand() ? LIST_OPTS : LIST_TYPE;
+			break;
+		case LIST_OPTS:
 #ifndef MPEXT_NO_ZLIB
-            if (code == 2 || code == 3)
-                m_zlibLevel = pData->newZlibLevel;
+			if (code == 2 || code == 3)
+				m_zlibLevel = pData->newZlibLevel;
 #endif
-            m_Operation.nOpState = LIST_TYPE;
-            break;
-        case LIST_TYPE:
-            if (code!=2 && code!=3)
-                error=TRUE;
-            m_Operation.nOpState = LIST_PORT_PASV;
-            break;
-        case LIST_PORT_PASV:
-            if (code!=2 && code!=3)
-            {
-                error=TRUE;
-                break;
-            }
-            if (pData->bPasv)
-            {
-                CString temp;
-                int i,j;
-                if((i=retmsg.Find(_T("(")))==-1||(j=retmsg.Find(_T(")")))==-1)
-                {
-                    if (!pData->bTriedPortPasvOnce)
-                    {
-                        pData->bTriedPortPasvOnce = TRUE;
-                        pData->bPasv = !pData->bPasv;
-                    }
-                    else
-                        error=TRUE;
-                    break;
-                }
-
-                if (GetFamily() == AF_INET)
-                {
-                    temp = retmsg.Mid(i+1,(j-i)-1);
-                    i=temp.ReverseFind(',');
-                    pData->port=atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); //get ls byte of server socket
-                    temp=temp.Left(i);
-                    i=temp.ReverseFind(',');
-                    pData->port+=256*atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); // add ms byte to server socket
-                    pData->host = temp.Left(i);
-                    pData->host.Replace(',', '.');
-                }
-                else if (GetFamily() == AF_INET6)
-                {
-                    temp = temp.Mid(3);
-                    pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
-                    if (pData->port < 0 || pData->port > 65535)
-                    {
-                        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
-                        error = TRUE;
-                        break;
-                    }
-
-                    unsigned int tmpPort;
-                    if (!GetPeerName(pData->host, tmpPort))
-                    {
-                        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
-                        error = TRUE;
-                        break;
-                    }
-                }
-                else
-                {
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
-                    error = TRUE;
-                    break;
-                }
-            }
-            m_Operation.nOpState = LIST_LIST;
-            break;
-        case LIST_LIST:
-            if (IsMisleadingListResponse())
-            {
-                ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
-
-                t_directory listing;
-                listing.server = m_CurrentServer;
-                listing.path = m_pOwner->GetCurrentPath();
+			m_Operation.nOpState = LIST_TYPE;
+			break;
+		case LIST_TYPE:
+			if (code!=2 && code!=3)
+				error=TRUE;
+			m_Operation.nOpState = LIST_PORT_PASV;
+			break;
+		case LIST_PORT_PASV:
+			if (code!=2 && code!=3)
+			{
+				error=TRUE;
+				break;
+			}
+			if (pData->bPasv)
+			{
+				CString temp;
+				int i,j;
+				if((i=retmsg.Find(_T("(")))==-1||(j=retmsg.Find(_T(")")))==-1)
+				{
+					if (!pData->bTriedPortPasvOnce)
+					{
+						pData->bTriedPortPasvOnce = TRUE;
+						pData->bPasv = !pData->bPasv;
+					}
+					else
+						error=TRUE;
+					break;
+				}
+
+				if (GetFamily() == AF_INET)
+				{
+					temp = retmsg.Mid(i+1,(j-i)-1);
+					i=temp.ReverseFind(',');
+					pData->port=atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); //get ls byte of server socket
+					temp=temp.Left(i);
+					i=temp.ReverseFind(',');
+					pData->port+=256*atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); // add ms byte to server socket
+					pData->host = temp.Left(i);
+					pData->host.Replace(',', '.');
+				}
+				else if (GetFamily() == AF_INET6)
+				{
+					temp = temp.Mid(3);
+					pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
+					if (pData->port < 0 || pData->port > 65535)
+					{
+						LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
+						error = TRUE;
+						break;
+					}
+
+					unsigned int tmpPort;
+					if (!GetPeerName(pData->host, tmpPort))
+					{
+						LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
+						error = TRUE;
+						break;
+					}
+				}
+				else
+				{
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
+					error = TRUE;
+					break;
+				}
+			}
+			m_Operation.nOpState = LIST_LIST;
+			break;
+		case LIST_LIST:
+			if (IsMisleadingListResponse())
+			{
+				ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
+
+				t_directory listing;
+				listing.server = m_CurrentServer;
+				listing.path = m_pOwner->GetCurrentPath();
 
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
-                cache.Lock();
-                t_directory dir;
-                if (!pData->path.IsEmpty() && pData->subdir != "")
-                {
-                    if (cache.Lookup(listing.path, listing.server, dir))
-                        listing.Merge(dir, pData->ListStartTime);
-                    cache.Store(listing, pData->path, pData->subdir);
-                }
-                else
-                {
-                    if (cache.Lookup(listing.path, listing.server, dir))
-                        listing.Merge(dir, pData->ListStartTime);
-                    cache.Store(listing);
-                }
-                cache.Unlock();
+				CDirectoryCache cache;
+				cache.Lock();
+				t_directory dir;
+				if (!pData->path.IsEmpty() && pData->subdir != "")
+				{
+					if (cache.Lookup(listing.path, listing.server, dir))
+						listing.Merge(dir, pData->ListStartTime);
+					cache.Store(listing, pData->path, pData->subdir);
+				}
+				else
+				{
+					if (cache.Lookup(listing.path, listing.server, dir))
+						listing.Merge(dir, pData->ListStartTime);
+					cache.Store(listing);
+				}
+				cache.Unlock();
 #endif
-                SetDirectoryListing(&listing);
-                ResetOperation(FZ_REPLY_OK);
-                return;
-            }
-            else if (code != 1)
-                error = TRUE;
-            else
-                m_Operation.nOpState = LIST_WAITFINISH;
-            break;
-        default:
-            error = TRUE;
-        }
-
-        if (error)
-        {
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-    }
-    if (m_Operation.nOpState==LIST_INIT)
-    { //Initialize some variables
-        pData=new CListData;
-        pData->nListMode=nListMode;
-        pData->path=path;
-        pData->subdir=subdir;
-        m_Operation.pData=pData;
-        ShowStatus(IDS_STATUSMSG_RETRIEVINGDIRLIST, 0);
-        pData->nFinish=-1;
-        if (m_pDirectoryListing)
-        {
-            delete m_pDirectoryListing;
-            m_pDirectoryListing=0;
-        }
-
-        if (COptions::GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY && !m_CurrentServer.fwbypass)
-            pData->bPasv = TRUE;
-        else if (m_CurrentServer.nPasv == 1)
-            pData->bPasv = TRUE;
-        else if (m_CurrentServer.nPasv == 2)
-            pData->bPasv = FALSE;
-        else
-            pData->bPasv = COptions::GetOptionVal(OPTION_PASV);
-
-        CServerPath path = pData->path;
-        CServerPath realpath = m_pOwner->GetCurrentPath();
-        if (!realpath.IsEmpty())
-        {
-            if (!pData->path.IsEmpty() && pData->path != realpath)
-                m_Operation.nOpState=LIST_CWD;
-            else if (!pData->path.IsEmpty() && pData->subdir!="")
-                m_Operation.nOpState=LIST_CWD2;
-            else
-            {
-                if (pData->nListMode & FZ_LIST_REALCHANGE)
-                {
-                    if (pData->subdir == "")
-                        m_Operation.nOpState = LIST_CWD;
-                    else
-                        m_Operation.nOpState = LIST_CWD2;
-                }
-                else
-                {
+				SetDirectoryListing(&listing);
+				ResetOperation(FZ_REPLY_OK);
+				return;
+			}
+			else if (code != 1)
+				error = TRUE;
+			else
+				m_Operation.nOpState = LIST_WAITFINISH;
+			break;
+		default:
+			error = TRUE;
+		}
+
+		if (error)
+		{
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+	}
+	if (m_Operation.nOpState==LIST_INIT)
+	{ //Initialize some variables
+		pData=new CListData;
+		pData->nListMode=nListMode;
+		pData->path=path;
+		pData->subdir=subdir;
+		m_Operation.pData=pData;
+		ShowStatus(IDS_STATUSMSG_RETRIEVINGDIRLIST, 0);
+		pData->nFinish=-1;
+		if (m_pDirectoryListing)
+		{
+			delete m_pDirectoryListing;
+			m_pDirectoryListing=0;
+		}
+
+		if (COptions::GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY && !m_CurrentServer.fwbypass)
+			pData->bPasv = TRUE;
+		else if (m_CurrentServer.nPasv == 1)
+			pData->bPasv = TRUE;
+		else if (m_CurrentServer.nPasv == 2)
+			pData->bPasv = FALSE;
+		else
+			pData->bPasv = COptions::GetOptionVal(OPTION_PASV);
+
+		CServerPath path = pData->path;
+		CServerPath realpath = m_pOwner->GetCurrentPath();
+		if (!realpath.IsEmpty())
+		{
+			if (!pData->path.IsEmpty() && pData->path != realpath)
+				m_Operation.nOpState=LIST_CWD;
+			else if (!pData->path.IsEmpty() && pData->subdir!="")
+				m_Operation.nOpState=LIST_CWD2;
+			else
+			{
+				if (pData->nListMode & FZ_LIST_REALCHANGE)
+				{
+					if (pData->subdir == "")
+						m_Operation.nOpState = LIST_CWD;
+					else
+						m_Operation.nOpState = LIST_CWD2;
+				}
+				else
+				{
 #ifndef MPEXT_NO_CACHE
-                    if (pData->nListMode&FZ_LIST_USECACHE)
-                    {
-                        t_directory dir;
-                        CDirectoryCache cache;
-                        BOOL res = cache.Lookup(realpath, m_CurrentServer,dir);
-                        if (res)
-                        {
-                            BOOL bExact = TRUE;
-                            if (pData->nListMode & FZ_LIST_EXACT)
-                                for (int i = 0; i < dir.num; i++)
-                                    if (dir.direntry[i].bUnsure || (dir.direntry[i].size == -1 && !dir.direntry[i].dir))
-                                    {
-                                        bExact = FALSE;
-                                        break;
-                                    }
-                            if (bExact)
-                            {
-                                ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,0);
-                                SetDirectoryListing(&dir);
-                                ResetOperation(FZ_REPLY_OK);
-                                return;
-                            }
-                        }
-                    }
+					if (pData->nListMode&FZ_LIST_USECACHE)
+					{
+						t_directory dir;
+						CDirectoryCache cache;
+						BOOL res = cache.Lookup(realpath, m_CurrentServer,dir);
+						if (res)
+						{
+							BOOL bExact = TRUE;
+							if (pData->nListMode & FZ_LIST_EXACT)
+								for (int i = 0; i < dir.num; i++)
+									if (dir.direntry[i].bUnsure || (dir.direntry[i].size == -1 && !dir.direntry[i].dir))
+									{
+										bExact = FALSE;
+										break;
+									}
+							if (bExact)
+							{
+								ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,0);
+								SetDirectoryListing(&dir);
+								ResetOperation(FZ_REPLY_OK);
+								return;
+							}
+						}
+					}
 #endif
-                    m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);;
-                }
-            }
-        }
-        else
-            m_Operation.nOpState = LIST_PWD;
-    }
-    CString cmd;
-    if (m_Operation.nOpState == LIST_PWD)
-        cmd=_T("PWD");
-    else if (m_Operation.nOpState==LIST_CWD)
-        cmd=_T("CWD ") + pData->path.GetPath(); //Command to retrieve the current directory
-    else if (m_Operation.nOpState==LIST_PWD2)
-        cmd=_T("PWD");
-    else if (m_Operation.nOpState==LIST_CWD2)
-    {
-        if (!pData->subdir)
-        {
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        if (pData->subdir != _T("..") )
-        {
-            if (m_CurrentServer.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS)
-            {
-                CServerPath path = m_pOwner->GetCurrentPath();
-                path.AddSubdir(pData->subdir);
-                cmd = _T("CWD ") + path.GetPath();
-            }
-            else
-                cmd = _T("CWD ") + pData->subdir;
-        }
-        else
-        {
-            if (pData->lastCmdSentCDUP)
-            {
-                pData->lastCmdSentCDUP = false;
-                cmd = _T("CWD ..");
-            }
-            else
-            {
-                pData->lastCmdSentCDUP = true;
-                cmd = _T("CDUP");
-            }
-        }
-    }
-    else if (m_Operation.nOpState == LIST_PWD3)
-        cmd=_T("PWD");
-    else if (m_Operation.nOpState == LIST_MODE)
-    {
+					m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);;
+				}
+			}
+		}
+		else
+			m_Operation.nOpState = LIST_PWD;
+	}
+	CString cmd;
+	if (m_Operation.nOpState == LIST_PWD)
+		cmd=_T("PWD");
+	else if (m_Operation.nOpState==LIST_CWD)
+		cmd=_T("CWD ") + pData->path.GetPath(); //Command to retrieve the current directory
+	else if (m_Operation.nOpState==LIST_PWD2)
+		cmd=_T("PWD");
+	else if (m_Operation.nOpState==LIST_CWD2)
+	{
+		if (!pData->subdir)
+		{
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		if (pData->subdir != _T("..") )
+		{
+			if (m_CurrentServer.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS)
+			{
+				CServerPath path = m_pOwner->GetCurrentPath();
+				path.AddSubdir(pData->subdir);
+				cmd = _T("CWD ") + path.GetPath();
+			}
+			else
+				cmd = _T("CWD ") + pData->subdir;
+		}
+		else
+		{
+			if (pData->lastCmdSentCDUP)
+			{
+				pData->lastCmdSentCDUP = false;
+				cmd = _T("CWD ..");
+			}
+			else
+			{
+				pData->lastCmdSentCDUP = true;
+				cmd = _T("CDUP");
+			}
+		}
+	}
+	else if (m_Operation.nOpState == LIST_PWD3)
+		cmd=_T("PWD");
+	else if (m_Operation.nOpState == LIST_MODE)
+	{
 #ifdef MPEXT_NO_ZLIB
-        ASSERT(false);
+		ASSERT(false);
 #else
-        if (m_useZlib)
+		if (m_useZlib)
 #endif
-            cmd = _T("MODE S");
+			cmd = _T("MODE S");
 #ifndef MPEXT_NO_ZLIB
-        else
-            cmd = _T("MODE Z");
+		else
+			cmd = _T("MODE Z");
 #endif
-    }
-    else if (m_Operation.nOpState == LIST_OPTS)
-    {
+	}
+	else if (m_Operation.nOpState == LIST_OPTS)
+	{
 #ifdef MPEXT_NO_ZLIB
-        ASSERT(false);
+		ASSERT(false);
 #else
-        pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
-        cmd.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
+		pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
+		cmd.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
 #endif
-    }
-    else if (m_Operation.nOpState == LIST_PORT_PASV)
-    {
-        m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
+	}
+	else if (m_Operation.nOpState == LIST_PORT_PASV)
+	{
+		m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
 #ifndef MPEXT_NO_ZLIB
-        if (m_useZlib)
-        {
-            if (!m_pTransferSocket->InitZlib(m_zlibLevel))
-            {
-                ShowStatus(_T("Failed to initialize zlib"), 1);
-                ResetOperation(FZ_REPLY_ERROR);
-                return;
-            }
-        }
+		if (m_useZlib)
+		{
+			if (!m_pTransferSocket->InitZlib(m_zlibLevel))
+			{
+				ShowStatus(_T("Failed to initialize zlib"), 1);
+				ResetOperation(FZ_REPLY_ERROR);
+				return;
+			}
+		}
 #endif
-        m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
+		m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
 #ifndef MPEXT_NO_GSS
-        if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
-            m_pTransferSocket->UseGSS(m_pGssLayer);
+		if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
+			m_pTransferSocket->UseGSS(m_pGssLayer);
 #endif
-        m_pTransferSocket->SetFamily(GetFamily());
-        if (!m_pTransferSocket->Create(
+		m_pTransferSocket->SetFamily(GetFamily());
+		if (!m_pTransferSocket->Create(
 #ifndef MPEXT_NO_SSL
-          m_pSslLayer && m_bProtP
+				m_pSslLayer && m_bProtP
 #endif
-        ) ||
-            !m_pTransferSocket->AsyncSelect())
-        {
-            ShowStatus(_T("Failed to create socket"), 1);
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        if (pData->bPasv)
-            switch (GetFamily())
-            {
-            case AF_INET:
-                cmd = _T("PASV");
-                break;
-            case AF_INET6:
-                cmd = _T("EPSV");
-                break;
-            default:
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
-                ResetOperation(FZ_REPLY_ERROR);
-                return;
-            }
-        else
-        {
-            m_pTransferSocket->m_bListening=TRUE;
-            if (m_pProxyLayer)
-            {
-                SOCKADDR_IN addr;
-                int len=sizeof(addr);
-                if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
-                {
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-                else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
-                {
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
-            else
-            {
-                //Set up an active file transfer
-                CString tempHostname;
-                UINT nPort;
-
-                if (// create listen socket (let MFC choose the port) & start the socket listening
-                    !m_pTransferSocket->Listen() ||
-                    !m_pTransferSocket->GetSockName(tempHostname, nPort))
-                {
-                    ShowStatus(_T("Failed to create listen socket"), 1);
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-
-                CString host;
-                bool bError = false;
-
-                if (GetFamily() == AF_INET)
-                {
-                    host = COptions::GetOption(OPTION_TRANSFERIP);
-                    if (host != "")
-                    {
-                        DWORD ip = inet_addr(T2CA(host));
-                        if (ip != INADDR_NONE)
-                            host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
-                        else
-                        {
-                            hostent *fullname = gethostbyname(T2CA(host));
-                            if (!fullname)
-                                host = "";
-                            else
-                            {
-                                DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
-                                if (ip != INADDR_NONE)
-                                    host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
-                                else
-                                    host = "";
-                            }
-                        }
-                    }
-                    if (host == "")
-                    {
-                        UINT temp;
-
-                        if (!GetSockName(host, temp))
-                        {
-                            ShowStatus(_T("Failed to get socket address "), 1);
-                            bError = true;
-                        }
-
-                        host.Replace('.', ',');
-                    }
-
-                    if (!bError)
-                    {
-                        host.Format(host+",%d,%d", nPort/256, nPort%256);
-                        cmd = _T("PORT ") + host; // send PORT cmd to server
-                    }
-                }
-                else if (GetFamily() == AF_INET6)
-                {
-                    host = COptions::GetOption(OPTION_TRANSFERIP6);
-                    if (host != "")
-                    {
-                        USES_CONVERSION;
-                        addrinfo hints, *res;
-                        memset(&hints, 0, sizeof(addrinfo));
-                        hints.ai_family = AF_INET6;
-                        hints.ai_socktype = SOCK_STREAM;
-                        if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
-                        {
-                            host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
-                            p_freeaddrinfo(res);
-                        }
-                        else
-                            host = _T("");
-                    }
-                    if (host == "")
-                    {
-                        UINT temp;
-
-                        if(!GetSockName(host, temp))
-                            bError = true;
-                    }
-
-                    if (!bError)
-                    {
-                        // assamble EPRT command
-                        cmd.Format(_T("EPRT |2|") + host + "|%d|", nPort);
-                    }
-                }
-                else
-                {
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
-                    bError = true;
-                }
-
-                if (bError)
-                {
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
-        }
-    }
-    else if (m_Operation.nOpState==LIST_TYPE)
-        cmd=_T("TYPE A");
-    else if (m_Operation.nOpState==LIST_LIST)
-    {
-        if (!m_pTransferSocket)
-        {
-            LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-
-        m_pTransferSocket->SetActive();
-
-        cmd = _T("LIST");
+		) ||
+			!m_pTransferSocket->AsyncSelect())
+		{
+			ShowStatus(_T("Failed to create socket"), 1);
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		if (pData->bPasv)
+			switch (GetFamily())
+			{
+			case AF_INET:
+				cmd = _T("PASV");
+				break;
+			case AF_INET6:
+				cmd = _T("EPSV");
+				break;
+			default:
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
+				ResetOperation(FZ_REPLY_ERROR);
+				return;
+			}
+		else
+		{
+			m_pTransferSocket->m_bListening=TRUE;
+			if (m_pProxyLayer)
+			{
+				SOCKADDR_IN addr;
+				int len=sizeof(addr);
+				if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
+				{
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+				else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
+				{
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
+			else
+			{
+				//Set up an active file transfer
+				CString tempHostname;
+				UINT nPort;
+
+				if (// create listen socket (let MFC choose the port) & start the socket listening
+					!m_pTransferSocket->Listen() ||
+					!m_pTransferSocket->GetSockName(tempHostname, nPort))
+				{
+					ShowStatus(_T("Failed to create listen socket"), 1);
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+
+				CString host;
+				bool bError = false;
+
+				if (GetFamily() == AF_INET)
+				{
+					host = COptions::GetOption(OPTION_TRANSFERIP);
+					if (host != "")
+					{
+						DWORD ip = inet_addr(T2CA(host));
+						if (ip != INADDR_NONE)
+							host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
+						else
+						{
+							hostent *fullname = gethostbyname(T2CA(host));
+							if (!fullname)
+								host = "";
+							else
+							{
+								DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
+								if (ip != INADDR_NONE)
+									host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
+								else
+									host = "";
+							}
+						}
+					}
+					if (host == "")
+					{
+						UINT temp;
+
+						if (!GetSockName(host, temp))
+						{
+							ShowStatus(_T("Failed to get socket address "), 1);
+							bError = true;
+						}
+
+						host.Replace('.', ',');
+					}
+
+					if (!bError)
+					{
+						host.Format(host+",%d,%d", nPort/256, nPort%256);
+						cmd = _T("PORT ") + host; // send PORT cmd to server
+					}
+				}
+				else if (GetFamily() == AF_INET6)
+				{
+					host = COptions::GetOption(OPTION_TRANSFERIP6);
+					if (host != "")
+					{
+						USES_CONVERSION;
+						addrinfo hints, *res;
+						memset(&hints, 0, sizeof(addrinfo));
+						hints.ai_family = AF_INET6;
+						hints.ai_socktype = SOCK_STREAM;
+						if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
+						{
+							host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
+							p_freeaddrinfo(res);
+						}
+						else
+							host = _T("");
+					}
+					if (host == "")
+					{
+						UINT temp;
+
+						if(!GetSockName(host, temp))
+							bError = true;
+					}
+
+					if (!bError)
+					{
+						// assamble EPRT command
+						cmd.Format(_T("EPRT |2|") +	host + "|%d|", nPort);
+					}
+				}
+				else
+				{
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
+					bError = true;
+				}
+
+				if (bError)
+				{
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
+		}
+	}
+	else if (m_Operation.nOpState==LIST_TYPE)
+		cmd=_T("TYPE A");
+	else if (m_Operation.nOpState==LIST_LIST)
+	{
+		if (!m_pTransferSocket)
+		{
+			LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+
+		m_pTransferSocket->SetActive();
+
+		cmd = _T("LIST");
 #ifdef MPEXT
-        if (TRUE && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
+		if (TRUE && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
 #else
-        if (m_pOwner->GetOption(FZAPI_OPTION_SHOWHIDDEN) && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
+		if (m_pOwner->GetOption(FZAPI_OPTION_SHOWHIDDEN) && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
 #endif
-            cmd += _T(" -a");
-
-        if (!Send(cmd))
-            return;
-
-        pData->ListStartTime=CTime::GetCurrentTime();
-
-        if (pData->bPasv)
-        {
-            // if PASV create the socket & initiate outbound data channel connection
-            if (!m_pTransferSocket->Connect(pData->host,pData->port))
-            {
-                if (GetLastError()!=WSAEWOULDBLOCK)
-                {
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
-        }
-
-        return;
-    }
-    if (cmd != _T(""))
-        Send(cmd);
+			cmd += _T(" -a");
+
+		if (!Send(cmd))
+			return;
+
+		pData->ListStartTime=CTime::GetCurrentTime();
+
+		if (pData->bPasv)
+		{
+			// if PASV create the socket & initiate outbound data channel connection
+			if (!m_pTransferSocket->Connect(pData->host,pData->port))
+			{
+				if (GetLastError()!=WSAEWOULDBLOCK)
+				{
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
+		}
+
+		return;
+	}
+	if (cmd != _T(""))
+		Send(cmd);
 }
 
 void CFtpControlSocket::TransferEnd(int nMode)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("TransferEnd(%d)  OpMode=%d OpState=%d"), nMode, m_Operation.nOpMode, m_Operation.nOpState);
-    if (!m_Operation.nOpMode)
-    {
-        LogMessage(__FILE__, __LINE__, this,FZ_LOG_INFO, _T("Ignoring old TransferEnd message"));
-        return;
-    }
-    m_LastRecvTime=CTime::GetCurrentTime();
-    if (m_Operation.nOpMode&CSMODE_TRANSFER)
-        FileTransfer(0,TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
-    else if (m_Operation.nOpMode&CSMODE_LIST)
-        List(TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("TransferEnd(%d)  OpMode=%d OpState=%d"), nMode, m_Operation.nOpMode, m_Operation.nOpState);
+	if (!m_Operation.nOpMode)
+	{
+		LogMessage(__FILE__, __LINE__, this,FZ_LOG_INFO, _T("Ignoring old TransferEnd message"));
+		return;
+	}
+	m_LastRecvTime=CTime::GetCurrentTime();
+	if (m_Operation.nOpMode&CSMODE_TRANSFER)
+		FileTransfer(0,TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
+	else if (m_Operation.nOpMode&CSMODE_LIST)
+		List(TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
 }
 
 void CFtpControlSocket::OnClose(int nErrorCode)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnClose(%d)  OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
-    ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
-    if (m_pTransferSocket)
-    {
-        m_pTransferSocket->OnClose(0);
-        m_pTransferSocket->Close();
-        delete m_pTransferSocket;
-        m_pTransferSocket=0;
-        DoClose();
-        ShowStatus(IDS_ERRORMSG_TIMEOUT,1);
-        return;
-    }
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnClose(%d)  OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
+	ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
+	if (m_pTransferSocket)
+	{
+		m_pTransferSocket->OnClose(0);
+		m_pTransferSocket->Close();
+		delete m_pTransferSocket;
+		m_pTransferSocket=0;
+		DoClose();
+		ShowStatus(IDS_ERRORMSG_TIMEOUT,1);
+		return;
+	}
 #ifndef MPEXT_NO_SSL
-    if (m_bDidRejectCertificate)
-        DoClose(FZ_REPLY_CANCEL);
-    else
+	if (m_bDidRejectCertificate)
+		DoClose(FZ_REPLY_CANCEL);
+	else
 #endif
-        DoClose();
+		DoClose();
 }
 
 void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFinish/*=FALSE*/,int nError/*=0*/)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("FileTransfer(%d, %s, %d)  OpMode=%d OpState=%d"), transferfile,bFinish?_T("TRUE"):_T("FALSE"), nError, m_Operation.nOpMode, m_Operation.nOpState);
-
-    USES_CONVERSION;
-
-    #define FILETRANSFER_INIT           -1
-    #define FILETRANSFER_PWD            0
-    #define FILETRANSFER_CWD            1
-    #define FILETRANSFER_MKD            2
-    #define FILETRANSFER_CWD2           3
-    #define FILETRANSFER_PWD2           4
-    #define FILETRANSFER_LIST_MODE      5
-    #define FILETRANSFER_LIST_OPTS      6
-    #define FILETRANSFER_LIST_PORTPASV  7
-    #define FILETRANSFER_LIST_TYPE      8
-    #define FILETRANSFER_LIST_LIST      9
-    #define FILETRANSFER_LIST_WAITFINISH    10
-    #define FILETRANSFER_NOLIST_SIZE    11
-    #define FILETRANSFER_NOLIST_MDTM    12
-    #define FILETRANSFER_TYPE           13
-    #define FILETRANSFER_REST           14
-    #define FILETRANSFER_MODE           15
-    #define FILETRANSFER_OPTS           16
-    #define FILETRANSFER_PORTPASV       17
-    #define FILETRANSFER_RETRSTOR       18
-    #define FILETRANSFER_WAITFINISH     19
-
-    #define FILETRANSFER_WAIT           20
-
-
-    //Partial flowchart of FileTransfer
-    //
-    //            +----+
-    //     /------|Init|--------\
-    //     |      +----+        |
-    //     |         |          |
-    //     |     /---+          |
-    //     |     |   |          |
-    //     |     | +---+        |
-    //     |     | |PWD|        |
-    //     |     | +---+        |
-    //     |     |   |          |
-    //     |     \---+          |
-    //     |         |          |
-    //     |       +---+        |
-    //     |       |CWD|--\     |
-    //     |       +---+  |     |
-    //     |         |    |     |
-    //     |         |    |     |
-    //     |         |  +---+   |
-    //     |         |  |MKD|   |
-    //     |         |  +---+   |
-    //     |         |    |     |
-    //     |         |    |     |
-    //     |         |  +----+  |
-    //     |         |  |CWD2|  |
-    //     |         |  +----+  |
-    //     |         |    |     |
-    //     |         +----/     |
-    //     |         |          |
-    //     |       +---+        |
-    //     +-------|PWD|        |
-    //     |       +---+        |
-    //     |         |          |
-    //     |         +----------/
-    //     |         |
-    //     |    +---------+
-    //     |    |LIST_TYPE|
-    //     |    +---------+
-    //     |         |
-    //     |         |
-    //     |  +-------------+
-    //     |  |LIST_PORTPASV|
-    //     |  +-------------+
-    //     |         |
-    //     |         |
-    //     |    +---------+
-    //     |    |LIST_LIST|-----\ //List failes, maybe folder is list protected
-    //     |    +---------+     | //Use SIZE and MDTM to get file information
-    //     |         |        +----+
-    //     |         |        |SIZE|
-    //     |         |        +----+
-    //     |         |          |
-    //     |         |        +----+
-    //     |         |        |MDTM|
-    //     |         |        +----+
-    //     |         |          |
-    //     |         |          |
-    //     | +---------------+  |
-    //     | |LIST_WAITFINISH|  |
-    //     | +---------------+  |
-    //     |         |          |
-    //     |         |          |
-    //     |         +----------/
-    //     |         |
-    //     \---------+
-    //               |
-    //            +----+
-    //            |TYPE|
-    //            +----+
-    //               |
-    //               |
-    //          +--------+
-    //          |PORTPASV|--\
-    //          +--------+  |
-    //               |      |
-    //               |      |
-    //               |   +----+
-    //               |   |REST|
-    //               |   +----+
-    //               |      |
-    //               +------/
-    //               |
-    //          +--------+
-    //          |RETRSTOR|
-    //          +--------+
-    //               |
-    //               |
-    //         +----------+
-    //         |WAITFINISH|
-    //         +----------+
-
-    ASSERT(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_TRANSFER);
-    if (!m_pOwner->IsConnected())
-    {
-        m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
-        ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED);
-        return;
-    }
-
-    CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
-
-    //Process finish and error messages
-    if (bFinish || nError)
-    {
-        ASSERT(m_Operation.nOpMode&CSMODE_TRANSFER);
-
-        // APPE failed, ignore this reply
-        if (m_Operation.nOpMode == FILETRANSFER_WAIT && bFinish)
-            return;
-
-        if (!(m_Operation.nOpMode&CSMODE_TRANSFER))
-            return;
-
-        if (nError)
-        {
-            if (m_Operation.nOpState == FILETRANSFER_LIST_LIST && nError & CSMODE_TRANSFERERROR)
-            { //Don't abort operation, use fallback to SIZE and MDTM (when actual LIST reply comes in)
-                if (m_pTransferSocket)
-                    m_pTransferSocket=0;
-                delete m_pDirectoryListing;
-                m_pDirectoryListing=0;
-            }
-            else if (nError&CSMODE_TRANSFERTIMEOUT)
-                DoClose();
-            else
-                ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        if (m_Operation.nOpState <= FILETRANSFER_LIST_PORTPASV)
-        {
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        else if (m_Operation.nOpState<=FILETRANSFER_LIST_WAITFINISH)
-        {
-            if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
-            {
-                delete m_pDirectoryListing;
-                m_pDirectoryListing=0;
-                ResetOperation(FZ_REPLY_ERROR);
-                return;
-            }
-
-            int num=0;
-            pData->pDirectoryListing=new t_directory;
-            if (COptions::GetOptionVal(OPTION_DEBUGSHOWLISTING))
-                m_pTransferSocket->m_pListResult->SendToMessageLog(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID);
-            pData->pDirectoryListing->direntry=m_pTransferSocket->m_pListResult->getList(num, pData->ListStartTime);
-            pData->pDirectoryListing->num=num;
-            if (m_pTransferSocket->m_pListResult->m_server.nServerType&FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType&FZ_SERVERTYPE_FTP)
-                m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
-            pData->pDirectoryListing->server = m_CurrentServer;
-            pData->pDirectoryListing->path.SetServer(m_CurrentServer);
-            pData->pDirectoryListing->path = pData->transferfile.remotepath;
-            if (pData->rawpwd!="")
-            {
-                if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
-                {
-                    delete m_pDirectoryListing;
-                    m_pDirectoryListing=0;
-                    delete m_pTransferSocket;
-                    m_pTransferSocket=0;
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
-            else
-                pData->pDirectoryListing->path=pData->transferfile.remotepath;
-
-            if (m_Operation.nOpState!=FILETRANSFER_LIST_WAITFINISH)
-                return;
-        }
-        else if (m_Operation.nOpState <= FILETRANSFER_PORTPASV)
-        {
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        else if (m_Operation.nOpState<=FILETRANSFER_WAITFINISH)
-        {
-            if (m_pTransferSocket->m_bListening)
-            {
-                ResetOperation(FZ_REPLY_ERROR);
-                return;
-            }
-            pData->nGotTransferEndReply |= 2;
-            if (m_Operation.nOpState!=FILETRANSFER_WAITFINISH)
-                return;
-            else
-            {
-                delete m_pTransferSocket;
-                m_pTransferSocket=0;
-            }
-        }
-    }
-
-    //////////////////
-    //Initialization//
-    //////////////////
-    int nReplyError = 0;
-    if (m_Operation.nOpState == FILETRANSFER_INIT)
-    {
-        ASSERT(transferfile);
-        ASSERT(!m_Operation.nOpMode);
-        ASSERT(!m_Operation.pData);
-
-        CString str;
-        str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
-                    transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile) : transferfile->localfile);
-        ShowStatus(str,0);
-
-        m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
-
-        m_Operation.pData=new CFileTransferData;
-        pData=static_cast<CFileTransferData *>(m_Operation.pData);
-
-        if (COptions::GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY && !m_CurrentServer.fwbypass)
-            pData->bPasv = TRUE;
-        else if (m_CurrentServer.nPasv == 1)
-            pData->bPasv = TRUE;
-        else if (m_CurrentServer.nPasv == 2)
-            pData->bPasv = FALSE;
-        else
-            pData->bPasv = COptions::GetOptionVal(OPTION_PASV);
-
-        //Replace invalid characters in the local filename
-        int pos=transferfile->localfile.ReverseFind('\\');
-        for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
-            if (transferfile->localfile[i]==':')
-                transferfile->localfile.SetAt(i, '_');
-
-        pData->transferfile=*transferfile;
-        pData->transferdata.transfersize=pData->transferfile.size;
-        pData->transferdata.transferleft=pData->transferfile.size;
-        pData->transferdata.bResume = FALSE;
-        pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
-
-        CServerPath path;
-        VERIFY(m_pOwner->GetCurrentPath(path));
-        if (path == pData->transferfile.remotepath)
-        {
-            if (m_pDirectoryListing)
-            {
-                m_Operation.nOpState=FILETRANSFER_TYPE;
-                CString remotefile=pData->transferfile.remotefile;
-                int i;
-                for (i=0; i<m_pDirectoryListing->num; i++)
-                {
-                    if (m_pDirectoryListing->direntry[i].name==remotefile &&
-                        ( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
-                    {
-                        delete m_pDirectoryListing;
-                        m_pDirectoryListing=0;
-                        m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-                        break;
-                    }
-                }
-                if (m_pDirectoryListing && i==m_pDirectoryListing->num)
-                {
-                    nReplyError = CheckOverwriteFile();
-                    if (!nReplyError)
-                    {
-                        if (pData->transferfile.get)
-                        {
-                            CString path=pData->transferfile.localfile;
-                            if (path.ReverseFind('\\')!=-1)
-                            {
-                                path=path.Left(path.ReverseFind('\\')+1);
-                                CString path2;
-                                while (path!="")
-                                {
-                                    path2+=path.Left(path.Find( _T("\\") )+1);
-                                    path=path.Mid(path.Find( _T("\\") )+1);
-                                    CreateDirectory(path2, 0);
-                                }
-                            }
-                        }
-                    }
-                }
-            }
-            else
-            {
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("FileTransfer(%d, %s, %d)  OpMode=%d OpState=%d"), transferfile,bFinish?_T("TRUE"):_T("FALSE"), nError, m_Operation.nOpMode, m_Operation.nOpState);
+
+	USES_CONVERSION;
+
+	#define FILETRANSFER_INIT			-1
+	#define FILETRANSFER_PWD			0
+	#define FILETRANSFER_CWD			1
+	#define FILETRANSFER_MKD			2
+	#define FILETRANSFER_CWD2			3
+	#define FILETRANSFER_PWD2			4
+	#define FILETRANSFER_LIST_MODE		5
+	#define FILETRANSFER_LIST_OPTS		6
+	#define FILETRANSFER_LIST_PORTPASV	7
+	#define FILETRANSFER_LIST_TYPE		8
+	#define FILETRANSFER_LIST_LIST		9
+	#define FILETRANSFER_LIST_WAITFINISH	10
+	#define FILETRANSFER_NOLIST_SIZE	11
+	#define FILETRANSFER_NOLIST_MDTM	12
+	#define FILETRANSFER_TYPE			13
+	#define FILETRANSFER_REST			14
+	#define FILETRANSFER_MODE			15
+	#define FILETRANSFER_OPTS			16
+	#define FILETRANSFER_PORTPASV		17
+	#define FILETRANSFER_RETRSTOR		18
+	#define FILETRANSFER_WAITFINISH		19
+
+	#define FILETRANSFER_WAIT			20
+
+
+	//Partial flowchart of FileTransfer
+	//
+	//            +----+
+	//     /------|Init|--------\
+	//     |      +----+        |
+	//     |         |          |
+	//     |     /---+          |
+	//     |     |   |          |
+	//     |     | +---+        |
+	//     |     | |PWD|        |
+	//     |     | +---+        |
+	//     |     |   |          |
+	//     |     \---+          |
+	//     |         |          |
+	//     |       +---+        |
+	//     |       |CWD|--\     |
+	//     |       +---+  |     |
+	//     |         |    |     |
+	//     |         |    |     |
+	//     |         |  +---+   |
+	//     |         |  |MKD|   |
+	//     |         |  +---+   |
+	//     |         |    |     |
+	//     |         |    |     |
+	//     |         |  +----+  |
+	//     |         |  |CWD2|  |
+	//     |         |  +----+  |
+	//     |         |    |     |
+	//     |         +----/     |
+	//     |         |          |
+	//     |       +---+        |
+	//     +-------|PWD|        |
+	//     |       +---+        |
+	//     |         |          |
+	//     |         +----------/
+	//     |         |
+	//     |    +---------+
+	//     |    |LIST_TYPE|
+	//     |    +---------+
+	//     |         |
+	//     |         |
+	//     |  +-------------+
+	//     |  |LIST_PORTPASV|
+	//     |  +-------------+
+	//     |         |
+	//     |         |
+	//     |    +---------+
+	//     |    |LIST_LIST|-----\ //List failes, maybe folder is list protected
+	//     |    +---------+     | //Use SIZE and MDTM to get file information
+	//     |         |        +----+
+	//     |         |        |SIZE|
+	//     |         |        +----+
+	//     |         |          |
+	//     |         |        +----+
+	//     |         |        |MDTM|
+	//     |         |        +----+
+	//     |         |          |
+	//     |         |          |
+	//     | +---------------+  |
+	//     | |LIST_WAITFINISH|  |
+	//     | +---------------+  |
+	//     |         |          |
+	//     |         |          |
+	//     |         +----------/
+	//     |         |
+	//     \---------+
+	//               |
+	//            +----+
+	//            |TYPE|
+	//            +----+
+	//               |
+	//               |
+	//          +--------+
+	//          |PORTPASV|--\
+	//          +--------+  |
+	//               |      |
+	//               |      |
+	//               |   +----+
+	//               |   |REST|
+	//               |   +----+
+	//				 |      |
+	//               +------/
+	//               |
+	//          +--------+
+	//          |RETRSTOR|
+	//          +--------+
+	//               |
+	//               |
+	//         +----------+
+	//         |WAITFINISH|
+	//         +----------+
+
+	ASSERT(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_TRANSFER);
+	if (!m_pOwner->IsConnected())
+	{
+		m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
+		ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED);
+		return;
+	}
+
+	CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
+
+	//Process finish and error messages
+	if (bFinish || nError)
+	{
+		ASSERT(m_Operation.nOpMode&CSMODE_TRANSFER);
+
+		// APPE failed, ignore this reply
+		if (m_Operation.nOpMode == FILETRANSFER_WAIT && bFinish)
+			return;
+
+		if (!(m_Operation.nOpMode&CSMODE_TRANSFER))
+			return;
+
+		if (nError)
+		{
+			if (m_Operation.nOpState == FILETRANSFER_LIST_LIST && nError & CSMODE_TRANSFERERROR)
+			{ //Don't abort operation, use fallback to SIZE and MDTM (when actual LIST reply comes in)
+				if (m_pTransferSocket)
+					m_pTransferSocket=0;
+				delete m_pDirectoryListing;
+				m_pDirectoryListing=0;
+			}
+			else if (nError&CSMODE_TRANSFERTIMEOUT)
+				DoClose();
+			else
+				ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		if (m_Operation.nOpState <= FILETRANSFER_LIST_PORTPASV)
+		{
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		else if (m_Operation.nOpState<=FILETRANSFER_LIST_WAITFINISH)
+		{
+			if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
+			{
+				delete m_pDirectoryListing;
+				m_pDirectoryListing=0;
+				ResetOperation(FZ_REPLY_ERROR);
+				return;
+			}
+
+			int num=0;
+			pData->pDirectoryListing=new t_directory;
+			if (COptions::GetOptionVal(OPTION_DEBUGSHOWLISTING))
+				m_pTransferSocket->m_pListResult->SendToMessageLog(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID);
+			pData->pDirectoryListing->direntry=m_pTransferSocket->m_pListResult->getList(num, pData->ListStartTime);
+			pData->pDirectoryListing->num=num;
+			if (m_pTransferSocket->m_pListResult->m_server.nServerType&FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType&FZ_SERVERTYPE_FTP)
+				m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
+			pData->pDirectoryListing->server = m_CurrentServer;
+			pData->pDirectoryListing->path.SetServer(m_CurrentServer);
+			pData->pDirectoryListing->path = pData->transferfile.remotepath;
+			if (pData->rawpwd!="")
+			{
+				if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
+				{
+					delete m_pDirectoryListing;
+					m_pDirectoryListing=0;
+					delete m_pTransferSocket;
+					m_pTransferSocket=0;
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
+			else
+				pData->pDirectoryListing->path=pData->transferfile.remotepath;
+
+			if (m_Operation.nOpState!=FILETRANSFER_LIST_WAITFINISH)
+				return;
+		}
+		else if (m_Operation.nOpState <= FILETRANSFER_PORTPASV)
+		{
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		else if (m_Operation.nOpState<=FILETRANSFER_WAITFINISH)
+		{
+			if (m_pTransferSocket->m_bListening)
+			{
+				ResetOperation(FZ_REPLY_ERROR);
+				return;
+			}
+			pData->nGotTransferEndReply |= 2;
+			if (m_Operation.nOpState!=FILETRANSFER_WAITFINISH)
+				return;
+			else
+			{
+				delete m_pTransferSocket;
+				m_pTransferSocket=0;
+			}
+		}
+	}
+
+	//////////////////
+	//Initialization//
+	//////////////////
+	int nReplyError = 0;
+	if (m_Operation.nOpState == FILETRANSFER_INIT)
+	{
+		ASSERT(transferfile);
+		ASSERT(!m_Operation.nOpMode);
+		ASSERT(!m_Operation.pData);
+
+		CString str;
+		str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
+					transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile) : transferfile->localfile);
+		ShowStatus(str,0);
+
+		m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
+
+		m_Operation.pData=new CFileTransferData;
+		pData=static_cast<CFileTransferData *>(m_Operation.pData);
+
+		if (COptions::GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY && !m_CurrentServer.fwbypass)
+			pData->bPasv = TRUE;
+		else if (m_CurrentServer.nPasv == 1)
+			pData->bPasv = TRUE;
+		else if (m_CurrentServer.nPasv == 2)
+			pData->bPasv = FALSE;
+		else
+			pData->bPasv = COptions::GetOptionVal(OPTION_PASV);
+
+		//Replace invalid characters in the local filename
+		int pos=transferfile->localfile.ReverseFind('\\');
+		for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
+			if (transferfile->localfile[i]==':')
+				transferfile->localfile.SetAt(i, '_');
+
+		pData->transferfile=*transferfile;
+		pData->transferdata.transfersize=pData->transferfile.size;
+		pData->transferdata.transferleft=pData->transferfile.size;
+		pData->transferdata.bResume = FALSE;
+		pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
+
+		CServerPath path;
+		VERIFY(m_pOwner->GetCurrentPath(path));
+		if (path == pData->transferfile.remotepath)
+		{
+			if (m_pDirectoryListing)
+			{
+				m_Operation.nOpState=FILETRANSFER_TYPE;
+				CString remotefile=pData->transferfile.remotefile;
+				int i;
+				for (i=0; i<m_pDirectoryListing->num; i++)
+				{
+					if (m_pDirectoryListing->direntry[i].name==remotefile &&
+						( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
+					{
+						delete m_pDirectoryListing;
+						m_pDirectoryListing=0;
+						m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+						break;
+					}
+				}
+				if (m_pDirectoryListing && i==m_pDirectoryListing->num)
+				{
+					nReplyError = CheckOverwriteFile();
+					if (!nReplyError)
+					{
+						if (pData->transferfile.get)
+						{
+							CString path=pData->transferfile.localfile;
+							if (path.ReverseFind('\\')!=-1)
+							{
+								path=path.Left(path.ReverseFind('\\')+1);
+								CString path2;
+								while (path!="")
+								{
+									path2+=path.Left(path.Find( _T("\\") )+1);
+									path=path.Mid(path.Find( _T("\\") )+1);
+									CreateDirectory(path2, 0);
+								}
+							}
+						}
+					}
+				}
+			}
+			else
+			{
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
-                t_server server;
-                m_pOwner->GetCurrentServer(server);
-                t_directory dir;
-                BOOL res = cache.Lookup(pData->transferfile.remotepath,server,dir);
-                if (res)
-                {
-                    CString remotefile=pData->transferfile.remotefile;
-                    int i;
-                    for (i=0; i<dir.num; i++)
-                    {
-                        if (dir.direntry[i].name==remotefile &&
-                            ( dir.direntry[i].bUnsure || dir.direntry[i].size==-1 ))
-                        {
-                            m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-                            break;
-                        }
-                    }
-                    if (i == dir.num)
-                    {
-                        SetDirectoryListing(&dir);
-                        m_Operation.nOpState=FILETRANSFER_TYPE;
-                        nReplyError = CheckOverwriteFile();
-                        if (!nReplyError)
-                        {
-                            if (pData->transferfile.get)
-                            {
-                                CString path=pData->transferfile.localfile;
-                                if (path.ReverseFind('\\')!=-1)
-                                {
-                                    path=path.Left(path.ReverseFind('\\')+1);
-                                    CString path2;
-                                    while (path!="")
-                                    {
-                                        path2+=path.Left(path.Find( _T("\\") )+1);
-                                        path=path.Mid(path.Find(_T( "\\") )+1);
-                                        CreateDirectory(path2, 0);
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-                else
+				CDirectoryCache cache;
+				t_server server;
+				m_pOwner->GetCurrentServer(server);
+				t_directory dir;
+				BOOL res = cache.Lookup(pData->transferfile.remotepath,server,dir);
+				if (res)
+				{
+					CString remotefile=pData->transferfile.remotefile;
+					int i;
+					for (i=0; i<dir.num; i++)
+					{
+						if (dir.direntry[i].name==remotefile &&
+							( dir.direntry[i].bUnsure || dir.direntry[i].size==-1 ))
+						{
+							m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+							break;
+						}
+					}
+					if (i == dir.num)
+					{
+						SetDirectoryListing(&dir);
+						m_Operation.nOpState=FILETRANSFER_TYPE;
+						nReplyError = CheckOverwriteFile();
+						if (!nReplyError)
+						{
+							if (pData->transferfile.get)
+							{
+								CString path=pData->transferfile.localfile;
+								if (path.ReverseFind('\\')!=-1)
+								{
+									path=path.Left(path.ReverseFind('\\')+1);
+									CString path2;
+									while (path!="")
+									{
+										path2+=path.Left(path.Find( _T("\\") )+1);
+										path=path.Mid(path.Find(_T( "\\") )+1);
+										CreateDirectory(path2, 0);
+									}
+								}
+							}
+						}
+					}
+				}
+				else
 #endif
-                    m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-            }
-        }
-        else
-        {
-            if (path.IsEmpty())
-                m_Operation.nOpState = FILETRANSFER_PWD;
-            else
-                m_Operation.nOpState = FILETRANSFER_CWD;
-        }
-    }
-    else
-    {
-        ///////////
-        //Replies//
-        ///////////
-        int code = GetReplyCode();
-        switch(m_Operation.nOpState)
-        {
-        case FILETRANSFER_PWD:
-            if (code != 2 && code != 3)
-            {
-                nReplyError = FZ_REPLY_ERROR;
-                break;
-            }
-
-            pData->rawpwd = GetReply();
-            if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
-                pData->rawpwd[0] != '/')
-            {
-                m_mayBeMvsFilesystem = false;
-                m_mayBeBS2000Filesystem = false;
-
-                if (m_mayBeBS2000Filesystem)
-                    m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
-                else
-                    m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
-
-                pData->transferfile.remotepath.SetServer(m_CurrentServer);
-            }
-            if (!ParsePwdReply(pData->rawpwd))
-                return;
-
-            if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
-            {
+					m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+			}
+		}
+		else
+		{
+			if (path.IsEmpty())
+				m_Operation.nOpState = FILETRANSFER_PWD;
+			else
+				m_Operation.nOpState = FILETRANSFER_CWD;
+		}
+	}
+	else
+	{
+		///////////
+		//Replies//
+		///////////
+		int code = GetReplyCode();
+		switch(m_Operation.nOpState)
+		{
+		case FILETRANSFER_PWD:
+			if (code != 2 && code != 3)
+			{
+				nReplyError = FZ_REPLY_ERROR;
+				break;
+			}
+
+			pData->rawpwd = GetReply();
+			if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
+				pData->rawpwd[0] != '/')
+			{
+				m_mayBeMvsFilesystem = false;
+				m_mayBeBS2000Filesystem = false;
+
+				if (m_mayBeBS2000Filesystem)
+					m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
+				else
+					m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
+
+				pData->transferfile.remotepath.SetServer(m_CurrentServer);
+			}
+			if (!ParsePwdReply(pData->rawpwd))
+				return;
+
+			if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
+			{
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
-                t_server server;
-                m_pOwner->GetCurrentServer(server);
-                t_directory dir;
-                BOOL res = cache.Lookup(pData->transferfile.remotepath,server,dir);
-                if (res)
-                {
-                    CString remotefile = pData->transferfile.remotefile;
-                    int i;
-                    for (i = 0; i < dir.num; i++)
-                    {
-                        if (dir.direntry[i].name == remotefile &&
-                            (dir.direntry[i].bUnsure || dir.direntry[i].size == -1))
-                        {
-                            m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-                            break;
-                        }
-                    }
-                    if (i == dir.num)
-                    {
-                        SetDirectoryListing(&dir);
-                        m_Operation.nOpState=FILETRANSFER_TYPE;
-                        nReplyError = CheckOverwriteFile();
-                        if (!nReplyError)
-                        {
-                            if (pData->transferfile.get)
-                            {
-                                CString path=pData->transferfile.localfile;
-                                if (path.ReverseFind('\\')!=-1)
-                                {
-                                    path=path.Left(path.ReverseFind('\\')+1);
-                                    CString path2;
-                                    while (path!="")
-                                    {
-                                        path2+=path.Left(path.Find( _T("\\") )+1);
-                                        path=path.Mid(path.Find(_T( "\\") )+1);
-                                        int res = CreateDirectory(path2, 0);
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-                else
+				CDirectoryCache cache;
+				t_server server;
+				m_pOwner->GetCurrentServer(server);
+				t_directory dir;
+				BOOL res = cache.Lookup(pData->transferfile.remotepath,server,dir);
+				if (res)
+				{
+					CString remotefile = pData->transferfile.remotefile;
+					int i;
+					for (i = 0; i < dir.num; i++)
+					{
+						if (dir.direntry[i].name == remotefile &&
+							(dir.direntry[i].bUnsure || dir.direntry[i].size == -1))
+						{
+							m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+							break;
+						}
+					}
+					if (i == dir.num)
+					{
+						SetDirectoryListing(&dir);
+						m_Operation.nOpState=FILETRANSFER_TYPE;
+						nReplyError = CheckOverwriteFile();
+						if (!nReplyError)
+						{
+							if (pData->transferfile.get)
+							{
+								CString path=pData->transferfile.localfile;
+								if (path.ReverseFind('\\')!=-1)
+								{
+									path=path.Left(path.ReverseFind('\\')+1);
+									CString path2;
+									while (path!="")
+									{
+										path2+=path.Left(path.Find( _T("\\") )+1);
+										path=path.Mid(path.Find(_T( "\\") )+1);
+										int res = CreateDirectory(path2, 0);
+									}
+								}
+							}
+						}
+					}
+				}
+				else
 #endif
-                    m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-            }
-            else
-                m_Operation.nOpState = LIST_CWD;
-            break;
-        case FILETRANSFER_CWD:
-            if (code != 2 && code != 3)
-                if (pData->transferfile.get)
-                {
-                    pData->bUseAbsolutePaths = TRUE;
-                    m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
-                }
-                else
-                    m_Operation.nOpState = FILETRANSFER_MKD;
-            else
-                m_Operation.nOpState = FILETRANSFER_PWD2;
-            break;
-        case FILETRANSFER_MKD:
-            switch(pData->nMKDOpState)
-            {
-            case MKD_FINDPARENT:
-                {
-                    if (code == 2 || code == 3)
-                    {
-                        m_pOwner->SetCurrentPath(pData->MKDCurrent);
+					m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+			}
+			else
+				m_Operation.nOpState = LIST_CWD;
+			break;
+		case FILETRANSFER_CWD:
+			if (code != 2 && code != 3)
+				if (pData->transferfile.get)
+				{
+					pData->bUseAbsolutePaths = TRUE;
+					m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
+				}
+				else
+					m_Operation.nOpState = FILETRANSFER_MKD;
+			else
+				m_Operation.nOpState = FILETRANSFER_PWD2;
+			break;
+		case FILETRANSFER_MKD:
+			switch(pData->nMKDOpState)
+			{
+			case MKD_FINDPARENT:
+				{
+					if (code == 2 || code == 3)
+					{
+						m_pOwner->SetCurrentPath(pData->MKDCurrent);
 
 #ifndef MPEXT_NO_CACHE
-                        if (!m_pDirectoryListing)
-                        {
-                            CDirectoryCache cache;
-                            t_directory dir;
-                            BOOL res = cache.Lookup(pData->MKDCurrent, m_CurrentServer, dir, TRUE);
-                            if (res)
-                                SetDirectoryListing(&dir);
-                        }
+						if (!m_pDirectoryListing)
+						{
+							CDirectoryCache cache;
+							t_directory dir;
+							BOOL res = cache.Lookup(pData->MKDCurrent, m_CurrentServer, dir, TRUE);
+							if (res)
+								SetDirectoryListing(&dir);
+						}
 #endif
 
-                        pData->nMKDOpState=MKD_CHANGETOSUBDIR;
-                        pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
-                        CString Segment=pData->MKDSegments.front();
-                        pData->MKDSegments.pop_front();
-                        if (!Send( _T("MKD ") + Segment))
-                            return;
-                    }
-                    else
-                    {
-                        if (!pData->MKDCurrent.HasParent())
-                            nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
-                        else
-                        {
-                            pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
-                            pData->MKDCurrent=pData->MKDCurrent.GetParent();
-                            if (!Send("CWD "+pData->MKDCurrent.GetPath()))
-                                return;
-                        }
-                    }
-                }
-                break;
-            case MKD_MAKESUBDIRS:
-                {
-                    if (code == 2 || code == 3)
-                    { //Create dir entry in parent dir
-                        ASSERT(!pData->MKDSegments.empty());
-                        pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
-                        CString Segment=pData->MKDSegments.front();
-                        pData->MKDSegments.pop_front();
-                        if (Send( _T("MKD ") + Segment))
-                            pData->nMKDOpState=MKD_CHANGETOSUBDIR;
-                        else
-                            return;
-                    }
-                    else
-                        nReplyError=FZ_REPLY_ERROR;
-                }
-                break;
-            case MKD_CHANGETOSUBDIR:
-                {
-                    if (code == 2 || code == 3 || //Creation successful
-                        m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
-                    {
-                        CServerPath path2 = pData->MKDCurrent;
-                        if (path2.HasParent())
-                        {
-                            CString name=path2.GetLastSegment();
-                            path2=path2.GetParent();
+						pData->nMKDOpState=MKD_CHANGETOSUBDIR;
+						pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
+						CString Segment=pData->MKDSegments.front();
+						pData->MKDSegments.pop_front();
+						if (!Send( _T("MKD ") + Segment))
+							return;
+					}
+					else
+					{
+						if (!pData->MKDCurrent.HasParent())
+							nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
+						else
+						{
+							pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
+							pData->MKDCurrent=pData->MKDCurrent.GetParent();
+							if (!Send("CWD "+pData->MKDCurrent.GetPath()))
+								return;
+						}
+					}
+				}
+				break;
+			case MKD_MAKESUBDIRS:
+				{
+					if (code == 2 || code == 3)
+					{ //Create dir entry in parent dir
+						ASSERT(!pData->MKDSegments.empty());
+						pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
+						CString Segment=pData->MKDSegments.front();
+						pData->MKDSegments.pop_front();
+						if (Send( _T("MKD ") + Segment))
+							pData->nMKDOpState=MKD_CHANGETOSUBDIR;
+						else
+							return;
+					}
+					else
+						nReplyError=FZ_REPLY_ERROR;
+				}
+				break;
+			case MKD_CHANGETOSUBDIR:
+				{
+					if (code == 2 || code == 3 || //Creation successful
+						m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
+					{
+						CServerPath path2 = pData->MKDCurrent;
+						if (path2.HasParent())
+						{
+							CString name=path2.GetLastSegment();
+							path2=path2.GetParent();
 #ifndef MPEXT_NO_CACHE
-                            CDirectoryCache cache;
-                            cache.Lock();
-                            t_directory dir;
-                            BOOL bCached=TRUE;
-                            BOOL res=cache.Lookup(path2,m_CurrentServer,dir);
-                            if (!res)
-                                bCached=FALSE;
+							CDirectoryCache cache;
+							cache.Lock();
+							t_directory dir;
+							BOOL bCached=TRUE;
+							BOOL res=cache.Lookup(path2,m_CurrentServer,dir);
+							if (!res)
+								bCached=FALSE;
 #else
-                            t_directory dir;
-                            BOOL res=FALSE;
+							t_directory dir;
+							BOOL res=FALSE;
 #endif
-                            if (!res && m_pDirectoryListing)
-                            {
-                                if (m_pDirectoryListing->path==path2)
-                                {
-                                    dir=*m_pDirectoryListing;
-                                    res=TRUE;
-                                }
-                            }
-                            t_directory WorkingDir;
-                            BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
-                            if (!res && bFound)
-                                if (WorkingDir.path==path2)
-                                {
-                                    dir=WorkingDir;
-                                    res=TRUE;
-                                }
-                            if (!res)
-                            {
-                                dir.path=path2;
-                                dir.server=m_CurrentServer;
-                            }
-
-                            int i;
-                            for (i=0; i<dir.num; i++)
-                                if (dir.direntry[i].name == name)
-                                {
-                                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Dir already exists in cache!"));
-                                    break;
-                                }
-                            if (i==dir.num)
-                            {
-                                t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
-                                for (i=0;i<dir.num;i++)
-                                    entries[i]=dir.direntry[i];
-                                entries[i].name=name;
-                                entries[i].lName=name;
-                                entries[i].lName.MakeLower();
-                                entries[i].dir=TRUE;
-                                entries[i].date.hasdate=FALSE;
-                                entries[i].size=-1;
-                                entries[i].bUnsure=FALSE;
-                                delete [] dir.direntry;
-                                dir.direntry=entries;
-                                dir.num++;
+							if (!res && m_pDirectoryListing)
+							{
+								if (m_pDirectoryListing->path==path2)
+								{
+									dir=*m_pDirectoryListing;
+									res=TRUE;
+								}
+							}
+							t_directory WorkingDir;
+							BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
+							if (!res && bFound)
+								if (WorkingDir.path==path2)
+								{
+									dir=WorkingDir;
+									res=TRUE;
+								}
+							if (!res)
+							{
+								dir.path=path2;
+								dir.server=m_CurrentServer;
+							}
+
+							int i;
+							for (i=0; i<dir.num; i++)
+								if (dir.direntry[i].name == name)
+								{
+									LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Dir already exists in cache!"));
+									break;
+								}
+							if (i==dir.num)
+							{
+								t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
+								for (i=0;i<dir.num;i++)
+									entries[i]=dir.direntry[i];
+								entries[i].name=name;
+								entries[i].lName=name;
+								entries[i].lName.MakeLower();
+								entries[i].dir=TRUE;
+								entries[i].date.hasdate=FALSE;
+								entries[i].size=-1;
+								entries[i].bUnsure=FALSE;
+								delete [] dir.direntry;
+								dir.direntry=entries;
+								dir.num++;
 #ifndef MPEXT_NO_CACHE
-                                cache.Store(dir, bCached);
+								cache.Store(dir, bCached);
 #endif
-                                BOOL updated=FALSE;
-                                if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
-                                {
-                                    updated=TRUE;
-                                    SetDirectoryListing(&dir);
-                                }
-                                if (!updated)
-                                    if (WorkingDir.path==dir.path)
-                                    {
-                                        updated=TRUE;
-                                        m_pOwner->SetWorkingDir(&dir);
-                                    }
-                            }
+								BOOL updated=FALSE;
+								if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
+								{
+									updated=TRUE;
+									SetDirectoryListing(&dir);
+								}
+								if (!updated)
+									if (WorkingDir.path==dir.path)
+									{
+										updated=TRUE;
+										m_pOwner->SetWorkingDir(&dir);
+									}
+							}
 #ifndef MPEXT_NO_CACHE
-                            cache.Unlock();
+							cache.Unlock();
 #endif
-                        }
-
-                    }
-
-                    //Continue operation even if MKD failed, maybe another thread did create this directory for us
-                    if (pData->MKDSegments.empty())
-                        m_Operation.nOpState=FILETRANSFER_CWD2;
-                    else
-                    {
-                        if (Send( _T("CWD ") + pData->MKDCurrent.GetPath()))
-                            pData->nMKDOpState=MKD_MAKESUBDIRS;
-                        else
-                            return;
-                    }
-                }
-                break;
-            default:
-                ASSERT(FALSE);
-            }
-
-            break;
-        case FILETRANSFER_CWD2:
-            if (code != 2 && code != 3)
-                if (code == 4)
-                    nReplyError=FZ_REPLY_ERROR;
-                else
-                    nReplyError=FZ_REPLY_CRITICALERROR;
-            else
-                m_Operation.nOpState=FILETRANSFER_PWD2;
-            break;
-        case FILETRANSFER_PWD2:
-            if (code != 2 && code != 2)
-                nReplyError = FZ_REPLY_ERROR;
-            else
-            {
-                pData->rawpwd = GetReply();
-                if (!ParsePwdReply(pData->rawpwd))
-                    return;
-
-                if (m_pOwner->GetCurrentPath() != pData->transferfile.remotepath)
-                {
-                    CString msg;
-                    msg.Format(_T("Real path and requested remote path do not match: \"%s\"  \"%s\""), m_pOwner->GetCurrentPath().GetSafePath(), pData->transferfile.remotepath.GetSafePath());
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, msg);
-                    nReplyError = FZ_REPLY_CRITICALERROR;
-                }
-                else
-                {
+						}
+
+					}
+
+					//Continue operation even if MKD failed, maybe another thread did create this directory for us
+					if (pData->MKDSegments.empty())
+						m_Operation.nOpState=FILETRANSFER_CWD2;
+					else
+					{
+						if (Send( _T("CWD ") + pData->MKDCurrent.GetPath()))
+							pData->nMKDOpState=MKD_MAKESUBDIRS;
+						else
+							return;
+					}
+				}
+				break;
+			default:
+				ASSERT(FALSE);
+			}
+
+			break;
+		case FILETRANSFER_CWD2:
+			if (code != 2 && code != 3)
+				if (code == 4)
+					nReplyError=FZ_REPLY_ERROR;
+				else
+					nReplyError=FZ_REPLY_CRITICALERROR;
+			else
+				m_Operation.nOpState=FILETRANSFER_PWD2;
+			break;
+		case FILETRANSFER_PWD2:
+			if (code != 2 && code != 2)
+				nReplyError = FZ_REPLY_ERROR;
+			else
+			{
+				pData->rawpwd = GetReply();
+				if (!ParsePwdReply(pData->rawpwd))
+					return;
+
+				if (m_pOwner->GetCurrentPath() != pData->transferfile.remotepath)
+				{
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Real path and requested remote path do not match: \"%s\"  \"%s\""), m_pOwner->GetCurrentPath().GetSafePath(), pData->transferfile.remotepath.GetSafePath());
+					nReplyError = FZ_REPLY_CRITICALERROR;
+				}
+				else
+				{
 #ifndef MPEXT_NO_CACHE
-                    CDirectoryCache cache;
-                    t_server server;
-                    m_pOwner->GetCurrentServer(server);
-                    t_directory dir;
-                    BOOL res = cache.Lookup(pData->transferfile.remotepath, server,dir);
-                    if (res)
-                    {
-                        CString remotefile = pData->transferfile.remotefile;
-                        int i;
-                        for (i = 0; i < dir.num; i++)
-                        {
-                            if (dir.direntry[i].name == remotefile &&
-                                (dir.direntry[i].bUnsure || dir.direntry[i].size == -1))
-                            {
-                                m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-                                break;
-                            }
-                        }
-                        if (i == dir.num)
-                        {
-                            SetDirectoryListing(&dir);
-                            m_Operation.nOpState=FILETRANSFER_TYPE;
-                            nReplyError=CheckOverwriteFile();
-                            if (!nReplyError)
-                            {
-                                if (pData->transferfile.get)
-                                {
-                                    CString path=pData->transferfile.localfile;
-                                    if (path.ReverseFind('\\')!=-1)
-                                    {
-                                        path=path.Left(path.ReverseFind('\\')+1);
-                                        CString path2;
-                                        while (path!="")
-                                        {
-                                            path2+=path.Left(path.Find( _T("\\") )+1);
-                                            path=path.Mid(path.Find( _T("\\") )+1);
-                                            CreateDirectory(path2, 0);
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    }
-                    else
+					CDirectoryCache cache;
+					t_server server;
+					m_pOwner->GetCurrentServer(server);
+					t_directory dir;
+					BOOL res = cache.Lookup(pData->transferfile.remotepath, server,dir);
+					if (res)
+					{
+						CString remotefile = pData->transferfile.remotefile;
+						int i;
+						for (i = 0; i < dir.num; i++)
+						{
+							if (dir.direntry[i].name == remotefile &&
+								(dir.direntry[i].bUnsure || dir.direntry[i].size == -1))
+							{
+								m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+								break;
+							}
+						}
+						if (i == dir.num)
+						{
+							SetDirectoryListing(&dir);
+							m_Operation.nOpState=FILETRANSFER_TYPE;
+							nReplyError=CheckOverwriteFile();
+							if (!nReplyError)
+							{
+								if (pData->transferfile.get)
+								{
+									CString path=pData->transferfile.localfile;
+									if (path.ReverseFind('\\')!=-1)
+									{
+										path=path.Left(path.ReverseFind('\\')+1);
+										CString path2;
+										while (path!="")
+										{
+											path2+=path.Left(path.Find( _T("\\") )+1);
+											path=path.Mid(path.Find( _T("\\") )+1);
+											CreateDirectory(path2, 0);
+										}
+									}
+								}
+							}
+						}
+					}
+					else
 #endif
-                        m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
-                }
-            }
-            break;
-        case FILETRANSFER_LIST_MODE:
+						m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
+				}
+			}
+			break;
+		case FILETRANSFER_LIST_MODE:
 #ifdef MPEXT_NO_ZLIB
-            ASSERT(false);
-            m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
+			ASSERT(false);
+			m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
 #else
-            if (code == 2 || code == 3)
-                m_useZlib = !m_useZlib;
-            m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE;
+			if (code == 2 || code == 3)
+				m_useZlib = !m_useZlib;
+			m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE;
 #endif
-            break;
-        case FILETRANSFER_LIST_OPTS:
+			break;
+		case FILETRANSFER_LIST_OPTS:
 #ifdef MPEXT_NO_ZLIB
-            ASSERT(false);
+			ASSERT(false);
 #else
-            if (code == 2 || code == 3)
-                m_zlibLevel = pData->newZlibLevel;
-            m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
+			if (code == 2 || code == 3)
+				m_zlibLevel = pData->newZlibLevel;
+			m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
 #endif
-            break;
-        case FILETRANSFER_LIST_TYPE:
-            if (code != 2 && code != 3)
-                nReplyError = FZ_REPLY_ERROR;
-            else
-                m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
-            break;
-        case FILETRANSFER_LIST_PORTPASV:
-            if (code!=3 && code!=2)
-            {
-                if (!pData->bTriedPortPasvOnce)
-                {
-                    pData->bTriedPortPasvOnce = TRUE;
-                    pData->bPasv = !pData->bPasv;
-                }
-                else
-                    nReplyError=FZ_REPLY_ERROR;
-                break;
-            }
-
-            if (pData->bPasv)
-            {
-                CString reply = GetReply();
-                int i = reply.Find( _T("(") );
-                int j = j = reply.Find( _T(")") );
-                // extract connect port number and IP from string returned by server
-                if (i==-1 || j==-1 || (i+11)>=j)
-                {
-                    if (!pData->bTriedPortPasvOnce)
-                    {
-                        pData->bTriedPortPasvOnce = TRUE;
-                        pData->bPasv = !pData->bPasv;
-                    }
-                    else
-                        nReplyError = FZ_REPLY_ERROR;
-                    break;
-                }
-
-                CString temp;
-                temp = reply.Mid(i+1,(j-i)-1);
-
-                if (GetFamily() == AF_INET)
-                {
-                    int count=0;
-                    int pos=0;
-                    //Convert commas to dots
-                    temp.Replace( _T(","), _T(".") );
-                    while(1)
-                    {
-                        pos=temp.Find(_T("."),pos);
-                        if (pos!=-1)
-                            count++;
-                        else
-                            break;
-                        pos++;
-                    }
-                    if (count!=5)
-                    {
-                        if (!pData->bTriedPortPasvOnce)
-                        {
-                            pData->bTriedPortPasvOnce = TRUE;
-                            pData->bPasv = !pData->bPasv;
-                        }
-                        else
-                            nReplyError = FZ_REPLY_ERROR;
-                        break;
-                    }
-
-                    i=temp.ReverseFind('.');
-                    pData->port=atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); //get ls byte of server socket
-                    temp=temp.Left(i);
-                    i=temp.ReverseFind('.');
-                    pData->port+=256*atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); // add ms byte to server socket
-                    pData->host=temp.Left(i);
-                }
-                else if (GetFamily() == AF_INET6)
-                {
-                    temp = temp.Mid(3);
-                    pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
-                    if (pData->port < 0 || pData->port > 65535)
-                    {
-                        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
-                        nReplyError = FZ_REPLY_ERROR;
-                        break;
-                    }
-
-                    unsigned int tmpPort;
-                    if (!GetPeerName(pData->host, tmpPort))
-                    {
-                        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
-                        nReplyError = FZ_REPLY_ERROR;
-                        break;
-                    }
-                }
-
-                m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
+			break;
+		case FILETRANSFER_LIST_TYPE:
+			if (code != 2 && code != 3)
+				nReplyError = FZ_REPLY_ERROR;
+			else
+				m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
+			break;
+		case FILETRANSFER_LIST_PORTPASV:
+			if (code!=3 && code!=2)
+			{
+				if (!pData->bTriedPortPasvOnce)
+				{
+					pData->bTriedPortPasvOnce = TRUE;
+					pData->bPasv = !pData->bPasv;
+				}
+				else
+					nReplyError=FZ_REPLY_ERROR;
+				break;
+			}
+
+			if (pData->bPasv)
+			{
+				CString reply = GetReply();
+				int i = reply.Find( _T("(") );
+				int j = j = reply.Find( _T(")") );
+				// extract connect port number and IP from string returned by server
+				if (i==-1 || j==-1 || (i+11)>=j)
+				{
+					if (!pData->bTriedPortPasvOnce)
+					{
+						pData->bTriedPortPasvOnce = TRUE;
+						pData->bPasv = !pData->bPasv;
+					}
+					else
+						nReplyError = FZ_REPLY_ERROR;
+					break;
+				}
+
+				CString temp;
+				temp = reply.Mid(i+1,(j-i)-1);
+
+				if (GetFamily() == AF_INET)
+				{
+					int count=0;
+					int pos=0;
+					//Convert commas to dots
+					temp.Replace( _T(","), _T(".") );
+					while(1)
+					{
+						pos=temp.Find(_T("."),pos);
+						if (pos!=-1)
+							count++;
+						else
+							break;
+						pos++;
+					}
+					if (count!=5)
+					{
+						if (!pData->bTriedPortPasvOnce)
+						{
+							pData->bTriedPortPasvOnce = TRUE;
+							pData->bPasv = !pData->bPasv;
+						}
+						else
+							nReplyError = FZ_REPLY_ERROR;
+						break;
+					}
+
+					i=temp.ReverseFind('.');
+					pData->port=atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); //get ls byte of server socket
+					temp=temp.Left(i);
+					i=temp.ReverseFind('.');
+					pData->port+=256*atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); // add ms byte to server socket
+					pData->host=temp.Left(i);
+				}
+				else if (GetFamily() == AF_INET6)
+				{
+					temp = temp.Mid(3);
+					pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
+					if (pData->port < 0 || pData->port > 65535)
+					{
+						LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
+						nReplyError = FZ_REPLY_ERROR;
+						break;
+					}
+
+					unsigned int tmpPort;
+					if (!GetPeerName(pData->host, tmpPort))
+					{
+						LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
+						nReplyError = FZ_REPLY_ERROR;
+						break;
+					}
+				}
+
+				m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
 #ifndef MPEXT_NO_ZLIB
-                if (m_useZlib)
-                {
-                    if (!m_pTransferSocket->InitZlib(m_zlibLevel))
-                    {
-                        ShowStatus("Failed to initialize zlib", 1);
-                        ResetOperation(FZ_REPLY_ERROR);
-                        return;
-                    }
-                }
+				if (m_useZlib)
+				{
+					if (!m_pTransferSocket->InitZlib(m_zlibLevel))
+					{
+						ShowStatus("Failed to initialize zlib", 1);
+						ResetOperation(FZ_REPLY_ERROR);
+						return;
+					}
+				}
 #endif
 #ifndef MPEXT_NO_GSS
-                if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
-                    m_pTransferSocket->UseGSS(m_pGssLayer);
+				if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
+					m_pTransferSocket->UseGSS(m_pGssLayer);
 #endif
-                m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
-                m_pTransferSocket->SetFamily(GetFamily());
-                if (!m_pTransferSocket->Create(
+				m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
+				m_pTransferSocket->SetFamily(GetFamily());
+				if (!m_pTransferSocket->Create(
 #ifndef MPEXT_NO_SSL
-               m_pSslLayer && m_bProtP
+						m_pSslLayer && m_bProtP
 #endif
-               ))
-                {
-                    nReplyError = FZ_REPLY_ERROR;
-                    break;
-                }
-
-                VERIFY(m_pTransferSocket->AsyncSelect());
-            }
-            m_Operation.nOpState=FILETRANSFER_LIST_LIST;
-            break;
-        case FILETRANSFER_LIST_LIST:
-            if (IsMisleadingListResponse())
-            {
-                ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
-
-                t_directory listing;
-                listing.server = m_CurrentServer;
-                listing.path.SetServer(m_CurrentServer);
-                if (pData->rawpwd != "")
-                {
-                    if (!listing.path.SetPath(pData->rawpwd))
-                    {
-                        delete m_pDirectoryListing;
-                        m_pDirectoryListing = 0;
-                        delete m_pTransferSocket;
-                        m_pTransferSocket = 0;
-                        ResetOperation(FZ_REPLY_ERROR);
-                        return;
-                    }
-                }
-                else
-                    listing.path = pData->transferfile.remotepath;
+					))
+				{
+					nReplyError = FZ_REPLY_ERROR;
+					break;
+				}
+
+				VERIFY(m_pTransferSocket->AsyncSelect());
+			}
+			m_Operation.nOpState=FILETRANSFER_LIST_LIST;
+			break;
+		case FILETRANSFER_LIST_LIST:
+			if (IsMisleadingListResponse())
+			{
+				ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
+
+				t_directory listing;
+				listing.server = m_CurrentServer;
+				listing.path.SetServer(m_CurrentServer);
+				if (pData->rawpwd != "")
+				{
+					if (!listing.path.SetPath(pData->rawpwd))
+					{
+						delete m_pDirectoryListing;
+						m_pDirectoryListing = 0;
+						delete m_pTransferSocket;
+						m_pTransferSocket = 0;
+						ResetOperation(FZ_REPLY_ERROR);
+						return;
+					}
+				}
+				else
+					listing.path = pData->transferfile.remotepath;
 
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
-                cache.Lock();
-                t_directory dir;
-                if (cache.Lookup(listing.path, listing.server, dir))
-                    listing.Merge(dir, pData->ListStartTime);
-                cache.Store(listing);
-                cache.Unlock();
+				CDirectoryCache cache;
+				cache.Lock();
+				t_directory dir;
+				if (cache.Lookup(listing.path, listing.server, dir))
+					listing.Merge(dir, pData->ListStartTime);
+				cache.Store(listing);
+				cache.Unlock();
 #endif
-                SetDirectoryListing(&listing);
-
-                m_Operation.nOpState = FILETRANSFER_TYPE;
-                delete m_pTransferSocket;
-                m_pTransferSocket = 0;
-
-                nReplyError = CheckOverwriteFile();
-                if (!nReplyError)
-                {
-                    if (pData->transferfile.get)
-                    {
-                        CString path=pData->transferfile.localfile;
-                        if (path.ReverseFind('\\')!=-1)
-                        {
-                            path=path.Left(path.ReverseFind('\\')+1);
-                            CString path2;
-                            while (path!="")
-                            {
-                                path2+=path.Left(path.Find( _T("\\") )+1);
-                                path=path.Mid(path.Find( _T("\\") )+1);
-                                CreateDirectory(path2, 0);
-                            }
-                        }
-                    }
-                }
-            }
-            else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
-            {
-                if (m_pTransferSocket)
-                    delete m_pTransferSocket;
-                m_pTransferSocket=0;
-                m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
-            }
-            else if (code!=1)
-                nReplyError=FZ_REPLY_ERROR;
-            else
-                m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
-            break;
-        case FILETRANSFER_LIST_WAITFINISH:
-            if (!bFinish)
-            {
-                if (code!=2 && code!=3)
-                    nReplyError=FZ_REPLY_ERROR;
-                else
-                    pData->nGotTransferEndReply = 1;
-            }
-            if (pData->nGotTransferEndReply && pData->pDirectoryListing)
-            {
+				SetDirectoryListing(&listing);
+
+				m_Operation.nOpState = FILETRANSFER_TYPE;
+				delete m_pTransferSocket;
+				m_pTransferSocket = 0;
+
+				nReplyError = CheckOverwriteFile();
+				if (!nReplyError)
+				{
+					if (pData->transferfile.get)
+					{
+						CString path=pData->transferfile.localfile;
+						if (path.ReverseFind('\\')!=-1)
+						{
+							path=path.Left(path.ReverseFind('\\')+1);
+							CString path2;
+							while (path!="")
+							{
+								path2+=path.Left(path.Find( _T("\\") )+1);
+								path=path.Mid(path.Find( _T("\\") )+1);
+								CreateDirectory(path2, 0);
+							}
+						}
+					}
+				}
+			}
+			else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
+			{
+				if (m_pTransferSocket)
+					delete m_pTransferSocket;
+				m_pTransferSocket=0;
+				m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
+			}
+			else if (code!=1)
+				nReplyError=FZ_REPLY_ERROR;
+			else
+				m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
+			break;
+		case FILETRANSFER_LIST_WAITFINISH:
+			if (!bFinish)
+			{
+				if (code!=2 && code!=3)
+					nReplyError=FZ_REPLY_ERROR;
+				else
+					pData->nGotTransferEndReply = 1;
+			}
+			if (pData->nGotTransferEndReply && pData->pDirectoryListing)
+			{
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
-                t_directory dir;
-                cache.Lock();
-                if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir, TRUE))
-                {
-                    pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
-                }
-                cache.Store(*pData->pDirectoryListing);
-                cache.Unlock();
+				CDirectoryCache cache;
+				t_directory dir;
+				cache.Lock();
+				if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir, TRUE))
+				{
+					pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
+				}
+				cache.Store(*pData->pDirectoryListing);
+				cache.Unlock();
 #endif
-                SetDirectoryListing(pData->pDirectoryListing);
-                delete m_pTransferSocket;
-                m_pTransferSocket=0;
-                m_Operation.nOpState=FILETRANSFER_TYPE;
-                nReplyError = CheckOverwriteFile();
-                if (!nReplyError)
-                {
-                    if (pData->transferfile.get)
-                    {
-                        CString path=pData->transferfile.localfile;
-                        if (path.ReverseFind('\\')!=-1)
-                        {
-                            path=path.Left(path.ReverseFind('\\')+1);
-                            CString path2;
-                            while (path!="")
-                            {
-                                path2+=path.Left(path.Find( _T("\\") )+1);
-                                path=path.Mid(path.Find( _T("\\") )+1);
-                                CreateDirectory(path2, 0);
-                            }
-                        }
-                    }
-                }
-                pData->nGotTransferEndReply=0;
-            }
-            break;
-        case FILETRANSFER_NOLIST_SIZE:
-            if (code==2)
-            {
-                CString line = GetReply();
-                if ( line.GetLength()>4  &&  line.Left(4) == _T("213 ") )
-                {
-                    __int64 size=_ttoi64(line.Mid(4));
-                    ASSERT(!pData->pFileSize);
-                    pData->pFileSize=new _int64;
-                    *pData->pFileSize=size;
-                }
-            }
-            m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
-            break;
-        case FILETRANSFER_NOLIST_MDTM:
-            if (code==2)
-            {
-                CString line = GetReply();
-                if ( line.GetLength()>4  &&  line.Left(4) == _T("213 ") )
-                {
-                    int y=0, M=0, d=0, h=0, m=0;
-                    line=line.Mid(4);
-                    y=_ttoi(line.Left(4));
-                    if (y && line.GetLength()>4)
-                    {
-                        line=line.Mid(4);
-                        M=_ttoi(line.Left(2));
-                        if (M && line.GetLength()>2)
-                        {
-                            line=line.Mid(2);
-                            d=_ttoi(line.Left(2));
-                            if (d && line.GetLength()>2)
-                            {
-                                line=line.Mid(2);
-                                h=_ttoi(line.Left(2));
-                                if (h && line.GetLength()>2)
-                                {
-                                    line=line.Mid(2);
-                                    m=_ttoi(line.Left(2));
-                                    if (m && line.GetLength()>2)
-                                    {
-                                        line=line.Mid(2);
-                                    }
-                                }
-                            }
-                            if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60)
-                            {
-                                if (pData->pFileTime)
-                                    delete pData->pFileTime;
-                                TRY
-                                {
-                                    pData->pFileTime = new CTime(y, M, d, h, m, 0);
-                                }
-                                CATCH_ALL(e)
-                                {
-                                    TCHAR buffer[1024];
-                                    CString str =_T("Exception creating CTime object: ");
-                                    if (e->GetErrorMessage(buffer, 1024, NULL))
-                                        str += buffer;
-                                    else
-                                    str += _T("Unknown exception");
-                                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
-                                    pData->pFileTime = 0;
-                                }
-                                END_CATCH_ALL;
-                            }
-                        }
-                    }
-                }
-            }
-            m_Operation.nOpState=FILETRANSFER_TYPE;
-            nReplyError=CheckOverwriteFile();
-            break;
-        case FILETRANSFER_TYPE:
-            if (code!=2 && code!=3)
-                nReplyError = FZ_REPLY_ERROR;
-            m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_MODE : (NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV);
-            break;
-        case FILETRANSFER_WAIT:
-            if (!pData->nWaitNextOpState)
-                nReplyError=FZ_REPLY_ERROR;
-            else
-                m_Operation.nOpState=pData->nWaitNextOpState;
-            break;
-        case FILETRANSFER_MODE:
+				SetDirectoryListing(pData->pDirectoryListing);
+				delete m_pTransferSocket;
+				m_pTransferSocket=0;
+				m_Operation.nOpState=FILETRANSFER_TYPE;
+				nReplyError = CheckOverwriteFile();
+				if (!nReplyError)
+				{
+					if (pData->transferfile.get)
+					{
+						CString path=pData->transferfile.localfile;
+						if (path.ReverseFind('\\')!=-1)
+						{
+							path=path.Left(path.ReverseFind('\\')+1);
+							CString path2;
+							while (path!="")
+							{
+								path2+=path.Left(path.Find( _T("\\") )+1);
+								path=path.Mid(path.Find( _T("\\") )+1);
+								CreateDirectory(path2, 0);
+							}
+						}
+					}
+				}
+				pData->nGotTransferEndReply=0;
+			}
+			break;
+		case FILETRANSFER_NOLIST_SIZE:
+			if (code==2)
+			{
+				CString line = GetReply();
+				if ( line.GetLength()>4  &&  line.Left(4) == _T("213 ") )
+				{
+					__int64 size=_ttoi64(line.Mid(4));
+					ASSERT(!pData->pFileSize);
+					pData->pFileSize=new _int64;
+					*pData->pFileSize=size;
+				}
+			}
+			m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
+			break;
+		case FILETRANSFER_NOLIST_MDTM:
+			if (code==2)
+			{
+				CString line = GetReply();
+				if ( line.GetLength()>4  &&  line.Left(4) == _T("213 ") )
+				{
+					int y=0, M=0, d=0, h=0, m=0;
+					line=line.Mid(4);
+					y=_ttoi(line.Left(4));
+					if (y && line.GetLength()>4)
+					{
+						line=line.Mid(4);
+						M=_ttoi(line.Left(2));
+						if (M && line.GetLength()>2)
+						{
+							line=line.Mid(2);
+							d=_ttoi(line.Left(2));
+							if (d && line.GetLength()>2)
+							{
+								line=line.Mid(2);
+								h=_ttoi(line.Left(2));
+								if (h && line.GetLength()>2)
+								{
+									line=line.Mid(2);
+									m=_ttoi(line.Left(2));
+									if (m && line.GetLength()>2)
+									{
+										line=line.Mid(2);
+									}
+								}
+							}
+							if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60)
+							{
+								if (pData->pFileTime)
+									delete pData->pFileTime;
+								TRY
+								{
+									pData->pFileTime = new CTime(y, M, d, h, m, 0);
+								}
+								CATCH_ALL(e)
+								{
+									TCHAR buffer[1024];
+									CString str =_T("Exception creating CTime object: ");
+									if (e->GetErrorMessage(buffer, 1024, NULL))
+										str += buffer;
+									else
+									str += _T("Unknown exception");
+									LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
+									pData->pFileTime = 0;
+								}
+								END_CATCH_ALL;
+							}
+						}
+					}
+				}
+			}
+			m_Operation.nOpState=FILETRANSFER_TYPE;
+			nReplyError=CheckOverwriteFile();
+			break;
+		case FILETRANSFER_TYPE:
+			if (code!=2 && code!=3)
+				nReplyError = FZ_REPLY_ERROR;
+			m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_MODE : (NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV);
+			break;
+		case FILETRANSFER_WAIT:
+			if (!pData->nWaitNextOpState)
+				nReplyError=FZ_REPLY_ERROR;
+			else
+				m_Operation.nOpState=pData->nWaitNextOpState;
+			break;
+		case FILETRANSFER_MODE:
 #ifdef MPEXT_NO_ZLIB
-            ASSERT(false);
-            m_Operation.nOpState = FILETRANSFER_PORTPASV;
+			ASSERT(false);
+			m_Operation.nOpState = FILETRANSFER_PORTPASV;
 #else
-            if (code == 2 || code == 3)
-                m_useZlib = !m_useZlib;
-            m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV;
+			if (code == 2 || code == 3)
+				m_useZlib = !m_useZlib;
+			m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV;
 #endif
-            break;
-        case FILETRANSFER_OPTS:
+			break;
+		case FILETRANSFER_OPTS:
 #ifdef MPEXT_NO_ZLIB
-            ASSERT(false);
+			ASSERT(false);
 #else
-            if (code == 2 || code == 3)
-                m_zlibLevel = pData->newZlibLevel;
+			if (code == 2 || code == 3)
+				m_zlibLevel = pData->newZlibLevel;
 #endif
-            m_Operation.nOpState = FILETRANSFER_PORTPASV;
-            break;
-        case FILETRANSFER_PORTPASV:
-            if (code == 3 || code == 2)
-            {
-                if (pData->bPasv)
-                {
-                    CString reply = GetReply();
-                    int i = reply.Find( _T("(") );
-                    int j = j = reply.Find( _T(")") );
-                    // extract connect port number and IP from string returned by server
-                    if(i==-1 || j==-1 || (GetFamily() == AF_INET && (i+11) >= j))
-                    {
-                        if (!pData->bTriedPortPasvOnce)
-                        {
-                            pData->bTriedPortPasvOnce = TRUE;
-                            pData->bPasv = !pData->bPasv;
-                        }
-                        else
-                            nReplyError = FZ_REPLY_ERROR;
-                        break;
-                    }
-
-                    CString temp;
-                    temp = reply.Mid(i+1,(j-i)-1);
-
-                    if (GetFamily() == AF_INET)
-                    {
-                        int count=0;
-                        int pos=0;
-                        //Convert commas to dots
-                        temp.Replace( _T(","), _T(".") );
-                        while(1)
-                        {
-                            pos=temp.Find( _T("."), pos);
-                            if (pos!=-1)
-                                count++;
-                            else
-                                break;
-                            pos++;
-                        }
-                        if (count!=5)
-                        {
-                            if (!pData->bTriedPortPasvOnce)
-                            {
-                                pData->bTriedPortPasvOnce = TRUE;
-                                pData->bPasv = !pData->bPasv;
-                            }
-                            else
-                                nReplyError = FZ_REPLY_ERROR;
-                            break;
-                        }
-
-                        i=temp.ReverseFind('.');
-                        pData->port=atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); //get ls byte of server socket
-                        temp=temp.Left(i);
-                        i=temp.ReverseFind('.');
-                        pData->port+=256*atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); // add ms byte to server socket
-                        pData->host=temp.Left(i);
-                    }
-                    else if (GetFamily() == AF_INET6)
-                    {
-                        temp = temp.Mid(3);
-                        pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
-                        if (pData->port < 0 || pData->port > 65535)
-                        {
-                            LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
-                            nReplyError = FZ_REPLY_ERROR;
-                            break;
-                        }
-
-                        unsigned int tmpPort;
-                        if (!GetPeerName(pData->host, tmpPort))
-                        {
-                            LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
-                            nReplyError = FZ_REPLY_ERROR;
-                            break;
-                        }
-                    }
-                    else
-                    {
-                        nReplyError = FZ_REPLY_ERROR;
-                        break;
-                    }
-                    m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
+			m_Operation.nOpState = FILETRANSFER_PORTPASV;
+			break;
+		case FILETRANSFER_PORTPASV:
+			if (code == 3 || code == 2)
+			{
+				if (pData->bPasv)
+				{
+					CString reply = GetReply();
+					int i = reply.Find( _T("(") );
+					int j = j = reply.Find( _T(")") );
+					// extract connect port number and IP from string returned by server
+					if(i==-1 || j==-1 || (GetFamily() == AF_INET && (i+11) >= j))
+					{
+						if (!pData->bTriedPortPasvOnce)
+						{
+							pData->bTriedPortPasvOnce = TRUE;
+							pData->bPasv = !pData->bPasv;
+						}
+						else
+							nReplyError = FZ_REPLY_ERROR;
+						break;
+					}
+
+					CString temp;
+					temp = reply.Mid(i+1,(j-i)-1);
+
+					if (GetFamily() == AF_INET)
+					{
+						int count=0;
+						int pos=0;
+						//Convert commas to dots
+						temp.Replace( _T(","), _T(".") );
+						while(1)
+						{
+							pos=temp.Find( _T("."), pos);
+							if (pos!=-1)
+								count++;
+							else
+								break;
+							pos++;
+						}
+						if (count!=5)
+						{
+							if (!pData->bTriedPortPasvOnce)
+							{
+								pData->bTriedPortPasvOnce = TRUE;
+								pData->bPasv = !pData->bPasv;
+							}
+							else
+								nReplyError = FZ_REPLY_ERROR;
+							break;
+						}
+
+						i=temp.ReverseFind('.');
+						pData->port=atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); //get ls byte of server socket
+						temp=temp.Left(i);
+						i=temp.ReverseFind('.');
+						pData->port+=256*atol(  T2CA( temp.Right(temp.GetLength()-(i+1)) )  ); // add ms byte to server socket
+						pData->host=temp.Left(i);
+					}
+					else if (GetFamily() == AF_INET6)
+					{
+						temp = temp.Mid(3);
+						pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
+						if (pData->port < 0 || pData->port > 65535)
+						{
+							LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
+							nReplyError = FZ_REPLY_ERROR;
+							break;
+						}
+
+						unsigned int tmpPort;
+						if (!GetPeerName(pData->host, tmpPort))
+						{
+							LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
+							nReplyError = FZ_REPLY_ERROR;
+							break;
+						}
+					}
+					else
+					{
+						nReplyError = FZ_REPLY_ERROR;
+						break;
+					}
+					m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
 #ifndef MPEXT_NO_ZLIB
-                    if (m_useZlib)
-                    {
-                        if (!m_pTransferSocket->InitZlib(m_zlibLevel))
-                        {
-                            ShowStatus("Failed to initialize zlib", 1);
-                            ResetOperation(FZ_REPLY_ERROR);
-                            return;
-                        }
-                    }
+					if (m_useZlib)
+					{
+						if (!m_pTransferSocket->InitZlib(m_zlibLevel))
+						{
+							ShowStatus("Failed to initialize zlib", 1);
+							ResetOperation(FZ_REPLY_ERROR);
+							return;
+						}
+					}
 #endif
 #ifndef MPEXT_NO_GSS
-                    if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
-                        m_pTransferSocket->UseGSS(m_pGssLayer);
+					if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
+						m_pTransferSocket->UseGSS(m_pGssLayer);
 #endif
-                    m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
-                    m_pTransferSocket->SetFamily(GetFamily());
-                    if (!m_pTransferSocket->Create(
+					m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
+					m_pTransferSocket->SetFamily(GetFamily());
+					if (!m_pTransferSocket->Create(
 #ifndef MPEXT_NO_SSL
-                 m_pSslLayer && m_bProtP
+							m_pSslLayer && m_bProtP
 #endif
-                 ))
-                    {
-                        nReplyError = FZ_REPLY_ERROR;
-                        break;
-                    }
-
-                    VERIFY(m_pTransferSocket->AsyncSelect());
-                }
-
-                if (pData->transferdata.bResume && pData->transferfile.get)
-                    m_Operation.nOpState = FILETRANSFER_REST;
-                else
-                    m_Operation.nOpState = FILETRANSFER_RETRSTOR;
-                BOOL res = FALSE;
-                if (!m_pDataFile)
-                    m_pDataFile = new CFile;
-                if (pData->transferfile.get)
-                {
-                    if (pData->transferdata.bResume)
-                        res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
-                    else
-                        res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
-                }
-                else
-                    res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyWrite);
-                if (!res)
-                {
-                    //Error opening the file
-                    CString str;
-                    str.Format(IDS_ERRORMSG_FILEOPENFAILED,pData->transferfile.localfile);
-                    ShowStatus(str,1);
-                    nReplyError = FZ_REPLY_ERROR;
-                    break;
-                }
-
-                if (!m_pTransferSocket)
-                {
-                    nReplyError=FZ_REPLY_ERROR;
-                    break;
-                }
-
-                m_pTransferSocket->m_pFile = m_pDataFile;
-                if (!pData->transferfile.get)
-                {
-                    pData->transferdata.transfersize=GetLength64(*m_pDataFile);
-                    pData->transferdata.transferleft=pData->transferdata.transfersize;
-                    if (pData->transferdata.bResume)
-                    {
-                        CString remotefile=pData->transferfile.remotefile;
-                        if (m_pDirectoryListing)
-                            for (int i = 0; i < m_pDirectoryListing->num; i++)
-                            {
-                                if (m_pDirectoryListing->direntry[i].name == remotefile)
-                                {
-                                    pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
-                                    break;
-                                }
-                            }
-                        _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
-                        LONG low = static_cast<LONG>(size&0xFFFFFFFF);
-                        LONG high = static_cast<LONG>(size>>32);
-                        if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
-                        {
-                            ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
-                            nReplyError = FZ_REPLY_ERROR;
-                        }
-                    }
-                }
-                else
-                {
-                    pData->transferdata.transfersize=-1;
-                    CString remotefile=pData->transferfile.remotefile;
-                    if (m_pDirectoryListing)
-                        for (int i=0; i<m_pDirectoryListing->num; i++)
-                        {
-                            if (m_pDirectoryListing->direntry[i].name==remotefile)
-                            {
-                                if (pData->pFileTime)
-                                {
-                                    delete pData->pFileTime;
-                                    pData->pFileTime = 0;
-                                }
-                                t_directory::t_direntry::t_date *pDate=&m_pDirectoryListing->direntry[i].date;
-                                if (pDate->hasdate)
-                                {
-                                    TRY
-                                    {
-                                        if (pDate->hastime)
-                                            pData->pFileTime = new CTime(pDate->year, pDate->month, pDate->day, pDate->hour, pDate->minute, 0);
-                                        else
-                                            pData->pFileTime = new CTime(pDate->year, pDate->month, pDate->day, 0, 0, 0);
-
-                                        TIME_ZONE_INFORMATION tzInfo = {0};
-                                        BOOL res = GetTimeZoneInformation(&tzInfo);
-                                        CTimeSpan span(0, 0, tzInfo.Bias + ((res == TIME_ZONE_ID_DAYLIGHT) ? tzInfo.DaylightBias : tzInfo.StandardBias), 0);
-                                        *pData->pFileTime += span;
-                                    }
-                                    CATCH_ALL(e)
-                                    {
-                                        TCHAR buffer[1024];
-                                        CString str =_T("Exception creating CTime object: ");
-                                        if (e->GetErrorMessage(buffer, 1024, NULL))
-                                            str += buffer;
-                                        else
-                                        str += _T("Unknown exception");
-                                        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
-                                        pData->pFileTime = 0;
-                                    }
-                                    END_CATCH_ALL;
-                                }
-
-                                pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
-                            }
-                        }
-                    else if (pData->pFileSize)
-                        pData->transferdata.transfersize=*pData->pFileSize;
-                    pData->transferdata.transferleft=pData->transferdata.transfersize;
-                }
-            }
-            else
-                if (!pData->bTriedPortPasvOnce)
-                {
-                    pData->bTriedPortPasvOnce = TRUE;
-                    pData->bPasv = !pData->bPasv;
-                }
-                else
-                    nReplyError = FZ_REPLY_ERROR;
-            break;
-        case FILETRANSFER_REST:
-            { //Resume
-                if (code==3 || code==2)
-                {
-                    LONG high = 0;
-                    pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
-                    if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
-                    {
-                        ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
-                        nReplyError = FZ_REPLY_ERROR;
-                    }
-                    else
-                        m_Operation.nOpState = FILETRANSFER_RETRSTOR;
-                }
-                else
-                {
-                    if (code==5 && GetReply()[1]=='0')
-                    {
-                        if (pData->transferdata.transfersize!=-1 && pData->transferfile.get)
-                        {
-                            ASSERT(m_pDataFile);
-                            if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
-                            {
-                                ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, 0);
-                                ResetOperation(FZ_REPLY_OK);
-                                return;
-                            }
-                        }
-
-                        ShowStatus(IDS_ERRORMSG_CANTRESUME, 1);
-                        pData->transferdata.transferleft=pData->transferdata.transfersize;
-                        pData->transferdata.bResume=FALSE;
-                        m_Operation.nOpState=FILETRANSFER_RETRSTOR;
-                    }
-                    else
-                        nReplyError=FZ_REPLY_ERROR;
-                }
-            }
-            break;
-        case FILETRANSFER_RETRSTOR:
-            // A '1xy opening data connection' reply is expected if RETR/STOR/APPE
-            // is successful.
-            // On failure, it's a 4xy or 5xy reply.
-            // However, some servers send a 2xy transfer complete reply without opening a data
-            // connection if there's no data to send.
-            if (code==2)
-            {
-                //Transfer successful, however server did not open data connection
-                ResetOperation(FZ_REPLY_OK);
-                return;
-            }
-            else if (code!=1)
-            {
-                if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
-                {
-                    pData->askOnResumeFail = false;
-                    delete m_pTransferSocket;
-                    m_pTransferSocket = 0;
-                    delete m_pDataFile;
-                    m_pDataFile = 0;
-                    pData->nGotTransferEndReply = 0;
-                    nReplyError = CheckOverwriteFile();
-                }
-                else
-                {
-                    nReplyError = FZ_REPLY_ERROR;
-                    if (code == 5)
-                        nReplyError |= FZ_REPLY_CRITICALERROR;
-                }
-            }
-            else
-            {
-                m_Operation.nOpState=FILETRANSFER_WAITFINISH;
-
-                //Look if we can find any information about the resume offset
-                if (!pData->transferfile.get && pData->transferdata.bResume)
-                {
-                    _int64 nOffset = -1;
-                    CString reply = GetReply();
-                    reply.MakeLower();
-                    int pos = reply.Find(_T("restarting at offset "));
-                    if (pos != -1)
-                        pos += _tcslen(_T("restarting at offset "));
-
-                    reply = reply.Mid(pos);
-
-                    int i;
-                    for (i=0; i<reply.GetLength(); i++)
-                    {
-                        if (reply[i] < '0' || reply[i] > '9')
-                            break;
-                    }
-                    if (i == reply.GetLength())
-                        nOffset = _ttoi64(reply);
-                    if (nOffset != -1 && m_pDataFile)
-                    {
-                        LONG low = 0;
-                        LONG high = 0;
-                        if (nOffset >= GetLength64(*m_pDataFile))
-                            if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
-                            {
-                                ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
-                                nReplyError = FZ_REPLY_ERROR;
-                            }
-                        else
-                        {
-                            low=static_cast<LONG>(nOffset&0xFFFFFFFF);
-                            high=static_cast<LONG>(nOffset>>32);
-                            if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
-                            {
-                                ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
-                                nReplyError = FZ_REPLY_ERROR;
-                            }
-                        }
-                    }
-                    if (!nReplyError)
-                        m_pTransferSocket->SetActive();
-                }
-                else if (pData->bPasv)
-                    m_pTransferSocket->SetActive();
-
-            }
-            break;
-        case FILETRANSFER_WAITFINISH:
-            if (!bFinish)
-            {
-                if (code == 1)
-                {
-                    /* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
-                     * Just ignore the additional ones.
-                     */
-                    LogMessage(FZ_LOG_WARNING, _T("Server sent more than one code 1yz reply, ignoring additional reply"));
-                    break;
-                }
-                else if (code!=2 && code!=3)
-                    nReplyError = FZ_REPLY_ERROR;
-                else
-                {
-                    pData->nGotTransferEndReply |= 1;
-                }
-            }
-            if (pData->nGotTransferEndReply==3)
-            {
-                if (COptions::GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) && m_pDataFile)
-                {
-                    if (pData->pFileTime)
-                    {
-                        SYSTEMTIME stime;
-                        FILETIME ftime;
-                        if (pData->pFileTime->GetAsSystemTime(stime))
-                            if (SystemTimeToFileTime(&stime, &ftime))
-                                SetFileTime((HANDLE)m_pDataFile->m_hFile, &ftime, &ftime, &ftime);
-                    }
-                }
-                //Transfer successful
-                ResetOperation(FZ_REPLY_OK);
-                return;
-            }
-            break;
-        }
-        if (nReplyError)
-        { //Error transferring the file
-            ResetOperation(nReplyError);
-            return;
-        }
-    }
-    /////////////////
-    //Send commands//
-    /////////////////
-    BOOL bError=FALSE;
-    switch(m_Operation.nOpState)
-    {
-    case FILETRANSFER_PWD:
-        if (!Send("PWD"))
-            bError = TRUE;
-        break;
-    case FILETRANSFER_CWD:
-        if (!Send("CWD "+pData->transferfile.remotepath.GetPath()))
-            bError=TRUE;
-        break;
-    case FILETRANSFER_MKD:
-        if (pData->nMKDOpState==MKD_INIT)
-        {
-            if (!pData->transferfile.remotepath.HasParent())
-            {
-                LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Can't create root dir"));
-                ResetOperation(FZ_REPLY_CRITICALERROR);
-                return;
-            }
-            if (!Send("CWD "+pData->transferfile.remotepath.GetParent().GetPath()))
-                bError=TRUE;
-            pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
-            pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
-            pData->nMKDOpState=MKD_FINDPARENT;
-        }
-        break;
-    case FILETRANSFER_CWD2:
-        if (!Send("CWD "+pData->transferfile.remotepath.GetPath()))
-            bError=TRUE;
-        break;
-    case FILETRANSFER_PWD2:
-        if (!Send("PWD"))
-            bError=TRUE;
-        break;
-    case FILETRANSFER_LIST_MODE:
+				 ))
+					{
+						nReplyError = FZ_REPLY_ERROR;
+						break;
+					}
+
+					VERIFY(m_pTransferSocket->AsyncSelect());
+				}
+
+				if (pData->transferdata.bResume && pData->transferfile.get)
+					m_Operation.nOpState = FILETRANSFER_REST;
+				else
+					m_Operation.nOpState = FILETRANSFER_RETRSTOR;
+				BOOL res = FALSE;
+				if (!m_pDataFile)
+					m_pDataFile = new CFile;
+				if (pData->transferfile.get)
+				{
+					if (pData->transferdata.bResume)
+						res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
+					else
+						res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
+				}
+				else
+					res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyWrite);
+				if (!res)
+				{
+					//Error opening the file
+					CString str;
+					str.Format(IDS_ERRORMSG_FILEOPENFAILED,pData->transferfile.localfile);
+					ShowStatus(str,1);
+					nReplyError = FZ_REPLY_ERROR;
+					break;
+				}
+
+				if (!m_pTransferSocket)
+				{
+					nReplyError=FZ_REPLY_ERROR;
+					break;
+				}
+
+				m_pTransferSocket->m_pFile = m_pDataFile;
+				if (!pData->transferfile.get)
+				{
+					pData->transferdata.transfersize=GetLength64(*m_pDataFile);
+					pData->transferdata.transferleft=pData->transferdata.transfersize;
+					if (pData->transferdata.bResume)
+					{
+						CString remotefile=pData->transferfile.remotefile;
+						if (m_pDirectoryListing)
+							for (int i = 0; i < m_pDirectoryListing->num; i++)
+							{
+								if (m_pDirectoryListing->direntry[i].name == remotefile)
+								{
+									pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
+									break;
+								}
+							}
+						_int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
+						LONG low = static_cast<LONG>(size&0xFFFFFFFF);
+						LONG high = static_cast<LONG>(size>>32);
+						if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
+						{
+							ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
+							nReplyError = FZ_REPLY_ERROR;
+						}
+					}
+				}
+				else
+				{
+					pData->transferdata.transfersize=-1;
+					CString remotefile=pData->transferfile.remotefile;
+					if (m_pDirectoryListing)
+						for (int i=0; i<m_pDirectoryListing->num; i++)
+						{
+							if (m_pDirectoryListing->direntry[i].name==remotefile)
+							{
+								if (pData->pFileTime)
+								{
+									delete pData->pFileTime;
+									pData->pFileTime = 0;
+								}
+								t_directory::t_direntry::t_date *pDate=&m_pDirectoryListing->direntry[i].date;
+								if (pDate->hasdate)
+								{
+									TRY
+									{
+										if (pDate->hastime)
+											pData->pFileTime = new CTime(pDate->year, pDate->month, pDate->day, pDate->hour, pDate->minute, 0);
+										else
+											pData->pFileTime = new CTime(pDate->year, pDate->month, pDate->day, 0, 0, 0);
+
+										TIME_ZONE_INFORMATION tzInfo = {0};
+										BOOL res = GetTimeZoneInformation(&tzInfo);
+										CTimeSpan span(0, 0, tzInfo.Bias + ((res == TIME_ZONE_ID_DAYLIGHT) ? tzInfo.DaylightBias : tzInfo.StandardBias), 0);
+										*pData->pFileTime += span;
+									}
+									CATCH_ALL(e)
+									{
+										TCHAR buffer[1024];
+										CString str =_T("Exception creating CTime object: ");
+										if (e->GetErrorMessage(buffer, 1024, NULL))
+											str += buffer;
+										else
+										str += _T("Unknown exception");
+										LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
+										pData->pFileTime = 0;
+									}
+									END_CATCH_ALL;
+								}
+
+								pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
+							}
+						}
+					else if (pData->pFileSize)
+						pData->transferdata.transfersize=*pData->pFileSize;
+					pData->transferdata.transferleft=pData->transferdata.transfersize;
+				}
+			}
+			else
+				if (!pData->bTriedPortPasvOnce)
+				{
+					pData->bTriedPortPasvOnce = TRUE;
+					pData->bPasv = !pData->bPasv;
+				}
+				else
+					nReplyError = FZ_REPLY_ERROR;
+			break;
+		case FILETRANSFER_REST:
+			{ //Resume
+				if (code==3 || code==2)
+				{
+					LONG high = 0;
+					pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
+					if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
+					{
+						ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
+						nReplyError = FZ_REPLY_ERROR;
+					}
+					else
+						m_Operation.nOpState = FILETRANSFER_RETRSTOR;
+				}
+				else
+				{
+					if (code==5 && GetReply()[1]=='0')
+					{
+						if (pData->transferdata.transfersize!=-1 && pData->transferfile.get)
+						{
+							ASSERT(m_pDataFile);
+							if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
+							{
+								ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, 0);
+								ResetOperation(FZ_REPLY_OK);
+								return;
+							}
+						}
+
+						ShowStatus(IDS_ERRORMSG_CANTRESUME, 1);
+						pData->transferdata.transferleft=pData->transferdata.transfersize;
+						pData->transferdata.bResume=FALSE;
+						m_Operation.nOpState=FILETRANSFER_RETRSTOR;
+					}
+					else
+						nReplyError=FZ_REPLY_ERROR;
+				}
+			}
+			break;
+		case FILETRANSFER_RETRSTOR:
+			// A '1xy opening data connection' reply is expected if RETR/STOR/APPE
+			// is successful.
+			// On failure, it's a 4xy or 5xy reply.
+			// However, some servers send a 2xy transfer complete reply without opening a data
+			// connection if there's no data to send.
+			if (code==2)
+			{
+				//Transfer successful, however server did not open data connection
+				ResetOperation(FZ_REPLY_OK);
+				return;
+			}
+			else if (code!=1)
+			{
+				if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
+				{
+					pData->askOnResumeFail = false;
+					delete m_pTransferSocket;
+					m_pTransferSocket = 0;
+					delete m_pDataFile;
+					m_pDataFile = 0;
+					pData->nGotTransferEndReply = 0;
+					nReplyError = CheckOverwriteFile();
+				}
+				else
+				{
+					nReplyError = FZ_REPLY_ERROR;
+					if (code == 5)
+						nReplyError |= FZ_REPLY_CRITICALERROR;
+				}
+			}
+			else
+			{
+				m_Operation.nOpState=FILETRANSFER_WAITFINISH;
+
+				//Look if we can find any information about the resume offset
+				if (!pData->transferfile.get && pData->transferdata.bResume)
+				{
+					_int64 nOffset = -1;
+					CString reply = GetReply();
+					reply.MakeLower();
+					int pos = reply.Find(_T("restarting at offset "));
+					if (pos != -1)
+						pos += _tcslen(_T("restarting at offset "));
+
+					reply = reply.Mid(pos);
+
+					int i;
+					for (i=0; i<reply.GetLength(); i++)
+					{
+						if (reply[i] < '0' || reply[i] > '9')
+							break;
+					}
+					if (i == reply.GetLength())
+						nOffset = _ttoi64(reply);
+					if (nOffset != -1 && m_pDataFile)
+					{
+						LONG low = 0;
+						LONG high = 0;
+						if (nOffset >= GetLength64(*m_pDataFile))
+							if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
+							{
+								ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
+								nReplyError = FZ_REPLY_ERROR;
+							}
+						else
+						{
+							low=static_cast<LONG>(nOffset&0xFFFFFFFF);
+							high=static_cast<LONG>(nOffset>>32);
+							if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
+							{
+								ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
+								nReplyError = FZ_REPLY_ERROR;
+							}
+						}
+					}
+					if (!nReplyError)
+						m_pTransferSocket->SetActive();
+				}
+				else if (pData->bPasv)
+					m_pTransferSocket->SetActive();
+
+			}
+			break;
+		case FILETRANSFER_WAITFINISH:
+			if (!bFinish)
+			{
+				if (code == 1)
+				{
+					/* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
+					 * Just ignore the additional ones.
+					 */
+					LogMessage(FZ_LOG_WARNING, _T("Server sent more than one code 1yz reply, ignoring additional reply"));
+					break;
+				}
+				else if (code!=2 && code!=3)
+					nReplyError = FZ_REPLY_ERROR;
+				else
+				{
+					pData->nGotTransferEndReply |= 1;
+				}
+			}
+			if (pData->nGotTransferEndReply==3)
+			{
+				if (COptions::GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) && m_pDataFile)
+				{
+					if (pData->pFileTime)
+					{
+						SYSTEMTIME stime;
+						FILETIME ftime;
+						if (pData->pFileTime->GetAsSystemTime(stime))
+							if (SystemTimeToFileTime(&stime, &ftime))
+								SetFileTime((HANDLE)m_pDataFile->m_hFile, &ftime, &ftime, &ftime);
+					}
+				}
+				//Transfer successful
+				ResetOperation(FZ_REPLY_OK);
+				return;
+			}
+			break;
+		}
+		if (nReplyError)
+		{ //Error transferring the file
+			ResetOperation(nReplyError);
+			return;
+		}
+	}
+	/////////////////
+	//Send commands//
+	/////////////////
+	BOOL bError=FALSE;
+	switch(m_Operation.nOpState)
+	{
+	case FILETRANSFER_PWD:
+		if (!Send("PWD"))
+			bError = TRUE;
+		break;
+	case FILETRANSFER_CWD:
+		if (!Send("CWD "+pData->transferfile.remotepath.GetPath()))
+			bError=TRUE;
+		break;
+	case FILETRANSFER_MKD:
+		if (pData->nMKDOpState==MKD_INIT)
+		{
+			if (!pData->transferfile.remotepath.HasParent())
+			{
+				LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Can't create root dir"));
+				ResetOperation(FZ_REPLY_CRITICALERROR);
+				return;
+			}
+			if (!Send("CWD "+pData->transferfile.remotepath.GetParent().GetPath()))
+				bError=TRUE;
+			pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
+			pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
+			pData->nMKDOpState=MKD_FINDPARENT;
+		}
+		break;
+	case FILETRANSFER_CWD2:
+		if (!Send("CWD "+pData->transferfile.remotepath.GetPath()))
+			bError=TRUE;
+		break;
+	case FILETRANSFER_PWD2:
+		if (!Send("PWD"))
+			bError=TRUE;
+		break;
+	case FILETRANSFER_LIST_MODE:
 #ifdef MPEXT_NO_ZLIB
-        ASSERT(false);
+		ASSERT(false);
 #else
-        if (m_useZlib)
-        {
-            if (!Send("MODE S"))
-                bError = TRUE;
-        }
-        else
-            if (!Send("MODE Z"))
-                bError = TRUE;
+		if (m_useZlib)
+		{
+			if (!Send("MODE S"))
+				bError = TRUE;
+		}
+		else
+			if (!Send("MODE Z"))
+				bError = TRUE;
 #endif
-        break;
-    case FILETRANSFER_LIST_OPTS:
+		break;
+	case FILETRANSFER_LIST_OPTS:
 #ifdef MPEXT_NO_ZLIB
-        ASSERT(false);
+		ASSERT(false);
 #else
-        {
-            pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
-            CString str;
-            str.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
-            if (!Send(str))
-                bError = TRUE;
-        }
+		{
+			pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
+			CString str;
+			str.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
+			if (!Send(str))
+				bError = TRUE;
+		}
 #endif
-        break;
-    case FILETRANSFER_LIST_PORTPASV:
-        delete m_pDirectoryListing;
-        m_pDirectoryListing=0;
-        if (pData->bPasv)
-        {
-            if (!Send((GetFamily() == AF_INET) ? "PASV" : "EPSV"))
-                bError=TRUE;
-        }
-        else
-        {
-            if (m_pTransferSocket)
-            {
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("m_pTransferSocket != 0"));
-                delete m_pTransferSocket;
-            }
-            m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
+		break;
+	case FILETRANSFER_LIST_PORTPASV:
+		delete m_pDirectoryListing;
+		m_pDirectoryListing=0;
+		if (pData->bPasv)
+		{
+			if (!Send((GetFamily() == AF_INET) ? "PASV" : "EPSV"))
+				bError=TRUE;
+		}
+		else
+		{
+			if (m_pTransferSocket)
+			{
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("m_pTransferSocket != 0"));
+				delete m_pTransferSocket;
+			}
+			m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
 #ifndef MPEXT_NO_ZLIB
-            if (m_useZlib)
-            {
-                if (!m_pTransferSocket->InitZlib(m_zlibLevel))
-                {
-                    ShowStatus("Failed to initialize zlib", 1);
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
+			if (m_useZlib)
+			{
+				if (!m_pTransferSocket->InitZlib(m_zlibLevel))
+				{
+					ShowStatus("Failed to initialize zlib", 1);
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
 #endif
 #ifndef MPEXT_NO_GSS
-            if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
-                m_pTransferSocket->UseGSS(m_pGssLayer);
+			if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
+				m_pTransferSocket->UseGSS(m_pGssLayer);
 #endif
-            m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
-            m_pTransferSocket->m_bListening = TRUE;
-            m_pTransferSocket->SetFamily(GetFamily());
-            if(!m_pTransferSocket->Create(
+			m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
+			m_pTransferSocket->m_bListening = TRUE;
+			m_pTransferSocket->SetFamily(GetFamily());
+			if(!m_pTransferSocket->Create(
 #ifndef MPEXT_NO_SSL
-            m_pSslLayer && m_bProtP
+					m_pSslLayer && m_bProtP
 #endif
-            ) || !m_pTransferSocket->AsyncSelect())
-                bError=TRUE;
-            else if (m_pProxyLayer)
-            {
-                SOCKADDR_IN addr;
-                int len=sizeof(addr);
-                if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
-                {
-                    ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
-                    bError=TRUE;
-                }
-                else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
-                {
-                    ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
-                    bError=TRUE;
-                }
-                //Don't send PORT command yet, params are unknown.
-                //will be sent in TransfersocketListenFinished
-            }
-            else
-            {
-                //Set up an active file transfer
-                CString temp;
-                UINT nPort;
-
-                if (//create listen socket (let Windows choose the port) & start listening
-                    !m_pTransferSocket->Listen() ||
-                    !m_pTransferSocket->GetSockName(temp, nPort))
-                {
-                    bError = TRUE;
-                    break;
-                }
-
-                CString host;
-                if (GetFamily() == AF_INET)
-                {
-                    host = COptions::GetOption(OPTION_TRANSFERIP);
-                    if (host != "")
-                    {
-                        DWORD ip = inet_addr(T2CA(host));
-                        if (ip != INADDR_NONE)
-                            host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
-                        else
-                        {
-                            hostent *fullname = gethostbyname(T2CA(host));
-                            if (!fullname)
-                                host = "";
-                            else
-                            {
-                                DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
-                                if (ip != INADDR_NONE)
-                                    host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
-                                else
-                                    host = "";
-                            }
-                        }
-                    }
-                    if (host == "")
-                    {
-                        UINT temp;
-
-                        if (!GetSockName(host, temp))
-                        {
-                            bError = true;
-                            break;
-                        }
-
-                        host.Replace('.', ',');
-                    }
-
-                    if (!bError)
-                    {
-                        host.Format(host+",%d,%d", nPort/256, nPort%256);
-                        if (!Send(_T("PORT ") + host)) // send PORT cmd to server
-                            bError = TRUE;
-                    }
-                }
-                else if (GetFamily() == AF_INET6)
-                {
-                    host = COptions::GetOption(OPTION_TRANSFERIP6);
-                    if (host != "")
-                    {
-                        USES_CONVERSION;
-                        addrinfo hints, *res;
-                        memset(&hints, 0, sizeof(addrinfo));
-                        hints.ai_family = AF_INET6;
-                        hints.ai_socktype = SOCK_STREAM;
-                        if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
-                        {
-                            host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
-                            p_freeaddrinfo(res);
-                        }
-                        else
-                            host = _T("");
-                    }
-                    if (host == "")
-                    {
-                        UINT temp;
-
-                        if(!GetSockName(host, temp))
-                            bError = true;
-                    }
-
-                    if (!bError)
-                    {
-                        // assamble EPRT command
-                        CString cmd;
-                        cmd.Format(_T("EPRT |2|") + host + "|%d|", nPort);
-                        if (!Send(cmd))
-                            bError = TRUE;
-                    }
-                }
-                else
-                {
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
-                    bError = true;
-                }
-            }
-        }
-        break;
-    case FILETRANSFER_LIST_TYPE:
-        if (!Send("TYPE A"))
-            bError=TRUE;
-        break;
-    case FILETRANSFER_LIST_LIST:
-        {
-            if (!m_pTransferSocket)
-            {
-                LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
-                ResetOperation(FZ_REPLY_ERROR);
-                return;
-            }
-
-            m_pTransferSocket->SetActive();
-            pData->ListStartTime=CTime::GetCurrentTime();
-            CString cmd="LIST";
+				) || !m_pTransferSocket->AsyncSelect())
+				bError=TRUE;
+			else if (m_pProxyLayer)
+			{
+				SOCKADDR_IN addr;
+				int len=sizeof(addr);
+				if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
+				{
+					ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
+					bError=TRUE;
+				}
+				else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
+				{
+					ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
+					bError=TRUE;
+				}
+				//Don't send PORT command yet, params are unknown.
+				//will be sent in TransfersocketListenFinished
+			}
+			else
+			{
+				//Set up an active file transfer
+				CString temp;
+				UINT nPort;
+
+				if (//create listen socket (let Windows choose the port) & start listening
+					!m_pTransferSocket->Listen() ||
+					!m_pTransferSocket->GetSockName(temp, nPort))
+				{
+					bError = TRUE;
+					break;
+				}
+
+				CString host;
+				if (GetFamily() == AF_INET)
+				{
+					host = COptions::GetOption(OPTION_TRANSFERIP);
+					if (host != "")
+					{
+						DWORD ip = inet_addr(T2CA(host));
+						if (ip != INADDR_NONE)
+							host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
+						else
+						{
+							hostent *fullname = gethostbyname(T2CA(host));
+							if (!fullname)
+								host = "";
+							else
+							{
+								DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
+								if (ip != INADDR_NONE)
+									host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
+								else
+									host = "";
+							}
+						}
+					}
+					if (host == "")
+					{
+						UINT temp;
+
+						if (!GetSockName(host, temp))
+						{
+							bError = true;
+							break;
+						}
+
+						host.Replace('.', ',');
+					}
+
+					if (!bError)
+					{
+						host.Format(host+",%d,%d", nPort/256, nPort%256);
+						if (!Send(_T("PORT ") + host)) // send PORT cmd to server
+							bError = TRUE;
+					}
+				}
+				else if (GetFamily() == AF_INET6)
+				{
+					host = COptions::GetOption(OPTION_TRANSFERIP6);
+					if (host != "")
+					{
+						USES_CONVERSION;
+						addrinfo hints, *res;
+						memset(&hints, 0, sizeof(addrinfo));
+						hints.ai_family = AF_INET6;
+						hints.ai_socktype = SOCK_STREAM;
+						if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
+						{
+							host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
+							p_freeaddrinfo(res);
+						}
+						else
+							host = _T("");
+					}
+					if (host == "")
+					{
+						UINT temp;
+
+						if(!GetSockName(host, temp))
+							bError = true;
+					}
+
+					if (!bError)
+					{
+						// assamble EPRT command
+						CString cmd;
+						cmd.Format(_T("EPRT |2|") +	host + "|%d|", nPort);
+						if (!Send(cmd))
+							bError = TRUE;
+					}
+				}
+				else
+				{
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
+					bError = true;
+				}
+			}
+		}
+		break;
+	case FILETRANSFER_LIST_TYPE:
+		if (!Send("TYPE A"))
+			bError=TRUE;
+		break;
+	case FILETRANSFER_LIST_LIST:
+		{
+			if (!m_pTransferSocket)
+			{
+				LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
+				ResetOperation(FZ_REPLY_ERROR);
+				return;
+			}
+
+			m_pTransferSocket->SetActive();
+			pData->ListStartTime=CTime::GetCurrentTime();
+			CString cmd="LIST";
 #ifdef MPEXT
-            if ((TRUE || pData->transferfile.remotefile.Left(1)==".") && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
+			if ((TRUE || pData->transferfile.remotefile.Left(1)==".") && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
 #else
-            if ((m_pOwner->GetOption(FZAPI_OPTION_SHOWHIDDEN) || pData->transferfile.remotefile.Left(1)==".") && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
+			if ((m_pOwner->GetOption(FZAPI_OPTION_SHOWHIDDEN) || pData->transferfile.remotefile.Left(1)==".") && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
 #endif
-                cmd += " -a";
-            if(!Send(cmd))
-                bError=TRUE;
-            else if(pData->bPasv)
-            {
-                // if PASV create the socket & initiate outbound data channel connection
-                if (!m_pTransferSocket->Connect(pData->host,pData->port))
-                {
-                    if (GetLastError()!=WSAEWOULDBLOCK)
-                    {
-                        bError=TRUE;
-                        ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
-                    }
-                }
-            }
-        }
-        break;
-    case FILETRANSFER_NOLIST_SIZE:
-        {
-            CString command = _T("SIZE ");
-            command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
-
-            if (!Send(command))
-                bError=TRUE;
-        }
-        break;
-    case FILETRANSFER_NOLIST_MDTM:
-        {
-            CString command = _T("MDTM ");
-            command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
-
-            if (!Send(command))
-                bError=TRUE;
-        }
-        break;
-    case FILETRANSFER_TYPE:
-        if (pData->transferfile.nType==1)
-        {
-            if (!Send("TYPE A"))
-                bError=TRUE;
-        }
-        else
-            if (!Send("TYPE I"))
-                bError=TRUE;
-        break;
-    case FILETRANSFER_MODE:
+				cmd += " -a";
+			if(!Send(cmd))
+				bError=TRUE;
+			else if(pData->bPasv)
+			{
+				// if PASV create the socket & initiate outbound data channel connection
+				if (!m_pTransferSocket->Connect(pData->host,pData->port))
+				{
+					if (GetLastError()!=WSAEWOULDBLOCK)
+					{
+						bError=TRUE;
+						ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
+					}
+				}
+			}
+		}
+		break;
+	case FILETRANSFER_NOLIST_SIZE:
+		{
+			CString command = _T("SIZE ");
+			command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
+
+			if (!Send(command))
+				bError=TRUE;
+		}
+		break;
+	case FILETRANSFER_NOLIST_MDTM:
+		{
+			CString command = _T("MDTM ");
+			command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
+
+			if (!Send(command))
+				bError=TRUE;
+		}
+		break;
+	case FILETRANSFER_TYPE:
+		if (pData->transferfile.nType==1)
+		{
+			if (!Send("TYPE A"))
+				bError=TRUE;
+		}
+		else
+			if (!Send("TYPE I"))
+				bError=TRUE;
+		break;
+	case FILETRANSFER_MODE:
 #ifdef MPEXT_NO_ZLIB
-        ASSERT(false);
+		ASSERT(false);
 #else
-        if (m_useZlib)
-        {
-            if (!Send("MODE S"))
-                bError = TRUE;
-        }
-        else
-            if (!Send("MODE Z"))
-                bError = TRUE;
+		if (m_useZlib)
+		{
+			if (!Send("MODE S"))
+				bError = TRUE;
+		}
+		else
+			if (!Send("MODE Z"))
+				bError = TRUE;
 #endif
-        break;
-    case FILETRANSFER_OPTS:
+		break;
+	case FILETRANSFER_OPTS:
 #ifdef MPEXT_NO_ZLIB
-        ASSERT(false);
+		ASSERT(false);
 #else
-        {
-            pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
-            CString str;
-            str.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
-            if (!Send(str))
-                bError = TRUE;
-        }
+		{
+			pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
+			CString str;
+			str.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
+			if (!Send(str))
+				bError = TRUE;
+		}
 #endif
-        break;
-    case FILETRANSFER_PORTPASV:
-        if (pData->bPasv)
-        {
-            if (!Send((GetFamily() == AF_INET) ? "PASV" : "EPSV"))
-                bError=TRUE;
-        }
-        else
-        {
-            if (m_pTransferSocket)
-            {
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("m_pTransferSocket != 0"));
-                delete m_pTransferSocket;
-            }
-            m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
+		break;
+	case FILETRANSFER_PORTPASV:
+		if (pData->bPasv)
+		{
+			if (!Send((GetFamily() == AF_INET) ? "PASV" : "EPSV"))
+				bError=TRUE;
+		}
+		else
+		{
+			if (m_pTransferSocket)
+			{
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("m_pTransferSocket != 0"));
+				delete m_pTransferSocket;
+			}
+			m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
 #ifndef MPEXT_NO_ZLIB
-            if (m_useZlib)
-            {
-                if (!m_pTransferSocket->InitZlib(m_zlibLevel))
-                {
-                    ShowStatus("Failed to initialize zlib", 1);
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
+			if (m_useZlib)
+			{
+				if (!m_pTransferSocket->InitZlib(m_zlibLevel))
+				{
+					ShowStatus("Failed to initialize zlib", 1);
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
 #endif
 #ifndef MPEXT_NO_GSS
-            if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
-                m_pTransferSocket->UseGSS(m_pGssLayer);
+			if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
+				m_pTransferSocket->UseGSS(m_pGssLayer);
 #endif
-            m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
-            m_pTransferSocket->m_bListening = TRUE;
-            m_pTransferSocket->SetFamily(GetFamily());
-            if(!m_pTransferSocket->Create(
+			m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
+			m_pTransferSocket->m_bListening = TRUE;
+			m_pTransferSocket->SetFamily(GetFamily());
+			if(!m_pTransferSocket->Create(
 #ifndef MPEXT_NO_SSL
-            m_pSslLayer && m_bProtP
+					m_pSslLayer && m_bProtP
 #endif
-            ) || !m_pTransferSocket->AsyncSelect())
-                bError = TRUE;
-            else if (m_pProxyLayer)
-            {
-                SOCKADDR_IN addr;
-                int len=sizeof(addr);
-                if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
-                {
-                    ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
-                    bError=TRUE;
-                }
-                else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
-                {
-                    ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
-                    bError=TRUE;
-                }
-                //Don't send PORT command yet, params are unknown.
-                //will be sent in TransfersocketListenFinished
-            }
-            else
-            {
-                //Set up an active file transfer
-
-                CString temp;
-                UINT nPort;
-                if (//create listen socket (let Windows choose the port) & start listening
-                    !m_pTransferSocket->Listen() ||
-                    !m_pTransferSocket->GetSockName(temp, nPort))
-                {
-                    bError = TRUE;
-                    break;
-                }
-
-                CString host;
-                if (GetFamily() == AF_INET)
-                {
-                    host = COptions::GetOption(OPTION_TRANSFERIP);
-                    if (host != "")
-                    {
-                        DWORD ip = inet_addr(T2CA(host));
-                        if (ip != INADDR_NONE)
-                            host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
-                        else
-                        {
-                            hostent *fullname = gethostbyname(T2CA(host));
-                            if (!fullname)
-                                host = "";
-                            else
-                            {
-                                DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
-                                if (ip != INADDR_NONE)
-                                    host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
-                                else
-                                    host = "";
-                            }
-                        }
-                    }
-                    if (host == "")
-                    {
-                        UINT temp;
-
-                        if (!GetSockName(host, temp))
-                            bError = true;
-
-                        host.Replace('.', ',');
-                    }
-
-                    if (!bError)
-                    {
-                        host.Format(host+",%d,%d", nPort/256, nPort%256);
-                        if (!Send(_T("PORT ") + host)) // send PORT cmd to server
-                            bError = TRUE;
-                    }
-                }
-                else if (GetFamily() == AF_INET6)
-                {
-                    host = COptions::GetOption(OPTION_TRANSFERIP6);
-                    if (host != "")
-                    {
-                        USES_CONVERSION;
-                        addrinfo hints, *res;
-                        memset(&hints, 0, sizeof(addrinfo));
-                        hints.ai_family = AF_INET6;
-                        hints.ai_socktype = SOCK_STREAM;
-                        if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
-                        {
-                            host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
-                            p_freeaddrinfo(res);
-                        }
-                        else
-                            host = _T("");
-                    }
-                    if (host == "")
-                    {
-                        UINT temp;
-
-                        if(!GetSockName(host, temp))
-                            bError = true;
-                    }
-
-                    if (!bError)
-                    {
-                        // assamble EPRT command
-                        CString cmd;
-                        cmd.Format(_T("EPRT |2|") + host + "|%d|", nPort);
-                        if (!Send(cmd))
-                            bError = TRUE;
-                    }
-                }
-                else
-                {
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
-                    bError = true;
-                }
-
-                if (bError)
-                {
-                    ResetOperation(FZ_REPLY_ERROR);
-                    return;
-                }
-            }
-        }
-        break;
-    case FILETRANSFER_REST:
-        ASSERT(m_pDataFile);
-        {
-            CString command;
-            command.Format(_T("REST %I64d"), GetLength64(*m_pDataFile));
-            if (!Send(command))
-                bError=TRUE;
-        }
-        break;
-    case FILETRANSFER_RETRSTOR:
-        pData->transferdata.nTransferStart=pData->transferdata.transfersize-pData->transferdata.transferleft;
-        m_pTransferSocket->m_transferdata=pData->transferdata;
-        // send RETR/STOR command to server
-        if (!m_pTransferSocket)
-        {
-            LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
-            ResetOperation(FZ_REPLY_ERROR);
-            return;
-        }
-        if ((pData->transferfile.get || !pData->transferdata.bResume) && !pData->bPasv)
-            m_pTransferSocket->SetActive();
-        CString filename;
-
-        filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
-        if(!Send((pData->transferfile.get?"RETR ":(pData->transferdata.bResume)?"APPE ":"STOR ")+ filename))
-            bError = TRUE;
-        else
-        {
-            if (pData->bPasv)
-            {// if PASV create the socket & initiate outbound data channel connection
-                if (!m_pTransferSocket->Connect(pData->host,pData->port))
-                {
-                    if (GetLastError()!=WSAEWOULDBLOCK)
-                        bError=TRUE;
-                }
-            }
-        }
-        break;
-    }
-    if (bError)
-    { //Error transferring the file
-        ResetOperation(FZ_REPLY_ERROR);
-        return;
-    }
+				) || !m_pTransferSocket->AsyncSelect())
+				bError = TRUE;
+			else if (m_pProxyLayer)
+			{
+				SOCKADDR_IN addr;
+				int len=sizeof(addr);
+				if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
+				{
+					ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
+					bError=TRUE;
+				}
+				else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
+				{
+					ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
+					bError=TRUE;
+				}
+				//Don't send PORT command yet, params are unknown.
+				//will be sent in TransfersocketListenFinished
+			}
+			else
+			{
+				//Set up an active file transfer
+
+				CString temp;
+				UINT nPort;
+				if (//create listen socket (let Windows choose the port) & start listening
+					!m_pTransferSocket->Listen() ||
+					!m_pTransferSocket->GetSockName(temp, nPort))
+				{
+					bError = TRUE;
+					break;
+				}
+
+				CString host;
+				if (GetFamily() == AF_INET)
+				{
+					host = COptions::GetOption(OPTION_TRANSFERIP);
+					if (host != "")
+					{
+						DWORD ip = inet_addr(T2CA(host));
+						if (ip != INADDR_NONE)
+							host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
+						else
+						{
+							hostent *fullname = gethostbyname(T2CA(host));
+							if (!fullname)
+								host = "";
+							else
+							{
+								DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
+								if (ip != INADDR_NONE)
+									host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
+								else
+									host = "";
+							}
+						}
+					}
+					if (host == "")
+					{
+						UINT temp;
+
+						if (!GetSockName(host, temp))
+							bError = true;
+
+						host.Replace('.', ',');
+					}
+
+					if (!bError)
+					{
+						host.Format(host+",%d,%d", nPort/256, nPort%256);
+						if (!Send(_T("PORT ") + host)) // send PORT cmd to server
+							bError = TRUE;
+					}
+				}
+				else if (GetFamily() == AF_INET6)
+				{
+					host = COptions::GetOption(OPTION_TRANSFERIP6);
+					if (host != "")
+					{
+						USES_CONVERSION;
+						addrinfo hints, *res;
+						memset(&hints, 0, sizeof(addrinfo));
+						hints.ai_family = AF_INET6;
+						hints.ai_socktype = SOCK_STREAM;
+						if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
+						{
+							host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
+							p_freeaddrinfo(res);
+						}
+						else
+							host = _T("");
+					}
+					if (host == "")
+					{
+						UINT temp;
+
+						if(!GetSockName(host, temp))
+							bError = true;
+					}
+
+					if (!bError)
+					{
+						// assamble EPRT command
+						CString cmd;
+						cmd.Format(_T("EPRT |2|") +	host + "|%d|", nPort);
+						if (!Send(cmd))
+							bError = TRUE;
+					}
+				}
+				else
+				{
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
+					bError = true;
+				}
+
+				if (bError)
+				{
+					ResetOperation(FZ_REPLY_ERROR);
+					return;
+				}
+			}
+		}
+		break;
+	case FILETRANSFER_REST:
+		ASSERT(m_pDataFile);
+		{
+			CString command;
+			command.Format(_T("REST %I64d"), GetLength64(*m_pDataFile));
+			if (!Send(command))
+				bError=TRUE;
+		}
+		break;
+	case FILETRANSFER_RETRSTOR:
+		pData->transferdata.nTransferStart=pData->transferdata.transfersize-pData->transferdata.transferleft;
+		m_pTransferSocket->m_transferdata=pData->transferdata;
+		// send RETR/STOR command to server
+		if (!m_pTransferSocket)
+		{
+			LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
+			ResetOperation(FZ_REPLY_ERROR);
+			return;
+		}
+		if ((pData->transferfile.get || !pData->transferdata.bResume) && !pData->bPasv)
+			m_pTransferSocket->SetActive();
+		CString filename;
+		
+		filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
+		if(!Send((pData->transferfile.get?"RETR ":(pData->transferdata.bResume)?"APPE ":"STOR ")+ filename))
+			bError = TRUE;
+		else
+		{
+			if (pData->bPasv)
+			{// if PASV create the socket & initiate outbound data channel connection
+				if (!m_pTransferSocket->Connect(pData->host,pData->port))
+				{
+					if (GetLastError()!=WSAEWOULDBLOCK)
+						bError=TRUE;
+				}
+			}
+		}
+		break;
+	}
+	if (bError)
+	{ //Error transferring the file
+		ResetOperation(FZ_REPLY_ERROR);
+		return;
+	}
 }
 
 void CFtpControlSocket::Cancel(BOOL bQuit/*=FALSE*/)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Cancel(%s)  OpMode=%d OpState=%d"), bQuit?_T("TRUE"):_T("FALSE"), m_Operation.nOpMode, m_Operation.nOpState);
-
-    const int nOpMode = m_Operation.nOpMode;
-    if (nOpMode==CSMODE_CONNECT)
-        DoClose(FZ_REPLY_CANCEL);
-    else if (nOpMode & CSMODE_LIST)
-    {
-        if (m_Operation.nOpState == LIST_WAITFINISH)
-            m_skipReply = true;
-        ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
-    }
-    else if (nOpMode & CSMODE_TRANSFER)
-    {
-        if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
-            m_skipReply = true;
-        ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
-    }
-    else if (nOpMode != CSMODE_NONE)
-        ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
-
-    if (nOpMode != CSMODE_NONE && !bQuit)
-        ShowStatus(IDS_ERRORMSG_INTERRUPTED, 1);
-
-    if (m_awaitsReply)
-        m_skipReply = true;
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Cancel(%s)  OpMode=%d OpState=%d"), bQuit?_T("TRUE"):_T("FALSE"), m_Operation.nOpMode, m_Operation.nOpState);
+
+	const int nOpMode = m_Operation.nOpMode;
+	if (nOpMode==CSMODE_CONNECT)
+		DoClose(FZ_REPLY_CANCEL);
+	else if (nOpMode & CSMODE_LIST)
+	{
+		if (m_Operation.nOpState == LIST_WAITFINISH)
+			m_skipReply = true;
+		ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
+	}
+	else if (nOpMode & CSMODE_TRANSFER)
+	{
+		if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
+			m_skipReply = true;
+		ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
+	}
+	else if (nOpMode != CSMODE_NONE)
+		ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
+
+	if (nOpMode != CSMODE_NONE && !bQuit)
+		ShowStatus(IDS_ERRORMSG_INTERRUPTED, 1);
+
+	if (m_awaitsReply)
+		m_skipReply = true;
 }
 
 void CFtpControlSocket::TransfersocketListenFinished(unsigned int ip, unsigned short port)
 {
-    if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
-    {
-        CString host;
-        host.Format(_T("%d,%d,%d,%d,%d,%d"),ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
-        Send("PORT "+host);
-    }
+	if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
+	{
+		CString host;
+		host.Format(_T("%d,%d,%d,%d,%d,%d"),ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
+		Send("PORT "+host);
+	}
 }
 
 void CFtpControlSocket::ResumeTransfer()
 {
-    if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
-    {
-        m_pTransferSocket->OnSend(0);
-        m_pTransferSocket->OnReceive(0);
-    }
+	if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
+	{
+		m_pTransferSocket->OnSend(0);
+		m_pTransferSocket->OnReceive(0);
+	}
 }
 
 BOOL CFtpControlSocket::Create()
 {
-    if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
-        return CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, COptions::GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET);
-    else
-    {
-        int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
-        int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
-        if (min>=max)
-        {
-            ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
-            return FALSE;
-        }
-        int startport = static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
-        int port = startport;
-
-        while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, COptions::GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET))
-        {
-            port++;
-            if (port>max)
-                port=min;
-            if (port==startport)
-            {
-                ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
-                return FALSE;
-            }
-
-            if (!InitConnect())
-                return FALSE;
-        }
-    }
-    return TRUE;
+	if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
+		return CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT |	FD_CONNECT | FD_CLOSE, 0, COptions::GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET);
+	else
+	{
+		int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
+		int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
+		if (min>=max)
+		{
+			ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
+			return FALSE;
+		}
+		int startport = static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
+		int port = startport;
+
+		while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT |	FD_CONNECT | FD_CLOSE, 0, COptions::GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET))
+		{
+			port++;
+			if (port>max)
+				port=min;
+			if (port==startport)
+			{
+				ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
+				return FALSE;
+			}
+
+			if (!InitConnect())
+				return FALSE; 
+		}
+	}
+	return TRUE;
 }
 
 
 void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("ResetOperation(%d)  OpMode=%d OpState=%d"), nSuccessful, m_Operation.nOpMode, m_Operation.nOpState);
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("ResetOperation(%d)  OpMode=%d OpState=%d"), nSuccessful, m_Operation.nOpMode, m_Operation.nOpState);
 
-    if (nSuccessful & FZ_REPLY_CRITICALERROR)
-        nSuccessful |= FZ_REPLY_ERROR;
+	if (nSuccessful & FZ_REPLY_CRITICALERROR)
+		nSuccessful |= FZ_REPLY_ERROR;
 
-    if (m_pTransferSocket)
-        delete m_pTransferSocket;
-    m_pTransferSocket=0;
+	if (m_pTransferSocket)
+		delete m_pTransferSocket;
+	m_pTransferSocket=0;
 
 #ifndef MPEXT_NO_IDENT
-    //There may be an active ident socket, close it
-    if (m_pIdentControl)
-    {
-        delete m_pIdentControl;
-        m_pIdentControl=0;
-    }
+	//There may be an active ident socket, close it
+	if (m_pIdentControl)
+	{
+		delete m_pIdentControl;
+		m_pIdentControl=0;
+	}
 #endif
 
-    if (m_pDataFile)
-        delete m_pDataFile;
-    m_pDataFile=0;
-
-    if (m_Operation.nOpMode)
-    {
-        //Unset busy attribute so that new commands can be executed
-        m_pOwner->SetBusy(FALSE);
-
-        if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
-        {
-            nSuccessful|=FZ_REPLY_DISCONNECTED;
-            ShowStatus(IDS_ERRORMSG_CANTCONNECT, 1);
-        }
-
-        if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
-            m_LastSendTime=CTime::GetCurrentTime();
-
-        //Update remote file entry
-        if (m_Operation.pData &&
-            m_Operation.nOpMode&CSMODE_TRANSFER &&
-            (!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
-            m_pDirectoryListing &&
-            m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
-        {
-            CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
-            CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
+	if (m_pDataFile)
+		delete m_pDataFile;
+	m_pDataFile=0;
+
+	if (m_Operation.nOpMode)
+	{
+		//Unset busy attribute so that new commands can be executed
+		m_pOwner->SetBusy(FALSE);
+
+		if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
+		{
+			nSuccessful|=FZ_REPLY_DISCONNECTED;
+			ShowStatus(IDS_ERRORMSG_CANTCONNECT, 1);
+		}
+
+		if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
+			m_LastSendTime=CTime::GetCurrentTime();
+
+		//Update remote file entry
+		if (m_Operation.pData &&
+			m_Operation.nOpMode&CSMODE_TRANSFER &&
+			(!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
+			m_pDirectoryListing &&
+			m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
+		{
+			CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
+			CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
 #ifndef MPEXT_NO_CACHE
-            CDirectoryCache cache;
-            cache.Lock();
-            t_directory dir;
-            BOOL bCached=TRUE;
-            BOOL res=cache.Lookup(path, m_CurrentServer, dir);
-            if (!res)
-                bCached=FALSE;
+			CDirectoryCache cache;
+			cache.Lock();
+			t_directory dir;
+			BOOL bCached=TRUE;
+			BOOL res=cache.Lookup(path, m_CurrentServer, dir);
+			if (!res)
+				bCached=FALSE;
 #else
-            t_directory dir;
-            BOOL res=FALSE;
+			t_directory dir;
+			BOOL res=FALSE;
 #endif
-            if (!res && m_pDirectoryListing)
-            {
-                if (m_pDirectoryListing->path==path)
-                {
-                    dir=*m_pDirectoryListing;
-                    res=TRUE;
-                }
-            }
-            t_directory WorkingDir;
-            BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
-            if (!res && bFound)
-                if (WorkingDir.path==path)
-                {
-                    dir=WorkingDir;
-                    res=TRUE;
-                }
-            if (res)
-            {
-                int i;
-                for (i=0; i<dir.num; i++)
-                    if (dir.direntry[i].name==filename)
-                    {
-                        dir.direntry[i].bUnsure = TRUE;
-                        if (nSuccessful & FZ_REPLY_ERROR)
-                        {
-                            dir.direntry[i].bUnsure = TRUE;
-                            if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
-                                dir.direntry[i].size = -1;
-                        }
-                        else if (nSuccessful & FZ_REPLY_ERROR)
-                        {
-                            if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
-                                dir.direntry[i].size = -1;
-                        }
-                        dir.direntry[i].date.hasdate = false;
-                        break;
-                    }
-                if (i==dir.num)
-                {
-                    t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
-                    int i;
-                    for (i=0; i<dir.num; i++)
-                        entries[i]=dir.direntry[i];
-                    entries[i].name=filename;
-                    entries[i].lName=filename;
-                    entries[i].lName.MakeLower();
-                    entries[i].dir=FALSE;
-                    entries[i].date.hasdate=FALSE;
-                    entries[i].size=-1;
-                    if (nSuccessful&FZ_REPLY_OK)
-                        entries[i].bUnsure=FALSE;
-                    else
-                        entries[i].bUnsure=TRUE;
-
-                    delete [] dir.direntry;
-                    dir.direntry=entries;
-                    dir.num++;
-                }
+			if (!res && m_pDirectoryListing)
+			{
+				if (m_pDirectoryListing->path==path)
+				{
+					dir=*m_pDirectoryListing;
+					res=TRUE;
+				}
+			}
+			t_directory WorkingDir;
+			BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
+			if (!res && bFound)
+				if (WorkingDir.path==path)
+				{
+					dir=WorkingDir;
+					res=TRUE;
+				}
+			if (res)
+			{
+				int i;
+				for (i=0; i<dir.num; i++)
+					if (dir.direntry[i].name==filename)
+					{
+						dir.direntry[i].bUnsure = TRUE;
+						if (nSuccessful & FZ_REPLY_ERROR)
+						{
+							dir.direntry[i].bUnsure = TRUE;
+							if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
+								dir.direntry[i].size = -1;
+						}
+						else if (nSuccessful & FZ_REPLY_ERROR)
+						{
+							if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
+								dir.direntry[i].size = -1;
+						}
+						dir.direntry[i].date.hasdate = false;
+						break;
+					}
+				if (i==dir.num)
+				{
+					t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
+					int i;
+					for (i=0; i<dir.num; i++)
+						entries[i]=dir.direntry[i];
+					entries[i].name=filename;
+					entries[i].lName=filename;
+					entries[i].lName.MakeLower();
+					entries[i].dir=FALSE;
+					entries[i].date.hasdate=FALSE;
+					entries[i].size=-1;
+					if (nSuccessful&FZ_REPLY_OK)
+						entries[i].bUnsure=FALSE;
+					else
+						entries[i].bUnsure=TRUE;
+
+					delete [] dir.direntry;
+					dir.direntry=entries;
+					dir.num++;
+				}
 #ifndef MPEXT_NO_CACHE
-                cache.Store(dir, bCached);
+				cache.Store(dir, bCached);
 #endif
-                BOOL updated=FALSE;
-                if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
-                {
-                    updated=TRUE;
-                    SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
-                }
-                if (!updated)
-                    if (bFound && WorkingDir.path==dir.path)
-                    {
-                        updated = TRUE;
-                        m_pOwner->SetWorkingDir(&dir);
-                    }
-            }
+				BOOL updated=FALSE;
+				if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
+				{
+					updated=TRUE;
+					SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
+				}
+				if (!updated)
+					if (bFound && WorkingDir.path==dir.path)
+					{
+						updated = TRUE;
+						m_pOwner->SetWorkingDir(&dir);
+					}
+			}
 #ifndef MPEXT_NO_CACHE
-            cache.Unlock();
+			cache.Unlock();
 #endif
-        }
-
-        if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
-        {
-            if (m_Operation.nOpMode&CSMODE_TRANSFER)
-                if (nSuccessful&FZ_REPLY_ABORTED)
-                    //Transfer aborted by user
-                    ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,1);
-                else
-                    ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,1);
-            else if (m_Operation.nOpMode&CSMODE_LIST)
-                ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
-        }
-        else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
-            ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,0);
-    }
-    else
-    {
-        //No operation in progress
-        nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
-        if (!nSuccessful)
-            ASSERT(FALSE);
-    }
-
-    if (nSuccessful&FZ_REPLY_DISCONNECTED)
-        m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
-
-    if (m_Operation.nOpMode)
-        PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
-    else
-        PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
-
-    m_Operation.nOpMode=0;
-    m_Operation.nOpState=-1;
-
-    if (m_Operation.pData)
-        delete m_Operation.pData;
-    m_Operation.pData=0;
+		}
+
+		if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
+		{
+			if (m_Operation.nOpMode&CSMODE_TRANSFER)
+				if (nSuccessful&FZ_REPLY_ABORTED)
+					//Transfer aborted by user
+					ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,1);
+				else
+					ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,1);
+			else if (m_Operation.nOpMode&CSMODE_LIST)
+				ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
+		}
+		else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
+			ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,0);
+	}
+	else
+	{
+		//No operation in progress
+		nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
+		if (!nSuccessful)
+			ASSERT(FALSE);
+	}
+
+	if (nSuccessful&FZ_REPLY_DISCONNECTED)
+		m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
+
+	if (m_Operation.nOpMode)
+		PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
+	else
+		PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
+
+	m_Operation.nOpMode=0;
+	m_Operation.nOpState=-1;
+
+	if (m_Operation.pData)
+		delete m_Operation.pData;
+	m_Operation.pData=0;
 }
 
 void CFtpControlSocket::Delete(CString filename, const CServerPath &path)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Delete(\"%s\", \"%s\")  OpMode=%d OpState=%d"), filename, path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Delete(\"%s\", \"%s\")  OpMode=%d OpState=%d"), filename, path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
 
-    class CDeleteData : public CFtpControlSocket::t_operation::COpData
-    {
+	class CDeleteData : public CFtpControlSocket::t_operation::COpData
+	{
 public:
-        CDeleteData() {}
-        virtual ~CDeleteData() {}
-        CString m_FileName;
-        CServerPath path;
-    };
-    if (filename!="")
-    {
-        ASSERT(!path.IsEmpty());
-        ASSERT(m_Operation.nOpMode==CSMODE_NONE);
-        ASSERT(m_Operation.nOpState==-1);
-        ASSERT(!m_Operation.pData);
-        m_Operation.nOpMode=CSMODE_DELETE;
-        if (!Send("DELE " + path.FormatFilename(filename)))
-            return;
-        CDeleteData *data=new CDeleteData;
-        data->m_FileName=filename;
-        data->path=path;
-        m_Operation.pData=data;
-    }
-    else
-    {
-        ASSERT(path.IsEmpty());
-        ASSERT(m_Operation.nOpMode==CSMODE_DELETE);
-        ASSERT(m_Operation.nOpState==-1);
-        ASSERT(m_Operation.pData);
-        int res=GetReplyCode();
-        if (res==2 || res==3)
-        { //Remove file from cached dirs
-            CDeleteData *pData=(CDeleteData *)m_Operation.pData;
+		CDeleteData() {}
+		virtual ~CDeleteData() {}
+		CString m_FileName;
+		CServerPath path;
+	};
+	if (filename!="")
+	{
+		ASSERT(!path.IsEmpty());
+		ASSERT(m_Operation.nOpMode==CSMODE_NONE);
+		ASSERT(m_Operation.nOpState==-1);
+		ASSERT(!m_Operation.pData);
+		m_Operation.nOpMode=CSMODE_DELETE;
+		if (!Send("DELE " + path.FormatFilename(filename)))
+			return;
+		CDeleteData *data=new CDeleteData;
+		data->m_FileName=filename;
+		data->path=path;
+		m_Operation.pData=data;
+	}
+	else
+	{
+		ASSERT(path.IsEmpty());
+		ASSERT(m_Operation.nOpMode==CSMODE_DELETE);
+		ASSERT(m_Operation.nOpState==-1);
+		ASSERT(m_Operation.pData);
+		int res=GetReplyCode();
+		if (res==2 || res==3)
+		{ //Remove file from cached dirs
+			CDeleteData *pData=(CDeleteData *)m_Operation.pData;
 #ifndef MPEXT_NO_CACHE
-            CDirectoryCache cache;
-            cache.Lock();
-            BOOL bCached=TRUE;
-            t_directory dir;
-            BOOL res=cache.Lookup(pData->path,m_CurrentServer,dir);
-            if (!res)
-                bCached=FALSE;
+			CDirectoryCache cache;
+			cache.Lock();
+			BOOL bCached=TRUE;
+			t_directory dir;
+			BOOL res=cache.Lookup(pData->path,m_CurrentServer,dir);
+			if (!res)
+				bCached=FALSE;
 #else
-            t_directory dir;
-            BOOL res=FALSE;
+			t_directory dir;
+			BOOL res=FALSE;
 #endif
-            if (!res && m_pDirectoryListing)
-            {
-                if (m_pDirectoryListing->path==pData->path)
-                {
-                    dir=*m_pDirectoryListing;
-                    res=TRUE;
-                }
-            }
-            t_directory WorkingDir;
-            BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
-            if (!res && bFound)
-                if (WorkingDir.path==pData->path)
-                {
-                    dir=WorkingDir;
-                    res=TRUE;
-                }
-            if (res)
-            {
-                BOOL found=FALSE;
-                for (int i=0;i<dir.num;i++)
-                {
-                    if (dir.direntry[i].name==pData->m_FileName)
-                    {
-                        ASSERT(!dir.direntry[i].dir || dir.direntry[i].bLink);
-                        found=TRUE;
-                        break;
-                    }
-                }
-                if (found)
-                {
-                    t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
-                    int j=0;
-                    int i;
-                    for (i=0; i<dir.num; i++)
-                    {
-                        if (dir.direntry[i].name==pData->m_FileName)
-                            continue;
-                        direntry[j]=dir.direntry[i];
-                        j++;
-                    }
-                    delete [] dir.direntry;
-                    dir.direntry=direntry;
-                    dir.num--;
+			if (!res && m_pDirectoryListing)
+			{
+				if (m_pDirectoryListing->path==pData->path)
+				{
+					dir=*m_pDirectoryListing;
+					res=TRUE;
+				}
+			}
+			t_directory WorkingDir;
+			BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
+			if (!res && bFound)
+				if (WorkingDir.path==pData->path)
+				{
+					dir=WorkingDir;
+					res=TRUE;
+				}
+			if (res)
+			{
+				BOOL found=FALSE;
+				for (int i=0;i<dir.num;i++)
+				{
+					if (dir.direntry[i].name==pData->m_FileName)
+					{
+						ASSERT(!dir.direntry[i].dir || dir.direntry[i].bLink);
+						found=TRUE;
+						break;
+					}
+				}
+				if (found)
+				{
+					t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
+					int j=0;
+					int i;
+					for (i=0; i<dir.num; i++)
+					{
+						if (dir.direntry[i].name==pData->m_FileName)
+							continue;
+						direntry[j]=dir.direntry[i];
+						j++;
+					}
+					delete [] dir.direntry;
+					dir.direntry=direntry;
+					dir.num--;
 #ifndef MPEXT_NO_CACHE
-                    cache.Store(dir, bCached);
+					cache.Store(dir, bCached);
 #endif
-                    BOOL updated=FALSE;
-                    if (m_pDirectoryListing)
-                        if (m_pDirectoryListing->path==dir.path)
-                        {
-                            updated=TRUE;
-                            SetDirectoryListing(&dir);
-                        }
-                    if (!updated)
-                        if (WorkingDir.path==dir.path)
-                        {
-                            updated=TRUE;
-                            m_pOwner->SetWorkingDir(&dir);
-                        }
-                }
-            }
+					BOOL updated=FALSE;
+					if (m_pDirectoryListing)
+						if (m_pDirectoryListing->path==dir.path)
+						{
+							updated=TRUE;
+							SetDirectoryListing(&dir);
+						}
+					if (!updated)
+						if (WorkingDir.path==dir.path)
+						{
+							updated=TRUE;
+							m_pOwner->SetWorkingDir(&dir);
+						}
+				}
+			}
 #ifndef MPEXT_NO_CACHE
-            cache.Unlock();
+			cache.Unlock();
 #endif
-        }
-        ResetOperation(FZ_REPLY_OK);
-    }
+		}
+		ResetOperation(FZ_REPLY_OK);
+	}
 }
 
 void CFtpControlSocket::RemoveDir(CString dirname, const CServerPath &path)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("RemoveDir(\"%s\", \"%s\")  OpMode=%d OpState=%d"), dirname, path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("RemoveDir(\"%s\", \"%s\")  OpMode=%d OpState=%d"), dirname, path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
 
-    class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
-    {
+	class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
+	{
 public:
-        CRemoveDirData() {}
-        virtual ~CRemoveDirData() {}
-        CString m_DirName;
-        CServerPath path;
-    };
-    if (dirname != "")
-    {
-        ASSERT(!path.IsEmpty());
-        ASSERT(m_Operation.nOpMode == CSMODE_NONE);
-        ASSERT(m_Operation.nOpState == -1);
-        ASSERT(!m_Operation.pData);
-        m_Operation.nOpMode = CSMODE_RMDIR;
-        CServerPath newPath = path;
-        if (!newPath.AddSubdir(dirname))
-        {
-            ShowStatus(_T("Unable to concatenate path"), 1);
-            return;
-        }
-        if (!Send("RMD "+ newPath.GetPath()))
-            return;
-        CRemoveDirData *data = new CRemoveDirData;
-        data->m_DirName = dirname;
-        data->path = path;
-        m_Operation.pData = data;
-    }
-    else
-    {
-        ASSERT(path.IsEmpty());
-        ASSERT(m_Operation.nOpMode == CSMODE_RMDIR);
-        ASSERT(m_Operation.nOpState == -1);
-        ASSERT(m_Operation.pData);
-        int res = GetReplyCode();
-        if (res == 2 || res == 3)
-        { //Remove dir from cached dirs
-            CRemoveDirData *pData=  (CRemoveDirData *)m_Operation.pData;
+		CRemoveDirData() {}
+		virtual ~CRemoveDirData() {}
+		CString m_DirName;
+		CServerPath path;
+	};
+	if (dirname != "")
+	{
+		ASSERT(!path.IsEmpty());
+		ASSERT(m_Operation.nOpMode == CSMODE_NONE);
+		ASSERT(m_Operation.nOpState == -1);
+		ASSERT(!m_Operation.pData);
+		m_Operation.nOpMode = CSMODE_RMDIR;
+		CServerPath newPath = path;
+		if (!newPath.AddSubdir(dirname))
+		{
+			ShowStatus(_T("Unable to concatenate path"), 1);
+			return;
+		}
+		if (!Send("RMD "+ newPath.GetPath()))
+			return;
+		CRemoveDirData *data = new CRemoveDirData;
+		data->m_DirName = dirname;
+		data->path = path;
+		m_Operation.pData = data;
+	}
+	else
+	{
+		ASSERT(path.IsEmpty());
+		ASSERT(m_Operation.nOpMode == CSMODE_RMDIR);
+		ASSERT(m_Operation.nOpState == -1);
+		ASSERT(m_Operation.pData);
+		int res = GetReplyCode();
+		if (res == 2 || res == 3)
+		{ //Remove dir from cached dirs
+			CRemoveDirData *pData=  (CRemoveDirData *)m_Operation.pData;
 #ifndef MPEXT_NO_CACHE
-            CDirectoryCache cache;
-            cache.Lock();
-            BOOL bCached = TRUE;
-            t_directory dir;
-            BOOL res = cache.Lookup(pData->path, m_CurrentServer, dir);
-            if (!res)
-                bCached = FALSE;
+			CDirectoryCache cache;
+			cache.Lock();
+			BOOL bCached = TRUE;
+			t_directory dir;
+			BOOL res = cache.Lookup(pData->path, m_CurrentServer, dir);
+			if (!res)
+				bCached = FALSE;
 #else
-            t_directory dir;
-            BOOL res = FALSE;
+			t_directory dir;
+			BOOL res = FALSE;
 #endif
-            if (!res && m_pDirectoryListing)
-            {
-                if (m_pDirectoryListing->path == pData->path)
-                {
-                    dir = *m_pDirectoryListing;
-                    res = TRUE;
-                }
-            }
-            t_directory WorkingDir;
-            BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
-            if (!res && bFound)
-                if (WorkingDir.path == pData->path)
-                {
-                    dir = WorkingDir;
-                    res = TRUE;
-                }
-            if (res)
-            {
-                BOOL found = FALSE;
-                for (int i = 0; i < dir.num; i++)
-                {
-                    if (dir.direntry[i].name == pData->m_DirName)
-                    {
-                        ASSERT(dir.direntry[i].dir);
-                        found = TRUE;
-                        break;
-                    }
-                }
-                if (found)
-                {
-                    t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
-                    int j = 0;
-                    int i;
-                    for (i = 0; i < dir.num; i++)
-                    {
-                        if (dir.direntry[i].name == pData->m_DirName)
-                            continue;
-                        direntry[j] = dir.direntry[i];
-                        j++;
-                    }
-                    delete [] dir.direntry;
-                    dir.direntry = direntry;
-                    dir.num--;
+			if (!res && m_pDirectoryListing)
+			{
+				if (m_pDirectoryListing->path == pData->path)
+				{
+					dir = *m_pDirectoryListing;
+					res = TRUE;
+				}
+			}
+			t_directory WorkingDir;
+			BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
+			if (!res && bFound)
+				if (WorkingDir.path == pData->path)
+				{
+					dir = WorkingDir;
+					res = TRUE;
+				}
+			if (res)
+			{
+				BOOL found = FALSE;
+				for (int i = 0; i < dir.num; i++)
+				{
+					if (dir.direntry[i].name == pData->m_DirName)
+					{
+						ASSERT(dir.direntry[i].dir);
+						found = TRUE;
+						break;
+					}
+				}
+				if (found)
+				{
+					t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
+					int j = 0;
+					int i;
+					for (i = 0; i < dir.num; i++)
+					{
+						if (dir.direntry[i].name == pData->m_DirName)
+							continue;
+						direntry[j] = dir.direntry[i];
+						j++;
+					}
+					delete [] dir.direntry;
+					dir.direntry = direntry;
+					dir.num--;
 #ifndef MPEXT_NO_CACHE
-                    cache.Store(dir, bCached);
+					cache.Store(dir, bCached);
 #endif
-                    BOOL updated = FALSE;
-                    if (m_pDirectoryListing)
-                        if (m_pDirectoryListing->path == dir.path)
-                        {
-                            updated = TRUE;
-                            SetDirectoryListing(&dir);
-                        }
-                    if (!updated)
-                        if (WorkingDir.path == dir.path)
-                        {
-                            updated = TRUE;
-                            m_pOwner->SetWorkingDir(&dir);
-                        }
-                }
-            }
+					BOOL updated = FALSE;
+					if (m_pDirectoryListing)
+						if (m_pDirectoryListing->path == dir.path)
+						{
+							updated = TRUE;
+							SetDirectoryListing(&dir);
+						}
+					if (!updated)
+						if (WorkingDir.path == dir.path)
+						{
+							updated = TRUE;
+							m_pOwner->SetWorkingDir(&dir);
+						}
+				}
+			}
 #ifndef MPEXT_NO_CACHE
-            if (cache.Lookup(pData->path, pData->m_DirName, m_CurrentServer, dir))
-                cache.Purge(dir.path, dir.server);
-            cache.Unlock();
+			if (cache.Lookup(pData->path, pData->m_DirName, m_CurrentServer, dir))
+				cache.Purge(dir.path, dir.server);
+			cache.Unlock();
 #endif
-            ResetOperation(FZ_REPLY_OK);
-        }
-        else
-            ResetOperation(FZ_REPLY_ERROR);
-    }
+			ResetOperation(FZ_REPLY_OK);
+		}
+		else
+			ResetOperation(FZ_REPLY_ERROR);
+	}
 }
 
 int CFtpControlSocket::CheckOverwriteFile()
 {
-    if (!m_Operation.pData)
-        return FZ_REPLY_ERROR;
-
-    CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
-
-    int nReplyError = 0;
-    CFileStatus64 status;
-    BOOL res = GetStatus64(pData->transferfile.localfile, status);
-    if (!res)
-        if (!pData->transferfile.get)
-            nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
-        else
-            m_Operation.nOpState = FILETRANSFER_TYPE;
-    else
-    {
-        if (status.m_attribute & 0x10)
-            nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
-        else
-        {
-            _int64 localsize;
-            if (!GetLength64(pData->transferfile.localfile, localsize))
-                if (!pData->transferfile.get)
-                    nReplyError = FZ_REPLY_CRITICALERROR;
-                else
-                    m_Operation.nOpState = FILETRANSFER_TYPE;
-
-
-            CTime *localtime = NULL;
-            TRY
-            {
-                if (status.m_has_mtime && status.m_mtime != -1)
-                    localtime = new CTime(status.m_mtime);
-            }
-            CATCH_ALL(e)
-            {
-                TCHAR buffer[1024];
-                CString str =_T("Exception creating CTime object: ");
-                if (e->GetErrorMessage(buffer, 1024, NULL))
-                    str += buffer;
-                else
-                    str += _T("Unknown exception");
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
-                localtime = NULL;
-            }
-            END_CATCH_ALL;
-            BOOL bRemoteFileExists = FALSE;
-            __int64 remotesize = -1;
-            CTime *remotetime = 0;
-            if (m_pDirectoryListing)
-            {
-                for (int i=0; i<m_pDirectoryListing->num; i++)
-                {
-                    CString remotefile = pData->transferfile.remotefile;
-                    if (m_pDirectoryListing->direntry[i].name == remotefile)
-                    {
-                        remotesize = m_pDirectoryListing->direntry[i].size;
-                        if (m_pDirectoryListing->direntry[i].date.hasdate)
-                        {
-                            TRY
-                            {
-                                remotetime = new CTime(m_pDirectoryListing->direntry[i].date.year,
-                                    m_pDirectoryListing->direntry[i].date.month,
-                                    m_pDirectoryListing->direntry[i].date.day,
-                                    m_pDirectoryListing->direntry[i].date.hastime?m_pDirectoryListing->direntry[i].date.hour:0,
-                                    m_pDirectoryListing->direntry[i].date.hastime?m_pDirectoryListing->direntry[i].date.minute:0,
-                                    0,-1);
-                            }
-                            CATCH_ALL(e)
-                            {
-                                TCHAR buffer[1024];
-                                CString str =_T("Exception creating CTime object: ");
-                                if (e->GetErrorMessage(buffer, 1024, NULL))
-                                    str += buffer;
-                                else
-                                    str += _T("Unknown exception");
-                                LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
-                                remotetime = NULL;
-                            }
-                            END_CATCH_ALL;
-                        }
-                        bRemoteFileExists = TRUE;
-                        break;
-                    }
-                }
-            }
-            if (remotesize == -1 && pData->pFileSize)
-            {
-                remotesize = *pData->pFileSize;
-                bRemoteFileExists = TRUE;
-            }
-            if (!remotetime && pData->pFileTime)
-            {
-                remotetime = new CTime;
-                *remotetime = *pData->pFileTime;
-                bRemoteFileExists = TRUE;
-            }
-
-            if (bRemoteFileExists || pData->transferfile.get )
-            {
-                COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
-                t_transferfile *pTransferFile = new t_transferfile;
-                *pTransferFile = pData->transferfile;
-                pOverwriteData->pTransferFile = pTransferFile;
-                if (pData->transferfile.get)
-                {
-                    int pos = pData->transferfile.localfile.ReverseFind('\\');
-                    ASSERT(pos!=-1);
-                    pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
-                    pOverwriteData->FileName2 = pData->transferfile.remotefile;
-                    pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
-                    pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
-                    pOverwriteData->size1 = localsize;
-                    pOverwriteData->size2 = remotesize;
-                    pOverwriteData->time1 = localtime;
-                    pOverwriteData->time2 = remotetime;
-                }
-                else
-                {
-                    int pos = pData->transferfile.localfile.ReverseFind('\\');
-                    ASSERT(pos!=-1);
-                    pOverwriteData->FileName1 = pData->transferfile.remotefile;
-                    pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
-                    pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
-                    pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
-                    pOverwriteData->size1 = remotesize;
-                    pOverwriteData->size2 = localsize;
-                    pOverwriteData->time1 = remotetime;
-                    pOverwriteData->time2 = localtime;
-                }
-                pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
-                if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
-                {
-                    delete pOverwriteData;
-                    nReplyError = FZ_REPLY_ERROR;
-                }
-                else
-                {
-                    m_bCheckForTimeout = FALSE;
-                    m_Operation.nOpState = FILETRANSFER_WAIT;
-                }
-            }
-            else
-            {
-                m_Operation.nOpState = FILETRANSFER_TYPE;
-                delete localtime;
-                delete remotetime;
-            }
-        }
-    }
-    return nReplyError;
+	if (!m_Operation.pData)
+		return FZ_REPLY_ERROR;
+
+	CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
+
+	int nReplyError = 0;
+	CFileStatus64 status;
+	BOOL res = GetStatus64(pData->transferfile.localfile, status);
+	if (!res)
+		if (!pData->transferfile.get)
+			nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
+		else
+			m_Operation.nOpState = FILETRANSFER_TYPE;
+	else
+	{
+		if (status.m_attribute & 0x10)
+			nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
+		else
+		{
+			_int64 localsize;
+			if (!GetLength64(pData->transferfile.localfile, localsize))
+				if (!pData->transferfile.get)
+					nReplyError = FZ_REPLY_CRITICALERROR;
+				else
+					m_Operation.nOpState = FILETRANSFER_TYPE;
+
+
+			CTime *localtime = NULL;
+			TRY
+			{
+				if (status.m_has_mtime && status.m_mtime != -1)
+					localtime = new CTime(status.m_mtime);
+			}
+			CATCH_ALL(e)
+			{
+				TCHAR buffer[1024];
+				CString str =_T("Exception creating CTime object: ");
+				if (e->GetErrorMessage(buffer, 1024, NULL))
+					str += buffer;
+				else
+					str += _T("Unknown exception");
+				LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
+				localtime = NULL;
+			}
+			END_CATCH_ALL;
+			BOOL bRemoteFileExists = FALSE;
+			__int64 remotesize = -1;
+			CTime *remotetime = 0;
+			if (m_pDirectoryListing)
+			{
+				for (int i=0; i<m_pDirectoryListing->num; i++)
+				{
+					CString remotefile = pData->transferfile.remotefile;
+					if (m_pDirectoryListing->direntry[i].name == remotefile)
+					{
+						remotesize = m_pDirectoryListing->direntry[i].size;
+						if (m_pDirectoryListing->direntry[i].date.hasdate)
+						{
+							TRY
+							{
+								remotetime = new CTime(m_pDirectoryListing->direntry[i].date.year,
+									m_pDirectoryListing->direntry[i].date.month,
+									m_pDirectoryListing->direntry[i].date.day,
+									m_pDirectoryListing->direntry[i].date.hastime?m_pDirectoryListing->direntry[i].date.hour:0,
+									m_pDirectoryListing->direntry[i].date.hastime?m_pDirectoryListing->direntry[i].date.minute:0,
+									0,-1);
+							}
+							CATCH_ALL(e)
+							{
+								TCHAR buffer[1024];
+								CString str =_T("Exception creating CTime object: ");
+								if (e->GetErrorMessage(buffer, 1024, NULL))
+									str += buffer;
+								else
+									str += _T("Unknown exception");
+								LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
+								remotetime = NULL;
+							}
+							END_CATCH_ALL;
+						}
+						bRemoteFileExists = TRUE;
+						break;
+					}
+				}
+			}
+			if (remotesize == -1 && pData->pFileSize)
+			{
+				remotesize = *pData->pFileSize;
+				bRemoteFileExists = TRUE;
+			}
+			if (!remotetime && pData->pFileTime)
+			{
+				remotetime = new CTime;
+				*remotetime = *pData->pFileTime;
+				bRemoteFileExists = TRUE;
+			}
+
+			if (bRemoteFileExists || pData->transferfile.get )
+			{
+				COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
+				t_transferfile *pTransferFile = new t_transferfile;
+				*pTransferFile = pData->transferfile;
+				pOverwriteData->pTransferFile = pTransferFile;
+				if (pData->transferfile.get)
+				{
+					int pos = pData->transferfile.localfile.ReverseFind('\\');
+					ASSERT(pos!=-1);
+					pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
+					pOverwriteData->FileName2 = pData->transferfile.remotefile;
+					pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
+					pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
+					pOverwriteData->size1 = localsize;
+					pOverwriteData->size2 = remotesize;
+					pOverwriteData->time1 = localtime;
+					pOverwriteData->time2 = remotetime;
+				}
+				else
+				{
+					int pos = pData->transferfile.localfile.ReverseFind('\\');
+					ASSERT(pos!=-1);
+					pOverwriteData->FileName1 = pData->transferfile.remotefile;
+					pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
+					pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
+					pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
+					pOverwriteData->size1 = remotesize;
+					pOverwriteData->size2 = localsize;
+					pOverwriteData->time1 = remotetime;
+					pOverwriteData->time2 = localtime;
+				}
+				pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
+				if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
+				{
+					delete pOverwriteData;
+					nReplyError = FZ_REPLY_ERROR;
+				}
+				else
+				{
+					m_bCheckForTimeout = FALSE;
+					m_Operation.nOpState = FILETRANSFER_WAIT;
+				}
+			}
+			else
+			{
+				m_Operation.nOpState = FILETRANSFER_TYPE;
+				delete localtime;
+				delete remotetime;
+			}
+		}
+	}
+	return nReplyError;
 }
 
 void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData *pData)
 {
-    if (!pData)
-        return;
-    if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
-        return;
-    if (m_Operation.nOpState != FILETRANSFER_WAIT)
-        return;
-
-    CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
-    if (!pTransferData)
-        return;
-
-    pTransferData->transferdata.bResume = false;
-
-    m_bCheckForTimeout = TRUE;
-    int nReplyError = 0;
-    switch (nAction)
-    {
-    case FILEEXISTS_SKIP:
-        nReplyError = FZ_REPLY_OK;
-        break;
-    case FILEEXISTS_OVERWRITE:
-        pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
-        break;
-    case FILEEXISTS_OVERWRITEIFNEWER:
-        if ( !pData->time1 || !pData->time2 )
-            pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
-        else if (*pData->time2 <= *pData->time1)
-            nReplyError = FZ_REPLY_OK;
-        else
-            pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
-        break;
-    case FILEEXISTS_RENAME:
-        if (pTransferData->transferfile.get)
-        {
-            CFileStatus64 status;
-            if (GetStatus64(pData->FileName1, status))
-            {
-                ShowStatus(IDS_ERRORMSG_NAMEINUSE, 1);
-                nReplyError=  FZ_REPLY_CRITICALERROR;
-            }
-            else
-            {
-                pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
-                //Replace invalid characters in the local filename
-                int pos = pTransferData->transferfile.localfile.ReverseFind('\\');
-                for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
-                    if (pTransferData->transferfile.localfile[i] == ':')
-                        pTransferData->transferfile.localfile.SetAt(i, '_');
-
-                pTransferData->nWaitNextOpState=  FILETRANSFER_TYPE;
-            }
-        }
-        else
-        {
-            ASSERT(m_pDirectoryListing);
-            int i;
-            for (i = 0; i < m_pDirectoryListing->num; i++)
-            {
-                if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
-                {
-                    ShowStatus(IDS_ERRORMSG_NAMEINUSE, 1);
-                    nReplyError = FZ_REPLY_CRITICALERROR;
-                    break;
-                }
-            }
-            if (i==m_pDirectoryListing->num)
-            {
-                pTransferData->transferfile.remotefile = pData->FileName1;
-                pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
-            }
-        }
-        break;
-    case FILEEXISTS_RESUME_ASKONFAIL:
-        pTransferData->askOnResumeFail = true;
-    case FILEEXISTS_RESUME:
-        if (pData->size1 >= 0)
-        {
-            pTransferData->transferdata.bResume = TRUE;
-        }
-        pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
-        break;
-    }
-    if (nReplyError == FZ_REPLY_OK)
-        ResetOperation(FZ_REPLY_OK);
-    else if (nReplyError)
-        ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
-    else
-        FileTransfer();
+	if (!pData)
+		return;
+	if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
+		return;
+	if (m_Operation.nOpState != FILETRANSFER_WAIT)
+		return;
+
+	CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
+	if (!pTransferData)
+		return;
+
+	pTransferData->transferdata.bResume = false;
+
+	m_bCheckForTimeout = TRUE;
+	int nReplyError = 0;
+	switch (nAction)
+	{
+	case FILEEXISTS_SKIP:
+		nReplyError = FZ_REPLY_OK;
+		break;
+	case FILEEXISTS_OVERWRITE:
+		pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
+		break;
+	case FILEEXISTS_OVERWRITEIFNEWER:
+		if ( !pData->time1 || !pData->time2 )
+			pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
+		else if (*pData->time2 <= *pData->time1)
+			nReplyError = FZ_REPLY_OK;
+		else
+			pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
+		break;
+	case FILEEXISTS_RENAME:
+		if (pTransferData->transferfile.get)
+		{
+			CFileStatus64 status;
+			if (GetStatus64(pData->FileName1, status))
+			{
+				ShowStatus(IDS_ERRORMSG_NAMEINUSE, 1);
+				nReplyError=  FZ_REPLY_CRITICALERROR;
+			}
+			else
+			{
+				pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
+				//Replace invalid characters in the local filename
+				int pos = pTransferData->transferfile.localfile.ReverseFind('\\');
+				for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
+					if (pTransferData->transferfile.localfile[i] == ':')
+						pTransferData->transferfile.localfile.SetAt(i, '_');
+
+				pTransferData->nWaitNextOpState=  FILETRANSFER_TYPE;
+			}
+		}
+		else
+		{
+			ASSERT(m_pDirectoryListing);
+			int i;
+			for (i = 0; i < m_pDirectoryListing->num; i++)
+			{
+				if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
+				{
+					ShowStatus(IDS_ERRORMSG_NAMEINUSE, 1);
+					nReplyError = FZ_REPLY_CRITICALERROR;
+					break;
+				}
+			}
+			if (i==m_pDirectoryListing->num)
+			{
+				pTransferData->transferfile.remotefile = pData->FileName1;
+				pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
+			}
+		}
+		break;
+	case FILEEXISTS_RESUME_ASKONFAIL:
+		pTransferData->askOnResumeFail = true;
+	case FILEEXISTS_RESUME:
+		if (pData->size1 >= 0)
+		{
+			pTransferData->transferdata.bResume = TRUE;
+		}
+		pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
+		break;
+	}
+	if (nReplyError == FZ_REPLY_OK)
+		ResetOperation(FZ_REPLY_OK);
+	else if (nReplyError)
+		ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
+	else
+		FileTransfer();
 }
 
 void CFtpControlSocket::SendKeepAliveCommand()
 {
-    m_bKeepAliveActive=TRUE;
-    //Choose a random command from the list
-    char commands[4][7]={"PWD","REST 0","TYPE A","TYPE I"};
-    int choice=(rand()*4)/(RAND_MAX+1);
-    Send(commands[choice]);
+	m_bKeepAliveActive=TRUE;
+	//Choose a random command from the list
+	char commands[4][7]={"PWD","REST 0","TYPE A","TYPE I"};
+	int choice=(rand()*4)/(RAND_MAX+1);
+	Send(commands[choice]);
 }
 
 void CFtpControlSocket::MakeDir(const CServerPath &path)
 {
-    //Directory creation works like this:
-    //Find existing parent and create subdirs one by one
-    LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("MakeDir(\"%s\")  OpMode=%d OpState=%d"), path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
-
-    if (m_Operation.nOpState == MKD_INIT)
-    {
-        ASSERT(!path.IsEmpty());
-        ASSERT(m_Operation.nOpMode==CSMODE_NONE);
-        ASSERT(!m_Operation.pData);
-        m_Operation.nOpMode = CSMODE_MKDIR;
-        if (!Send("CWD "+path.GetParent().GetPath()))
-            return;
-        CMakeDirData *data = new CMakeDirData;
-        data->path = path;
-        data->Current = path.GetParent();
-        data->Segments.push_front(path.GetLastSegment());
-        m_Operation.pData = data;
-        m_Operation.nOpState = MKD_FINDPARENT;
-    }
-    else if (m_Operation.nOpState==MKD_FINDPARENT)
-    {
-        ASSERT(m_Operation.nOpMode==CSMODE_MKDIR);
-        ASSERT(path.IsEmpty());
-        ASSERT(m_Operation.pData);
-        CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
-        int res=GetReplyCode();
-        if (res==2 || res==3)
-        {
-            m_pOwner->SetCurrentPath(pData->Current);
-
-            m_Operation.nOpState=MKD_MAKESUBDIRS;
-            pData->Current.AddSubdir(pData->Segments.front());
-            CString Segment=pData->Segments.front();
-            pData->Segments.pop_front();
-            if (Send( _T("MKD ") + Segment))
-                m_Operation.nOpState = MKD_CHANGETOSUBDIR;
-            else
-                return;
-        }
-        else
-        {
-            if (!pData->Current.HasParent())
-                ResetOperation(FZ_REPLY_ERROR);
-            else
-            {
-                pData->Segments.push_front(pData->Current.GetLastSegment());
-                pData->Current=pData->Current.GetParent();
-                if (!Send("CWD "+pData->Current.GetPath()))
-                    return;
-            }
-        }
-    }
-    else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
-    {
-        int res=GetReplyCode();
-        if (res==2 || res==3)
-        { //Create dir entry in parent dir
-            CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
-
-            ASSERT(!pData->Segments.empty());
-
-            m_pOwner->SetCurrentPath(pData->Current);
-
-            pData->Current.AddSubdir(pData->Segments.front());
-            CString Segment=pData->Segments.front();
-            pData->Segments.pop_front();
-            if (Send( _T("MKD ") + Segment))
-                m_Operation.nOpState=MKD_CHANGETOSUBDIR;
-            else
-                return;
-        }
-        else
-            ResetOperation(FZ_REPLY_ERROR);
-    }
-    else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
-    {
-        CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
-        int res=GetReplyCode();
-        if (res==2 || res==3 || //Creation successful
-            GetReply() == _T("550 Directory already exists"))//Creation was successful, although someone else did the work for us
-        { //Create dir entry in parent dir
-            CServerPath path2=pData->Current;
-            if (path2.HasParent())
-            {
-                CString name=path2.GetLastSegment();
-                path2=path2.GetParent();
+	//Directory creation works like this:
+	//Find existing parent and create subdirs one by one
+	LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("MakeDir(\"%s\")  OpMode=%d OpState=%d"), path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
+
+	if (m_Operation.nOpState == MKD_INIT)
+	{
+		ASSERT(!path.IsEmpty());
+		ASSERT(m_Operation.nOpMode==CSMODE_NONE);
+		ASSERT(!m_Operation.pData);
+		m_Operation.nOpMode = CSMODE_MKDIR;
+		if (!Send("CWD "+path.GetParent().GetPath()))
+			return;
+		CMakeDirData *data = new CMakeDirData;
+		data->path = path;
+		data->Current = path.GetParent();
+		data->Segments.push_front(path.GetLastSegment());
+		m_Operation.pData = data;
+		m_Operation.nOpState = MKD_FINDPARENT;
+	}
+	else if (m_Operation.nOpState==MKD_FINDPARENT)
+	{
+		ASSERT(m_Operation.nOpMode==CSMODE_MKDIR);
+		ASSERT(path.IsEmpty());
+		ASSERT(m_Operation.pData);
+		CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
+		int res=GetReplyCode();
+		if (res==2 || res==3)
+		{
+			m_pOwner->SetCurrentPath(pData->Current);
+
+			m_Operation.nOpState=MKD_MAKESUBDIRS;
+			pData->Current.AddSubdir(pData->Segments.front());
+			CString Segment=pData->Segments.front();
+			pData->Segments.pop_front();
+			if (Send( _T("MKD ") + Segment))
+				m_Operation.nOpState = MKD_CHANGETOSUBDIR;
+			else
+				return;
+		}
+		else
+		{
+			if (!pData->Current.HasParent())
+				ResetOperation(FZ_REPLY_ERROR);
+			else
+			{
+				pData->Segments.push_front(pData->Current.GetLastSegment());
+				pData->Current=pData->Current.GetParent();
+				if (!Send("CWD "+pData->Current.GetPath()))
+					return;
+			}
+		}
+	}
+	else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
+	{
+		int res=GetReplyCode();
+		if (res==2 || res==3)
+		{ //Create dir entry in parent dir
+			CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
+
+			ASSERT(!pData->Segments.empty());
+
+			m_pOwner->SetCurrentPath(pData->Current);
+
+			pData->Current.AddSubdir(pData->Segments.front());
+			CString Segment=pData->Segments.front();
+			pData->Segments.pop_front();
+			if (Send( _T("MKD ") + Segment))
+				m_Operation.nOpState=MKD_CHANGETOSUBDIR;
+			else
+				return;
+		}
+		else
+			ResetOperation(FZ_REPLY_ERROR);
+	}
+	else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
+	{
+		CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
+		int res=GetReplyCode();
+		if (res==2 || res==3 || //Creation successful
+			GetReply() == _T("550 Directory already exists"))//Creation was successful, although someone else did the work for us
+		{ //Create dir entry in parent dir
+			CServerPath path2=pData->Current;
+			if (path2.HasParent())
+			{
+				CString name=path2.GetLastSegment();
+				path2=path2.GetParent();
 
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
-                t_directory dir;
-                cache.Lock();
-                BOOL bCached = TRUE;
-                BOOL res = cache.Lookup(path2, m_CurrentServer,dir);
-                if (!res)
-                    bCached = FALSE;
+				CDirectoryCache cache;
+				t_directory dir;
+				cache.Lock();
+				BOOL bCached = TRUE;
+				BOOL res = cache.Lookup(path2, m_CurrentServer,dir);
+				if (!res)
+					bCached = FALSE;
 #else
-                t_directory dir;
-                BOOL res = FALSE;
+				t_directory dir;
+				BOOL res = FALSE;
 #endif
-                if (!res && m_pDirectoryListing)
-                {
-                    if (m_pDirectoryListing->path == path2)
-                    {
-                        dir = *m_pDirectoryListing;
-                        res = TRUE;
-                    }
-                }
-                t_directory WorkingDir;
-                BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
-                if (!res && bFound)
-                    if (WorkingDir.path == path2)
-                    {
-                        dir = WorkingDir;
-                        res = TRUE;
-                    }
-                if (!res)
-                {
-                    dir.path = path2;
-                    dir.server = m_CurrentServer;
-                }
-
-                int i;
-                for (i=0; i<dir.num; i++)
-                    if (dir.direntry[i].name==name)
-                    {
-                        LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Dir already exists in cache!"));
-                        break;
-                    }
-                if (i==dir.num)
-                {
-                    t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
-                    for (i=0;i<dir.num;i++)
-                        entries[i]=dir.direntry[i];
-                    entries[i].name=name;
-                    entries[i].lName=name;
-                    entries[i].lName.MakeLower();
-                    entries[i].dir=TRUE;
-                    entries[i].date.hasdate=FALSE;
-                    entries[i].size=-1;
-                    entries[i].bUnsure=FALSE;
-                    delete [] dir.direntry;
-                    dir.direntry=entries;
-                    dir.num++;
+				if (!res && m_pDirectoryListing)
+				{
+					if (m_pDirectoryListing->path == path2)
+					{
+						dir = *m_pDirectoryListing;
+						res = TRUE;
+					}
+				}
+				t_directory WorkingDir;
+				BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
+				if (!res && bFound)
+					if (WorkingDir.path == path2)
+					{
+						dir = WorkingDir;
+						res = TRUE;
+					}
+				if (!res)
+				{
+					dir.path = path2;
+					dir.server = m_CurrentServer;
+				}
+
+				int i;
+				for (i=0; i<dir.num; i++)
+					if (dir.direntry[i].name==name)
+					{
+						LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Dir already exists in cache!"));
+						break;
+					}
+				if (i==dir.num)
+				{
+					t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
+					for (i=0;i<dir.num;i++)
+						entries[i]=dir.direntry[i];
+					entries[i].name=name;
+					entries[i].lName=name;
+					entries[i].lName.MakeLower();
+					entries[i].dir=TRUE;
+					entries[i].date.hasdate=FALSE;
+					entries[i].size=-1;
+					entries[i].bUnsure=FALSE;
+					delete [] dir.direntry;
+					dir.direntry=entries;
+					dir.num++;
 
 #ifndef MPEXT_NO_CACHE
-                    cache.Store(dir, bCached);
+					cache.Store(dir, bCached);
 #endif
-                    BOOL updated = FALSE;
-                    if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
-                    {
-                        updated = TRUE;
-                        SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
-                    }
-                    if (!updated)
-                        if (bFound && WorkingDir.path == dir.path)
-                        {
-                            updated = TRUE;
-                            m_pOwner->SetWorkingDir(&dir);
-                        }
-                }
+					BOOL updated = FALSE;
+					if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
+					{
+						updated = TRUE;
+						SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
+					}
+					if (!updated)
+						if (bFound && WorkingDir.path == dir.path)
+						{
+							updated = TRUE;
+							m_pOwner->SetWorkingDir(&dir);
+						}
+				}
 
 #ifndef MPEXT_NO_CACHE
-                cache.Unlock();
+				cache.Unlock();
 #endif
-            }
-        }
-
-        //Continue operation even if MKD failed, maybe another thread did create this directory for us
-        if (pData->Segments.empty())
-            ResetOperation(FZ_REPLY_OK);
-        else
-        {
-            if (Send( _T("CWD ") + pData->Current.GetPath()))
-                m_Operation.nOpState=MKD_MAKESUBDIRS;
-            else
-                return;
-        }
-    }
-    else
-        ASSERT(FALSE);
+			}
+		}
+
+		//Continue operation even if MKD failed, maybe another thread did create this directory for us
+		if (pData->Segments.empty())
+			ResetOperation(FZ_REPLY_OK);
+		else
+		{
+			if (Send( _T("CWD ") + pData->Current.GetPath()))
+				m_Operation.nOpState=MKD_MAKESUBDIRS;
+			else
+				return;
+		}
+	}
+	else
+		ASSERT(FALSE);
 }
 
 void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPath &path, const CServerPath &newPath)
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Rename(\"%s\", \"%s\", \"%s\")  OpMode=%d OpState=%d"), oldName, newName, path.GetPath(),
-               m_Operation.nOpMode, m_Operation.nOpState);
-    class CRenameData : public CFtpControlSocket::t_operation::COpData
-    {
-    public:
-        CRenameData() {}
-        virtual ~CRenameData() {}
-        CString oldName, newName;
-        CServerPath path;
-        CServerPath newPath;
-    };
-    if (oldName != "")
-    {
-        ASSERT(newName != "");
-        ASSERT(!path.IsEmpty());
-        ASSERT(m_Operation.nOpMode == CSMODE_NONE);
-        ASSERT(m_Operation.nOpState == -1);
-        ASSERT(!m_Operation.pData);
-        m_Operation.nOpMode = CSMODE_RENAME;
-        if (!Send("RNFR " + path.FormatFilename(oldName)))
-            return;
-        CRenameData *data = new CRenameData;
-        data->oldName = oldName;
-        data->newName = newName;
-        data->path = path;
-        data->newPath = newPath;
-        m_Operation.pData = data;
-    }
-    else
-    {
-        ASSERT(oldName == "");
-        ASSERT(path.IsEmpty());
-        ASSERT(m_Operation.nOpMode == CSMODE_RENAME);
-        ASSERT(m_Operation.pData);
-        CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
-
-        if (m_Operation.nOpState == -1)
-        {
-            int res = GetReplyCode();
-            if (res == 2 || res == 3)
-            {
-                m_Operation.nOpState++;
-                if (pData->newPath.IsEmpty())
-                {
-                    if (!Send("RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
-                        return;
-                }
-                else
-                    if (!Send("RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
-                        return;
-            }
-            else
-                ResetOperation(FZ_REPLY_ERROR);
-        }
-        else
-        {
-            int res = GetReplyCode();
-            if (res == 2 || res == 3)
-            { //Rename entry in cached directory
-                CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Rename(\"%s\", \"%s\", \"%s\")  OpMode=%d OpState=%d"), oldName, newName, path.GetPath(),
+			   m_Operation.nOpMode, m_Operation.nOpState);
+	class CRenameData : public CFtpControlSocket::t_operation::COpData
+	{
+	public:
+		CRenameData() {}
+		virtual ~CRenameData() {}
+		CString oldName, newName;
+		CServerPath path;
+		CServerPath newPath;
+	};
+	if (oldName != "")
+	{
+		ASSERT(newName != "");
+		ASSERT(!path.IsEmpty());
+		ASSERT(m_Operation.nOpMode == CSMODE_NONE);
+		ASSERT(m_Operation.nOpState == -1);
+		ASSERT(!m_Operation.pData);
+		m_Operation.nOpMode = CSMODE_RENAME;
+		if (!Send("RNFR " + path.FormatFilename(oldName)))
+			return;
+		CRenameData *data = new CRenameData;
+		data->oldName = oldName;
+		data->newName = newName;
+		data->path = path;
+		data->newPath = newPath;
+		m_Operation.pData = data;
+	}
+	else
+	{
+		ASSERT(oldName == "");
+		ASSERT(path.IsEmpty());
+		ASSERT(m_Operation.nOpMode == CSMODE_RENAME);
+		ASSERT(m_Operation.pData);
+		CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
+
+		if (m_Operation.nOpState == -1)
+		{
+			int res = GetReplyCode();
+			if (res == 2 || res == 3)
+			{
+				m_Operation.nOpState++;
+				if (pData->newPath.IsEmpty())
+				{
+					if (!Send("RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
+						return;
+				}
+				else
+					if (!Send("RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
+						return;
+			}
+			else
+				ResetOperation(FZ_REPLY_ERROR);
+		}
+		else
+		{
+			int res = GetReplyCode();
+			if (res == 2 || res == 3)
+			{ //Rename entry in cached directory
+				CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
 
 #ifndef MPEXT_NO_CACHE
-                CDirectoryCache cache;
+				CDirectoryCache cache;
 
-                cache.Lock();
+				cache.Lock();
 
-                //Rename all references to the directory in the cache
-                if (pData->newPath.IsEmpty())
-                    cache.Rename(pData->path, pData->oldName, pData->newName, m_CurrentServer);
+				//Rename all references to the directory in the cache
+				if (pData->newPath.IsEmpty())
+					cache.Rename(pData->path, pData->oldName, pData->newName, m_CurrentServer);
 
-                BOOL bCached = TRUE;
-                t_directory dir;
-                BOOL res = cache.Lookup(pData->path, m_CurrentServer, dir);
-                if (!res)
-                    bCached = FALSE;
+				BOOL bCached = TRUE;
+				t_directory dir;
+				BOOL res = cache.Lookup(pData->path, m_CurrentServer, dir);
+				if (!res)
+					bCached = FALSE;
 #else
-                t_directory dir;
-                BOOL res = FALSE;
+				t_directory dir;
+				BOOL res = FALSE;
 #endif
-                if (!res && m_pDirectoryListing)
-                {
-                    if (m_pDirectoryListing->path == pData->path)
-                    {
-                        dir = *m_pDirectoryListing;
-                        res = TRUE;
-                    }
-                }
-                t_directory WorkingDir;
-                BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
-                if (!res && bFound)
-                    if (WorkingDir.path == pData->path)
-                    {
-                        dir = WorkingDir;
-                        res = TRUE;
-                    }
-                if (res)
-                {
-                    for (int i=0; i<dir.num; i++)
-                        if (dir.direntry[i].name == pData->oldName)
-                        {
-                            if (pData->newPath.IsEmpty())
-                            {
-                                dir.direntry[i].name = pData->newName;
-                                dir.direntry[i].lName = pData->newName;
-                                dir.direntry[i].lName.MakeLower();
+				if (!res && m_pDirectoryListing)
+				{
+					if (m_pDirectoryListing->path == pData->path)
+					{
+						dir = *m_pDirectoryListing;
+						res = TRUE;
+					}
+				}
+				t_directory WorkingDir;
+				BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
+				if (!res && bFound)
+					if (WorkingDir.path == pData->path)
+					{
+						dir = WorkingDir;
+						res = TRUE;
+					}
+				if (res)
+				{
+					for (int i=0; i<dir.num; i++)
+						if (dir.direntry[i].name == pData->oldName)
+						{
+							if (pData->newPath.IsEmpty())
+							{
+								dir.direntry[i].name = pData->newName;
+								dir.direntry[i].lName = pData->newName;
+								dir.direntry[i].lName.MakeLower();
 
 #ifndef MPEXT_NO_CACHE
-                                CDirectoryCache cache;
-                                cache.Store(dir, bCached);
+								CDirectoryCache cache;
+								cache.Store(dir, bCached);
 #endif
-                                BOOL updated = FALSE;
-                                if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
-                                {
-                                    updated = TRUE;
-                                    SetDirectoryListing(&dir, WorkingDir.path == dir.path);
-                                }
-                                if (!updated)
-                                    if (WorkingDir.path == dir.path)
-                                    {
-                                        updated = TRUE;
-                                        m_pOwner->SetWorkingDir(&dir);
-                                    }
-                            }
-                            else
-                            {
-                                t_directory::t_direntry oldentry = dir.direntry[i];
-
-                                for (int j = i+1; j < dir.num; j++)
-                                {
-                                    dir.direntry[j-1] = dir.direntry[j];
-                                }
-                                dir.num--;
+								BOOL updated = FALSE;
+								if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
+								{
+									updated = TRUE;
+									SetDirectoryListing(&dir, WorkingDir.path == dir.path);
+								}
+								if (!updated)
+									if (WorkingDir.path == dir.path)
+									{
+										updated = TRUE;
+										m_pOwner->SetWorkingDir(&dir);
+									}
+							}
+							else
+							{
+								t_directory::t_direntry oldentry = dir.direntry[i];
+
+								for (int j = i+1; j < dir.num; j++)
+								{
+									dir.direntry[j-1] = dir.direntry[j];
+								}
+								dir.num--;
 
 #ifndef MPEXT_NO_CACHE
-                                cache.Store(dir, bCached);
-
-                                // If directory, delete old directory from cache
-                                t_directory olddir;
-                                res = cache.Lookup(pData->path, pData->oldName, m_CurrentServer, olddir);
-                                if (res)
-                                {
-                                    cache.Purge(olddir.path, m_CurrentServer);
-                                    t_directory newdir;
-                                    if (cache.Lookup(dir.path, m_CurrentServer, newdir))
-                                        dir = newdir;
-                                }
+								cache.Store(dir, bCached);
+
+								// If directory, delete old directory from cache
+								t_directory olddir;
+								res = cache.Lookup(pData->path, pData->oldName, m_CurrentServer, olddir);
+								if (res)
+								{
+									cache.Purge(olddir.path, m_CurrentServer);
+									t_directory newdir;
+									if (cache.Lookup(dir.path, m_CurrentServer, newdir))
+										dir = newdir;
+								}
 #endif
 
-                                BOOL updated = FALSE;
-                                if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
-                                {
-                                    updated = TRUE;
-                                    SetDirectoryListing(&dir, WorkingDir.path == dir.path);
-                                }
-                                if (!updated)
-                                    if (WorkingDir.path == dir.path)
-                                    {
-                                        updated = TRUE;
-                                        m_pOwner->SetWorkingDir(&dir);
-                                    }
+								BOOL updated = FALSE;
+								if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
+								{
+									updated = TRUE;
+									SetDirectoryListing(&dir, WorkingDir.path == dir.path);
+								}
+								if (!updated)
+									if (WorkingDir.path == dir.path)
+									{
+										updated = TRUE;
+										m_pOwner->SetWorkingDir(&dir);
+									}
 
 #ifndef MPEXT_NO_CACHE
-                                BOOL bCached = TRUE;
-                                BOOL res = cache.Lookup(pData->newPath, m_CurrentServer, dir);
-                                if (!res)
-                                    bCached = FALSE;
+								BOOL bCached = TRUE;
+								BOOL res = cache.Lookup(pData->newPath, m_CurrentServer, dir);
+								if (!res)
+									bCached = FALSE;
 #else
-                                BOOL res = FALSE;
+								BOOL res = FALSE;
 #endif
 
-                                if (!res && m_pDirectoryListing)
-                                {
-                                    if (m_pDirectoryListing->path == pData->newPath)
-                                    {
-                                        dir = *m_pDirectoryListing;
-                                        res = TRUE;
-                                    }
-                                }
-                                t_directory WorkingDir;
-                                BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
-                                if (!res && bFound)
-                                    if (WorkingDir.path == pData->newPath)
-                                    {
-                                        dir = WorkingDir;
-                                        res = TRUE;
-                                    }
-                                if (res)
-                                {
-                                    t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
-                                    for (int i = 0; i < dir.num; i++)
-                                        direntry[i] = dir.direntry[i];
-                                    direntry[dir.num] = oldentry;
-                                    direntry[dir.num].name = pData->newName;
-                                    direntry[dir.num].lName = pData->newName;
-                                    direntry[dir.num].lName.MakeLower();
-                                    dir.num++;
-                                    delete [] dir.direntry;
-                                    dir.direntry = direntry;
+								if (!res && m_pDirectoryListing)
+								{
+									if (m_pDirectoryListing->path == pData->newPath)
+									{
+										dir = *m_pDirectoryListing;
+										res = TRUE;
+									}
+								}
+								t_directory WorkingDir;
+								BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
+								if (!res && bFound)
+									if (WorkingDir.path == pData->newPath)
+									{
+										dir = WorkingDir;
+										res = TRUE;
+									}
+								if (res)
+								{
+									t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
+									for (int i = 0; i < dir.num; i++)
+										direntry[i] = dir.direntry[i];
+									direntry[dir.num] = oldentry;
+									direntry[dir.num].name = pData->newName;
+									direntry[dir.num].lName = pData->newName;
+									direntry[dir.num].lName.MakeLower();
+									dir.num++;
+									delete [] dir.direntry;
+									dir.direntry = direntry;
 
 #ifndef MPEXT_NO_CACHE
-                                    cache.Store(dir, bCached);
+									cache.Store(dir, bCached);
 #endif
-                                    BOOL updated = FALSE;
-                                    if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
-                                    {
-                                        updated = TRUE;
-                                        SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
-                                    }
-                                    if (!updated)
-                                        if (bFound && WorkingDir.path == dir.path)
-                                        {
-                                            updated = TRUE;
-                                            m_pOwner->SetWorkingDir(&dir);
-                                        }
-                                }
-                            }
-                            break;
-                        }
-                }
+									BOOL updated = FALSE;
+									if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
+									{
+										updated = TRUE;
+										SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
+									}
+									if (!updated)
+										if (bFound && WorkingDir.path == dir.path)
+										{
+											updated = TRUE;
+											m_pOwner->SetWorkingDir(&dir);
+										}
+								}
+							}
+							break;
+						}
+				}
 #ifndef MPEXT_NO_CACHE
-                cache.Unlock();
+				cache.Unlock();
 #endif
-                ResetOperation(FZ_REPLY_OK);
-            }
-            else
-                ResetOperation(FZ_REPLY_ERROR);
-        }
-    }
+				ResetOperation(FZ_REPLY_OK);
+			}
+			else
+				ResetOperation(FZ_REPLY_ERROR);
+		}
+	}
 }
 
 #ifndef MPEXT_NO_SSL
 void CFtpControlSocket::SetVerifyCertResult(int nResult, t_SslCertData *pData)
 {
-    ASSERT(pData);
-    if (!m_pSslLayer)
-        return;
-    if (!m_Operation.nOpMode == CSMODE_CONNECT)
-        return;
-    m_bCheckForTimeout = TRUE;
-    m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
-    m_LastRecvTime = CTime::GetCurrentTime();
+	ASSERT(pData);
+	if (!m_pSslLayer)
+		return;
+	if (!m_Operation.nOpMode == CSMODE_CONNECT)
+		return;
+	m_bCheckForTimeout = TRUE;
+	m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
+	m_LastRecvTime = CTime::GetCurrentTime();
 }
 #endif
 
 void CFtpControlSocket::OnTimer()
 {
-    CheckForTimeout();
-    ResumeTransfer();
-    if (COptions::GetOptionVal(OPTION_KEEPALIVE))
-    {
-        if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
-        {
-            //Getting intervals for the Keep Alive feature
-            int low=COptions::GetOptionVal(OPTION_INTERVALLOW);
-            int diff=COptions::GetOptionVal(OPTION_INTERVALHIGH)-low;
-
-            //Choose a new delay
-            static int delay=low+(rand()*diff)/RAND_MAX;
-
-            CTimeSpan span=CTime::GetCurrentTime()-m_LastSendTime;
-            if (span.GetTotalSeconds()>=delay)
-                SendKeepAliveCommand();
-        }
-    }
+	CheckForTimeout();
+	ResumeTransfer();
+	if (COptions::GetOptionVal(OPTION_KEEPALIVE))
+	{
+		if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
+		{
+			//Getting intervals for the Keep Alive feature
+			int low=COptions::GetOptionVal(OPTION_INTERVALLOW);
+			int diff=COptions::GetOptionVal(OPTION_INTERVALHIGH)-low;
+
+			//Choose a new delay
+			static int delay=low+(rand()*diff)/RAND_MAX;
+
+			CTimeSpan span=CTime::GetCurrentTime()-m_LastSendTime;
+			if (span.GetTotalSeconds()>=delay)
+				SendKeepAliveCommand();
+		}
+	}
 }
 
 BOOL CFtpControlSocket::IsReady()
 {
-    return !m_bKeepAliveActive;
+	return !m_bKeepAliveActive;
 }
 
 void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nValue)
 {
-    m_Operation.nOpMode=CSMODE_CHMOD;
-    CString str;
-    str.Format( _T("SITE CHMOD %03d %s"), nValue, path.FormatFilename(filename));
-    Send(str);
+	m_Operation.nOpMode=CSMODE_CHMOD;
+	CString str;
+	str.Format( _T("SITE CHMOD %03d %s"), nValue, path.FormatFilename(filename));
+	Send(str);
 }
 
 void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData)
 {
-    switch (pData->nRequestType)
-    {
-    case FZ_ASYNCREQUEST_OVERWRITE:
-        SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
-        break;
+	switch (pData->nRequestType)
+	{
+	case FZ_ASYNCREQUEST_OVERWRITE:
+		SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
+		break;
 #ifndef MPEXT_NO_SSL
-    case FZ_ASYNCREQUEST_VERIFYCERT:
-        SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
-        break;
+	case FZ_ASYNCREQUEST_VERIFYCERT:
+		SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
+		break;
 #endif
 #ifndef MPEXT_NO_GSS
-    case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
-        if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
-            break;
-        if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
-        {
-            DoClose();
-            break;
-        }
-        if (!nAction)
-        {
-            DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
-            ShowStatus(IDS_ERRORMSG_INTERRUPTED,1);
-            break;
-        }
-        m_Operation.nOpState=-1;
-        LogOnToServer(TRUE);
-        break;
-    case FZ_ASYNCREQUEST_GSS_NEEDPASS:
-        if (m_Operation.nOpMode!=CSMODE_CONNECT ||
-            m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
-            break;
-        if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
-        {
-            DoClose();
-            break;
-        }
-        if (!nAction)
-        {
-            DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
-            ShowStatus(IDS_ERRORMSG_INTERRUPTED,1);
-            break;
-        }
-        else
-        {
-            m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
-            m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
-            LogOnToServer(TRUE);
-        }
-        break;
-    case FZ_ASYNCREQUEST_GSS_NEEDUSER:
-        if (m_Operation.nOpMode != CSMODE_CONNECT ||
-            m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
-            break;
-        if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
-        {
-            DoClose();
-            break;
-        }
-        if (!nAction)
-        {
-            DoClose(FZ_REPLY_CRITICALERROR | FZ_REPLY_CANCEL);
-            ShowStatus(IDS_ERRORMSG_INTERRUPTED, 1);
-            break;
-        }
-        else
-        {
-            m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
-            m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
-            LogOnToServer(TRUE);
-        }
-        break;
+	case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
+		if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
+			break;
+		if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
+		{
+			DoClose();
+			break;
+		}
+		if (!nAction)
+		{
+			DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
+			ShowStatus(IDS_ERRORMSG_INTERRUPTED,1);
+			break;
+		}
+		m_Operation.nOpState=-1;
+		LogOnToServer(TRUE);
+		break;
+	case FZ_ASYNCREQUEST_GSS_NEEDPASS:
+		if (m_Operation.nOpMode!=CSMODE_CONNECT ||
+			m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
+			break;
+		if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
+		{
+			DoClose();
+			break;
+		}
+		if (!nAction)
+		{
+			DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
+			ShowStatus(IDS_ERRORMSG_INTERRUPTED,1);
+			break;
+		}
+		else
+		{
+			m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
+			m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
+			LogOnToServer(TRUE);
+		}
+		break;
+	case FZ_ASYNCREQUEST_GSS_NEEDUSER:
+		if (m_Operation.nOpMode != CSMODE_CONNECT ||
+			m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
+			break;
+		if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
+		{
+			DoClose();
+			break;
+		}
+		if (!nAction)
+		{
+			DoClose(FZ_REPLY_CRITICALERROR | FZ_REPLY_CANCEL);
+			ShowStatus(IDS_ERRORMSG_INTERRUPTED, 1);
+			break;
+		}
+		else
+		{
+			m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
+			m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
+			LogOnToServer(TRUE);
+		}
+		break;
 #endif
-    default:
-        LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Unknown request reply %d"), pData->nRequestType);
-        break;
-    }
+	default:
+		LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Unknown request reply %d"), pData->nRequestType);
+		break;
+	}
 }
 
 int CFtpControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
 {
-    for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
-    {
-        if (iter->nType == LAYERCALLBACK_STATECHANGE)
-        {
+	for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
+	{
+		if (iter->nType == LAYERCALLBACK_STATECHANGE)
+		{
 #ifndef MPEXT_NO_SSL
-            if (iter->pLayer == m_pSslLayer)
-            {
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pSslLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
-                delete [] iter->str;
-                continue;
-            }
+			if (iter->pLayer == m_pSslLayer)
+			{
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pSslLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
+				delete [] iter->str;
+				continue;
+			}
 #endif
-        }
-        else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
-        {
+		}
+		else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
+		{
 #ifndef MPEXT_NO_SSL
-            if (iter->pLayer == m_pSslLayer)
-            {
-                USES_CONVERSION;
-
-                switch (iter->nParam1)
-                {
-                case SSL_INFO:
-                    switch (iter->nParam2)
-                    {
-                    case SSL_INFO_ESTABLISHED:
-                        ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, 0);
-                        PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, 1), 0);
-                        if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
-                        {
-                            LogOnToServer();
-                        }
-                        break;
-                    }
-                    break;
-                case SSL_FAILURE:
-                    switch (iter->nParam2)
-                    {
-                    case SSL_FAILURE_UNKNOWN:
-                        ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, 1);
-                        break;
-                    case SSL_FAILURE_ESTABLISH:
-                        ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, 1);
-                        break;
-                    case SSL_FAILURE_LOADDLLS:
-                        ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
-                        break;
-                    case SSL_FAILURE_INITSSL:
-                        ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
-                        break;
-                    case SSL_FAILURE_VERIFYCERT:
-                        ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, 1);
-                        break;
-                    case SSL_FAILURE_CERTREJECTED:
-                        ShowStatus(IDS_ERRORMSG_CERTREJECTED, 1);
-                        m_bDidRejectCertificate = TRUE;
-                        break;
-                    }
-                    TriggerEvent(FD_CLOSE);
-                    break;
-                case SSL_VERBOSE_INFO:
-                    LogMessage(FZ_LOG_INFO, A2CT(iter->str));
-                    break;
-                case SSL_VERBOSE_WARNING:
-                    LogMessage(FZ_LOG_WARNING, A2CT(iter->str));
-                    break;
-                case SSL_VERIFY_CERT:
-                    t_SslCertData *pData = new t_SslCertData;
-                    if (m_pSslLayer->GetPeerCertificateData(*pData))
-                    {
-                        CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
-                        pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
-
-                        pRequestData->pCertData = pData;
-
-                        m_bCheckForTimeout = FALSE;
-                        if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
-                        {
-                            delete pRequestData->pCertData;
-                            delete pRequestData;
-                            ResetOperation(FZ_REPLY_ERROR);
-                        }
-                        delete [] iter->str;
-                        continue;
-                    }
-                    else
-                    {
-                        delete pData;
-                        delete [] iter->str;
-                        ResetOperation(FZ_REPLY_ERROR);
-                        delete [] iter->str;
-                        continue;
-                    }
-                    break;
-                }
-                delete [] iter->str;
-                continue;
-            }
+			if (iter->pLayer == m_pSslLayer)
+			{
+				USES_CONVERSION;
+
+				switch (iter->nParam1)
+				{
+				case SSL_INFO:
+					switch (iter->nParam2)
+					{
+					case SSL_INFO_ESTABLISHED:
+						ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, 0);
+						PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, 1), 0);
+						if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
+						{
+							LogOnToServer();
+						}
+						break;
+					}
+					break;
+				case SSL_FAILURE:
+					switch (iter->nParam2)
+					{
+					case SSL_FAILURE_UNKNOWN:
+						ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, 1);
+						break;
+					case SSL_FAILURE_ESTABLISH:
+						ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, 1);
+						break;
+					case SSL_FAILURE_LOADDLLS:
+						ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
+						break;
+					case SSL_FAILURE_INITSSL:
+						ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
+						break;
+					case SSL_FAILURE_VERIFYCERT:
+						ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, 1);
+						break;
+					case SSL_FAILURE_CERTREJECTED:
+						ShowStatus(IDS_ERRORMSG_CERTREJECTED, 1);
+						m_bDidRejectCertificate = TRUE;
+						break;
+					}
+					TriggerEvent(FD_CLOSE);
+					break;
+				case SSL_VERBOSE_INFO:
+					LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
+					break;
+				case SSL_VERBOSE_WARNING:
+					LogMessageRaw(FZ_LOG_WARNING, A2CT(iter->str));
+					break;
+				case SSL_VERIFY_CERT:
+					t_SslCertData *pData = new t_SslCertData;
+					if (m_pSslLayer->GetPeerCertificateData(*pData))
+					{
+						CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
+						pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
+
+						pRequestData->pCertData = pData;
+
+						m_bCheckForTimeout = FALSE;
+						if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
+						{
+							delete pRequestData->pCertData;
+							delete pRequestData;
+							ResetOperation(FZ_REPLY_ERROR);
+						}
+						delete [] iter->str;
+						continue;
+					}
+					else
+					{
+						delete pData;
+						delete [] iter->str;
+						ResetOperation(FZ_REPLY_ERROR);
+						delete [] iter->str;
+						continue;
+					}
+					break;
+				}
+				delete [] iter->str;
+				continue;
+			}
 #ifndef MPEXT_NO_GSS
-            else
+			else
 #endif
 #endif
 #ifndef MPEXT_NO_GSS
-            if (iter->pLayer == m_pGssLayer)
-            {
-                if (iter->nParam1 == GSS_AUTHCOMPLETE ||
-                    iter->nParam1 == GSS_AUTHFAILED)
-                {
-                    LogOnToServer(TRUE);
-                    delete [] iter->str;
-                    continue;
-                }
-            }
+			if (iter->pLayer == m_pGssLayer)
+			{
+				if (iter->nParam1 == GSS_AUTHCOMPLETE ||
+					iter->nParam1 == GSS_AUTHFAILED)
+				{
+					LogOnToServer(TRUE);
+					delete [] iter->str;
+					continue;
+				}
+			}
 #endif
-        }
-        std::list<t_callbackMsg> tmp;
-        tmp.push_back(*iter);
-        CControlSocket::OnLayerCallback(tmp);
-    }
-    return 0;
+		}
+		std::list<t_callbackMsg> tmp;
+		tmp.push_back(*iter);
+		CControlSocket::OnLayerCallback(tmp);
+	}
+	return 0;
 }
 
 BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd)
 {
-    CListData *pData = static_cast<CListData *>(m_Operation.pData);
-    ASSERT(pData);
-
-    int pos1 = rawpwd.Find('"');
-    int pos2 = rawpwd.ReverseFind('"');
-    if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
-    {
-        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("No quoted path found, try using first token as path"));
-        pos1 = rawpwd.Find(' ');
-        if (pos1 != -1)
-        {
-            pos2 = rawpwd.Find(' ', pos1 + 1);
-            if (pos2 == -1)
-                pos2 = rawpwd.GetLength();
-        }
-
-        if (pos1 == -1)
-        {
-            LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Can't parse path!"));
-            ResetOperation(FZ_REPLY_ERROR);
-            return FALSE;
-        }
-    }
-    rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
-
-    CServerPath realPath = m_pOwner->GetCurrentPath();
-    realPath.SetServer(m_CurrentServer);
-    if (!realPath.SetPath(rawpwd))
-    {
-        LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Can't parse path!"));
-        ResetOperation(FZ_REPLY_ERROR);
-        return FALSE;
-    }
-    m_pOwner->SetCurrentPath(realPath);
-
-    return TRUE;
+	CListData *pData = static_cast<CListData *>(m_Operation.pData);
+	ASSERT(pData);
+
+	int pos1 = rawpwd.Find('"');
+	int pos2 = rawpwd.ReverseFind('"');
+	if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
+	{
+		LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("No quoted path found, try using first token as path"));
+		pos1 = rawpwd.Find(' ');
+		if (pos1 != -1)
+		{
+			pos2 = rawpwd.Find(' ', pos1 + 1);
+			if (pos2 == -1)
+				pos2 = rawpwd.GetLength();
+		}
+
+		if (pos1 == -1)
+		{
+			LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Can't parse path!"));
+			ResetOperation(FZ_REPLY_ERROR);
+			return FALSE;
+		}
+	}
+	rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
+
+	CServerPath realPath = m_pOwner->GetCurrentPath();
+	realPath.SetServer(m_CurrentServer);
+	if (!realPath.SetPath(rawpwd))
+	{
+		LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Can't parse path!"));
+		ResetOperation(FZ_REPLY_ERROR);
+		return FALSE;
+	}
+	m_pOwner->SetCurrentPath(realPath);
+	
+	return TRUE;
 }
 
 void CFtpControlSocket::DiscardLine(CStringA line)
 {
-    if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
-    {
-        line.MakeUpper();
+	if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
+	{
+		line.MakeUpper();
 #ifndef MPEXT_NO_ZLIB
-        if (line == _T(" MODE Z") || line.Left(8) == _T(" MODE Z "))
-            m_zlibSupported = true;
-        else
+		if (line == _T(" MODE Z") || line.Left(8) == _T(" MODE Z "))
+			m_zlibSupported = true;
+		else
 #endif
-            if (line == _T(" UTF8") && m_CurrentServer.nUTF8 != 2)
-            m_bAnnouncesUTF8 = true;
-        else if (line == _T(" CLNT") || line.Left(6) == _T(" CLNT "))
-            m_hasClntCmd = true;
-    }
+			if (line == _T(" UTF8") && m_CurrentServer.nUTF8 != 2)
+			m_bAnnouncesUTF8 = true;
+		else if (line == _T(" CLNT") || line.Left(6) == _T(" CLNT "))
+			m_hasClntCmd = true;
+	}
 }
 
 bool CFtpControlSocket::NeedModeCommand()
 {
 #ifdef MPEXT_NO_ZLIB
-    return false;
+	return false;
 #else
-    bool useZlib;
-    if (m_Operation.nOpMode == CSMODE_LIST || (m_Operation.nOpMode == CSMODE_TRANSFER && m_Operation.nOpMode <= FILETRANSFER_TYPE))
-        useZlib = COptions::GetOptionVal(OPTION_MODEZ_USE) != 0;
-    else
-        useZlib = COptions::GetOptionVal(OPTION_MODEZ_USE) > 1;
+	bool useZlib;
+	if (m_Operation.nOpMode == CSMODE_LIST || (m_Operation.nOpMode == CSMODE_TRANSFER && m_Operation.nOpMode <= FILETRANSFER_TYPE))
+		useZlib = COptions::GetOptionVal(OPTION_MODEZ_USE) != 0;
+	else
+		useZlib = COptions::GetOptionVal(OPTION_MODEZ_USE) > 1;
 
-    if (!m_useZlib && !m_zlibSupported)
-        return false;
+	if (!m_useZlib && !m_zlibSupported)
+		return false;
 
-    return m_useZlib != useZlib;
+	return m_useZlib != useZlib;
 #endif
 }
 
 bool CFtpControlSocket::NeedOptsCommand()
 {
 #ifndef MPEXT_NO_ZLIB
-    if (!m_useZlib)
+	if (!m_useZlib)
 #endif
-        return false;
+		return false;
 
 #ifndef MPEXT_NO_ZLIB
-    return m_zlibLevel != COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
+	return m_zlibLevel != COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
 #endif
 }
 
 CString CFtpControlSocket::GetReply()
 {
-    if (m_RecvBuffer.empty())
-        return "";
-
-    USES_CONVERSION;
-
-    if (m_bUTF8)
-    {
-        // convert from UTF-8 to ANSI
-        LPCSTR utf8 = (LPCSTR)m_RecvBuffer.front();
-        if (!utf8_valid((const unsigned char*)utf8, strlen(utf8)))
-        {
-            if (m_CurrentServer.nUTF8 != 1)
-            {
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Server does not send proper UTF-8, falling back to local charset"));
-                m_bUTF8 = false;
-            }
-            return A2CT(m_RecvBuffer.front());
-        }
-
-        // convert from UTF-8 to ANSI
-        int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
-        if (!len)
-        {
-            m_RecvBuffer.pop_front();
-            if (m_RecvBuffer.empty())
-                m_RecvBuffer.push_back("");
-            return "";
-        }
-        else
-        {
-            LPWSTR p1 = new WCHAR[len + 1];
-            MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
-            CString reply = W2CT(p1);
-            delete [] p1;
-            return reply;
-        }
-    }
-    else
-        return A2CT(m_RecvBuffer.front());
+	if (m_RecvBuffer.empty())
+		return "";
+
+	USES_CONVERSION;
+
+	if (m_bUTF8)
+	{
+		// convert from UTF-8 to ANSI
+		LPCSTR utf8 = (LPCSTR)m_RecvBuffer.front();
+		if (!utf8_valid((const unsigned char*)utf8, strlen(utf8)))
+		{
+			if (m_CurrentServer.nUTF8 != 1)
+			{
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Server does not send proper UTF-8, falling back to local charset"));
+				m_bUTF8 = false;
+			}
+			return A2CT(m_RecvBuffer.front());
+		}
+
+		// convert from UTF-8 to ANSI
+		int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
+		if (!len)
+		{
+			m_RecvBuffer.pop_front();
+			if (m_RecvBuffer.empty())
+				m_RecvBuffer.push_back("");
+			return "";
+		}
+		else
+		{
+			LPWSTR p1 = new WCHAR[len + 1];
+			MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
+			CString reply = W2CT(p1);
+			delete [] p1;
+			return reply;
+		}
+	}
+	else
+		return A2CT(m_RecvBuffer.front());
 }
 
 void CFtpControlSocket::OnSend(int nErrorCode)
 {
-    if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
-        return;
-
-    int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
-    if (res == -1)
-    {
-        if (GetLastError() != WSAEWOULDBLOCK)
-        {
-            ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
-            DoClose();
-        }
-        return;
-    }
-    if (!res)
-    {
-        ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
-        DoClose();
-    }
-
-    m_awaitsReply = true;
-    m_LastSendTime = CTime::GetCurrentTime();
-    PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
-
-    if (res == m_sendBufferLen)
-    {
-        delete [] m_sendBuffer;
-        m_sendBuffer = 0;
-        m_sendBufferLen = 0;
-    }
-    else
-    {
-        char* tmp = new char[m_sendBufferLen - res];
-        memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
-        delete [] m_sendBuffer;
-        m_sendBuffer = tmp;
-        m_sendBufferLen -= res;
-    }
+	if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
+		return;
+
+	int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
+	if (res == -1)
+	{
+		if (GetLastError() != WSAEWOULDBLOCK)
+		{
+			ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
+			DoClose();
+		}
+		return;
+	}
+	if (!res)
+	{
+		ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
+		DoClose();
+	}
+
+	m_awaitsReply = true;
+	m_LastSendTime = CTime::GetCurrentTime();
+	PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
+
+	if (res == m_sendBufferLen)
+	{
+		delete [] m_sendBuffer;
+		m_sendBuffer = 0;
+		m_sendBufferLen = 0;
+	}
+	else
+	{
+		char* tmp = new char[m_sendBufferLen - res];
+		memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
+		delete [] m_sendBuffer;
+		m_sendBuffer = tmp;
+		m_sendBufferLen -= res;
+	}
 }
 
 bool CFtpControlSocket::IsMisleadingListResponse()
 {
-    // Some servers are broken. Instead of an empty listing, some MVS servers
-    // for example they return something "550 no members found"
-    // Other servers return "550 No files found."
+	// Some servers are broken. Instead of an empty listing, some MVS servers
+	// for example they return something "550 no members found"
+	// Other servers return "550 No files found."
 
-    CString retmsg = GetReply();
-    if (!retmsg.CompareNoCase(_T("550 No members found.")))
-        return true;
+	CString retmsg = GetReply();
+	if (!retmsg.CompareNoCase(_T("550 No members found.")))
+		return true;
 
-    if (!retmsg.CompareNoCase(_T("550 No data sets found.")))
-        return true;
+	if (!retmsg.CompareNoCase(_T("550 No data sets found.")))
+		return true;
 
-    if (!retmsg.CompareNoCase(_T("550 No files found.")))
-        return true;
+	if (!retmsg.CompareNoCase(_T("550 No files found.")))
+		return true;
 
-    return false;
+	return false;
 }

+ 334 - 334
filezilla/MainThread.cpp

@@ -44,490 +44,490 @@ static char THIS_FILE[] = __FILE__;
 
 CMainThread::CMainThread()
 {
-    m_hOwnerWnd = 0;
-    m_pControlSocket = NULL;
-    m_pFtpControlSocket = NULL;
+	m_hOwnerWnd = 0;
+	m_pControlSocket = NULL;
+	m_pFtpControlSocket = NULL;
 #ifndef MPEXT_NO_SFTP
-    m_pSFtpControlSocket = NULL;
+	m_pSFtpControlSocket = NULL;
 #endif
-    m_bBusy = FALSE;
-    m_bConnected = FALSE;
+	m_bBusy = FALSE;
+	m_bConnected = FALSE;
 #ifndef MPEXT_NO_CACHE
-    m_pDirectoryCache = 0;
+	m_pDirectoryCache = 0;
 #endif
-    m_pWorkingDir = 0;
-    m_nAsyncRequestID = 0;
-    m_bQuit = FALSE;
+	m_pWorkingDir = 0;
+	m_nAsyncRequestID = 0;
+	m_bQuit = FALSE;
 #ifndef MPEXT_NO_IDENT
-    m_pIdentServer = 0;
+	m_pIdentServer = 0;
 #endif
-    m_hThread = 0;
-    m_dwThreadId = 0;
+	m_hThread = 0;
+	m_dwThreadId = 0;
 }
 
 CMainThread::~CMainThread()
 {
-    delete m_pWorkingDir;
-    CloseHandle(m_hThread);
+	delete m_pWorkingDir;
+	CloseHandle(m_hThread);
 }
 
 BOOL CMainThread::InitInstance()
-{
-    m_nTimerID=SetTimer(0,1,1000,0);
+{	
+	m_nTimerID=SetTimer(0,1,1000,0);
 #ifndef MPEXT_NO_CACHE
-    m_pDirectoryCache=new CDirectoryCache;
+	m_pDirectoryCache=new CDirectoryCache;					
 #endif
-    m_pPostKeepAliveCommand=0;
-
-    // initialize Winsock library
-    BOOL res=TRUE;
-    WSADATA wsaData;
-
-    WORD wVersionRequested = MAKEWORD(1, 1);
-    int nResult = WSAStartup(wVersionRequested, &wsaData);
-    if (nResult != 0)
-        res=FALSE;
-    else if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
-    {
-        WSACleanup();
-        res=FALSE;
-    }
-
-    m_pFtpControlSocket=new CFtpControlSocket(this);
+	m_pPostKeepAliveCommand=0;
+	
+	// initialize Winsock library
+	BOOL res=TRUE;
+	WSADATA wsaData;
+	
+	WORD wVersionRequested = MAKEWORD(1, 1);
+	int nResult = WSAStartup(wVersionRequested, &wsaData);
+	if (nResult != 0)
+		res=FALSE;
+	else if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
+	{
+		WSACleanup();
+		res=FALSE;
+	}
+	
+	m_pFtpControlSocket=new CFtpControlSocket(this);
 #ifndef MPEXT_NO_SFTP
-    m_pSFtpControlSocket=new CSFtpControlSocket(this);
+	m_pSFtpControlSocket=new CSFtpControlSocket(this);
 #endif
-    m_pControlSocket=m_pFtpControlSocket;
-    m_pFtpControlSocket->InitLog(this);
+	m_pControlSocket=m_pFtpControlSocket;
+	m_pFtpControlSocket->InitLog(this);
 #ifndef MPEXT_NO_SFTP
-    m_pSFtpControlSocket->InitLog(this);
+	m_pSFtpControlSocket->InitLog(this);
 #endif
 #ifndef MPEXT_NO_IDENT
-    if (COptions::GetOptionVal(OPTION_IDENT) && !COptions::GetOptionVal(OPTION_IDENTCONNECT))
-        m_pIdentServer=new CIdentServerControl(this);
+	if (COptions::GetOptionVal(OPTION_IDENT) && !COptions::GetOptionVal(OPTION_IDENTCONNECT))
+		m_pIdentServer=new CIdentServerControl(this);
 #endif
-    return TRUE;
+	return TRUE;
 }
 
 DWORD CMainThread::ExitInstance()
 {
-    KillTimer(0,m_nTimerID);
-    if (m_pFtpControlSocket)
-        delete m_pFtpControlSocket;
+	KillTimer(0,m_nTimerID);
+	if (m_pFtpControlSocket)
+		delete m_pFtpControlSocket;
 #ifndef MPEXT_NO_SFTP
-    if (m_pSFtpControlSocket)
-        delete m_pSFtpControlSocket;
+	if (m_pSFtpControlSocket)
+		delete m_pSFtpControlSocket;
 #endif
 #ifndef MPEXT_NO_CACHE
-    if (m_pDirectoryCache)
-        delete m_pDirectoryCache;
+	if (m_pDirectoryCache)
+		delete m_pDirectoryCache;
 #endif
 #ifndef MPEXT_NO_IDENT
-    if (m_pIdentServer)
-        delete m_pIdentServer;
+	if (m_pIdentServer)
+		delete m_pIdentServer;
 #endif
-    return 1;
+	return 1;
 }
 
 BOOL CMainThread::IsConnected()
 {
-    BOOL bConnected;
-    ECS;
-    bConnected=m_bConnected;
-    LCS;
-    return bConnected;
+	BOOL bConnected;
+	ECS;
+	bConnected=m_bConnected;
+	LCS;
+	return bConnected;
 }
 
 void CMainThread::OnTimer(WPARAM wParam, LPARAM lParam)
 {
-    if (!m_pControlSocket)
-        return;
-
-    if (wParam==m_nTimerID)
-        m_pControlSocket->OnTimer();
-
-    return;
+	if (!m_pControlSocket)
+		return;
+	
+	if (wParam==m_nTimerID)
+		m_pControlSocket->OnTimer();
+	
+	return;
 }
 
 void CMainThread::ShowStatus(CString status, int type)
 {
-    ECS;
-    if (m_bQuit)
-    {
-        LCS;
-        return;
-    }
-    LCS;
-    //Displays a message in the message log
-    t_ffam_statusmessage *pStatus = new t_ffam_statusmessage;
-    pStatus->post = TRUE;
-    pStatus->status = status;
-    pStatus->type = type;
-    if (!PostMessage(m_hOwnerWnd, m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_STATUS, 0), (LPARAM)pStatus))
-        delete pStatus;
+	ECS;
+	if (m_bQuit)
+	{
+		LCS;
+		return;
+	}
+	LCS;
+	//Displays a message in the message log
+	t_ffam_statusmessage *pStatus = new t_ffam_statusmessage;
+	pStatus->post = TRUE;
+	pStatus->status = status;
+	pStatus->type = type;
+	if (!PostMessage(m_hOwnerWnd, m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_STATUS, 0), (LPARAM)pStatus))
+		delete pStatus;
 }
 
 void CMainThread::ShowStatus(UINT nID, int type)
 {
-    ECS;
-    if (m_bQuit)
-    {
-        LCS;
-        return;
-    }
-    LCS;
-    CString str;
-    str.LoadString(nID);
-    ShowStatus(str,type);
+	ECS;
+	if (m_bQuit)
+	{
+		LCS;
+		return;
+	}
+	LCS;
+	CString str;
+	str.LoadString(nID);
+	ShowStatus(str,type);
 }
 
 BOOL CMainThread::OnThreadMessage(UINT Msg, WPARAM wParam, LPARAM lParam)
 {
-    if (Msg==m_nInternalMessageID)
-    {
-        if (wParam==FZAPI_THREADMSG_COMMAND)
-        {
-            if (m_pControlSocket && !m_pControlSocket->IsReady())
-                m_pPostKeepAliveCommand=(t_command *)lParam;
-            else
-            {
-                t_command *pCommand=(t_command *)lParam;
-                switch(pCommand->id)
-                {
-                case FZ_COMMAND_CONNECT:
-                    ASSERT(!IsConnected());
-                    SetCurrentPath(CServerPath());
+	if (Msg==m_nInternalMessageID)
+	{
+		if (wParam==FZAPI_THREADMSG_COMMAND)
+		{
+			if (m_pControlSocket && !m_pControlSocket->IsReady())
+				m_pPostKeepAliveCommand=(t_command *)lParam;
+			else
+			{
+				t_command *pCommand=(t_command *)lParam;
+				switch(pCommand->id)
+				{
+				case FZ_COMMAND_CONNECT:
+					ASSERT(!IsConnected());
+					SetCurrentPath(CServerPath());
 #ifndef MPEXT_NO_SFTP
-                    if (pCommand->server.nServerType&FZ_SERVERTYPE_SUB_FTP_SFTP)
-                        m_pControlSocket=m_pSFtpControlSocket;
-                    else
+					if (pCommand->server.nServerType&FZ_SERVERTYPE_SUB_FTP_SFTP)
+						m_pControlSocket=m_pSFtpControlSocket;
+					else
 #endif
-                        m_pControlSocket=m_pFtpControlSocket;
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->Connect(pCommand->server);
-                    break;
-                case FZ_COMMAND_LIST:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->List(FALSE, 0, pCommand->path, pCommand->param1, pCommand->param4);
-                    break;
-                case FZ_COMMAND_FILETRANSFER:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->FileTransfer(&pCommand->transferfile);
-                    break;
-                case FZ_COMMAND_CUSTOMCOMMAND:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->FtpCommand(pCommand->param1);
-                    break;
-                case FZ_COMMAND_DELETE:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->Delete(pCommand->param1, pCommand->path);
-                    break;
-                case FZ_COMMAND_REMOVEDIR:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->RemoveDir(pCommand->param1, pCommand->path);
-                    break;
-                case FZ_COMMAND_MAKEDIR:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->MakeDir(pCommand->path);
-                    break;
-                case FZ_COMMAND_RENAME:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->Rename(pCommand->param1, pCommand->param2, pCommand->path, pCommand->newPath);
-                    break;
-                case FZ_COMMAND_CHMOD:
-                    ASSERT(m_pControlSocket);
-                    m_pControlSocket->Chmod(pCommand->param1, pCommand->path, pCommand->param4);
-                    break;
-                }
-                delete pCommand;
-            }
-        }
-        else if (wParam==FZAPI_THREADMSG_PROCESSREPLY)
-            m_pControlSocket->ProcessReply();
-        else if (wParam==FZAPI_THREADMSG_TRANSFEREND)
-            m_pControlSocket->TransferEnd(lParam);
-        else if (wParam==FZAPI_THREADMSG_CANCEL)
-            m_pControlSocket->Cancel(lParam);
-        else if (wParam==FZAPI_THREADMSG_DISCONNECT)
-            m_pControlSocket->Disconnect();
-        else if (wParam==FZAPI_THREADMSG_POSTKEEPALIVE)
-        {
-            if (m_pPostKeepAliveCommand)
-            {
-                PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,(LPARAM)m_pPostKeepAliveCommand);
-                m_pPostKeepAliveCommand=0;
-            }
-        }
-        else if (wParam==FZAPI_THREADMSG_ASYNCREQUESTREPLY)
-        {
-            CAsyncRequestData *pData=(CAsyncRequestData *)lParam;
-            if (pData)
-            {
-                if (pData->nRequestID!=GetAsyncRequestID())
-                    LogMessage(__FILE__, __LINE__, this,FZ_LOG_INFO, _T("Ignoring old request ID"));
-                else
-                    m_pControlSocket->SetAsyncRequestResult(pData->nRequestResult, pData);
-                delete pData;
-            }
-            else
-                LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Request reply without data"));
-        }
-        return TRUE;
-    }
-    else if (Msg==WM_TIMER)
-    {
-        OnTimer(wParam, lParam);
-    }
-
-    return TRUE;
+						m_pControlSocket=m_pFtpControlSocket;
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->Connect(pCommand->server);
+					break;
+				case FZ_COMMAND_LIST:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->List(FALSE, 0, pCommand->path, pCommand->param1, pCommand->param4);
+					break;
+				case FZ_COMMAND_FILETRANSFER:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->FileTransfer(&pCommand->transferfile);
+					break;
+				case FZ_COMMAND_CUSTOMCOMMAND:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->FtpCommand(pCommand->param1);
+					break;
+				case FZ_COMMAND_DELETE:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->Delete(pCommand->param1, pCommand->path);
+					break;
+				case FZ_COMMAND_REMOVEDIR:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->RemoveDir(pCommand->param1, pCommand->path);
+					break;
+				case FZ_COMMAND_MAKEDIR:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->MakeDir(pCommand->path);
+					break;
+				case FZ_COMMAND_RENAME:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->Rename(pCommand->param1, pCommand->param2, pCommand->path, pCommand->newPath);
+					break;
+				case FZ_COMMAND_CHMOD:
+					ASSERT(m_pControlSocket);
+					m_pControlSocket->Chmod(pCommand->param1, pCommand->path, pCommand->param4);
+					break;
+				}
+				delete pCommand;
+			}
+		}
+		else if (wParam==FZAPI_THREADMSG_PROCESSREPLY)
+			m_pControlSocket->ProcessReply();
+		else if (wParam==FZAPI_THREADMSG_TRANSFEREND)
+			m_pControlSocket->TransferEnd(lParam);
+		else if (wParam==FZAPI_THREADMSG_CANCEL)
+			m_pControlSocket->Cancel(lParam);
+		else if (wParam==FZAPI_THREADMSG_DISCONNECT)
+			m_pControlSocket->Disconnect();
+		else if (wParam==FZAPI_THREADMSG_POSTKEEPALIVE)
+		{
+			if (m_pPostKeepAliveCommand)
+			{
+				PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,(LPARAM)m_pPostKeepAliveCommand);
+				m_pPostKeepAliveCommand=0;
+			}
+		}
+		else if (wParam==FZAPI_THREADMSG_ASYNCREQUESTREPLY)
+		{
+			CAsyncRequestData *pData=(CAsyncRequestData *)lParam;
+			if (pData)
+			{
+				if (pData->nRequestID!=GetAsyncRequestID())
+					LogMessage(__FILE__, __LINE__, this,FZ_LOG_INFO, _T("Ignoring old request ID"));
+				else
+					m_pControlSocket->SetAsyncRequestResult(pData->nRequestResult, pData);
+				delete pData;
+			}
+			else
+				LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Request reply without data"));
+		}
+		return TRUE;
+	}
+	else if (Msg==WM_TIMER)
+	{
+		OnTimer(wParam, lParam);
+	}
+	
+	return TRUE;
 }
 
 BOOL CMainThread::IsBusy()
 {
-    BOOL bBusy;
-    ECS;
-    bBusy=m_bBusy;
-    LCS;
-    return bBusy;
+	BOOL bBusy;
+	ECS;
+	bBusy=m_bBusy;
+	LCS;
+	return bBusy;
 }
 
 void CMainThread::Command(const t_command &command)
 {
-    ASSERT(!IsBusy());
-    ECS;
-    if (m_bQuit)
-    {
-        LCS;
-        return;
-    }
-    m_bBusy=TRUE;
-    t_command *pCommand=new t_command;
-    *pCommand=command;
-    VERIFY(PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,(LPARAM)pCommand));
-    m_LastCommand=command;
-    LCS;
+	ASSERT(!IsBusy());
+	ECS;
+	if (m_bQuit)
+	{
+		LCS;
+		return;
+	}
+	m_bBusy=TRUE;
+	t_command *pCommand=new t_command;
+	*pCommand=command;
+	VERIFY(PostThreadMessage(m_nInternalMessageID,FZAPI_THREADMSG_COMMAND,(LPARAM)pCommand));
+	m_LastCommand=command;
+	LCS;	
 }
 
 BOOL CMainThread::LastOperationSuccessful()
 {
-    return TRUE;
+	return TRUE;
 }
 
 void CMainThread::SetBusy(BOOL bBusy)
 {
-    ECS;
-    m_bBusy=bBusy;
-    LCS;
+	ECS;
+	m_bBusy=bBusy;
+	LCS;
 }
 
 void CMainThread::SetConnected(BOOL bConnected /*=TRUE*/)
 {
-    ECS;
-    m_bConnected=bConnected;
-    LCS;
+	ECS;
+	m_bConnected=bConnected;
+	LCS;
 }
 
 bool CMainThread::GetCurrentPath(CServerPath &dir)
 {
-    if (!IsConnected())
-        return false;
-    ECS;
-    dir=m_CurrentPath;
-    LCS;
-    return true;
+	if (!IsConnected())
+		return false;
+	ECS;
+	dir=m_CurrentPath;
+	LCS;
+	return true;
 }
 
 CServerPath CMainThread::GetCurrentPath()
 {
-    CServerPath path;
-    bool res = GetCurrentPath(path);
-    if (!res)
-        return CServerPath();
-
-    return path;
+	CServerPath path;
+	bool res = GetCurrentPath(path);
+	if (!res)
+		return CServerPath();
+	
+	return path;
 }
 
 BOOL CMainThread::GetCurrentServer(t_server &server)
 {
-    if (!IsConnected())
-        return FALSE;
-    ECS;
-    server=m_pControlSocket->GetCurrentServer();
-    LCS;
-    return TRUE;
+	if (!IsConnected())
+		return FALSE;
+	ECS;
+	server=m_pControlSocket->GetCurrentServer();
+	LCS;
+	return TRUE;
 }
 
 void CMainThread::Quit()
 {
-    ECS;
-    m_bQuit=TRUE;
-    LCS;
-    if (IsBusy())
-        PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_CANCEL, 1);
-    PostThreadMessage(WM_QUIT, 0, 0);
+	ECS;
+	m_bQuit=TRUE;
+	LCS;
+	if (IsBusy())
+		PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_CANCEL, 1);
+	PostThreadMessage(WM_QUIT, 0, 0);
 }
 
 void CMainThread::SetCurrentPath(CServerPath path)
 {
-    ECS;
-    m_CurrentPath=path;
-    LCS;
-    return;
+	ECS;
+	m_CurrentPath=path;
+	LCS;
+	return;
 }
 
 #ifndef MPEXT
 int CMainThread::GetOption(int nOption)
 {
-    int nValue=0;
-    ECS;
-    std::map<int, int>::iterator iter=m_Options.find(nOption);
-    if (iter!=m_Options.end())
-        nValue=iter->second;
-    LCS;
-    return nValue;
+	int nValue=0;
+	ECS;
+	std::map<int, int>::iterator iter=m_Options.find(nOption);
+	if (iter!=m_Options.end())
+		nValue=iter->second;
+	LCS;
+	return nValue;
 }
 
 void CMainThread::SetOption(int nOption, int nValue)
 {
-    ECS;
-    m_Options[nOption]=nValue;
-    LCS;
+	ECS;
+	m_Options[nOption]=nValue;
+	LCS;
 }
 #endif
 
 BOOL CMainThread::GetWorkingDir(t_directory *pWorkingDir)
 {
-    ECS;
-    if (m_pWorkingDir)
-    {
-        *pWorkingDir=*m_pWorkingDir;
-        LCS;
-        return TRUE;
-    }
-    LCS;
-    return FALSE;
+	ECS;
+	if (m_pWorkingDir)
+	{
+		*pWorkingDir=*m_pWorkingDir;
+		LCS;
+		return TRUE;
+	}
+	LCS;
+	return FALSE;
 }
 
 void CMainThread::SetWorkingDir(t_directory *pWorkingDir)
 {
-    if (!pWorkingDir)
-    {
-        ECS;
-        delete m_pWorkingDir;
-        m_pWorkingDir=0;
-        LCS;
-    }
-    else
-    {
-        ECS;
-        if (!m_pWorkingDir)
-            m_pWorkingDir=new t_directory;
-        *m_pWorkingDir=*pWorkingDir;
-        LCS;
-    }
-    if (pWorkingDir)
-    {
-        t_directory *pDirectoryToSend=new t_directory;
-        *pDirectoryToSend=*pWorkingDir;
-        PostMessage(m_hOwnerWnd, m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_LISTDATA, 0), (LPARAM)pDirectoryToSend);
-    }
-
-    return;
+	if (!pWorkingDir)
+	{
+		ECS;
+		delete m_pWorkingDir;
+		m_pWorkingDir=0;
+		LCS;
+	}
+	else
+	{
+		ECS;
+		if (!m_pWorkingDir)
+			m_pWorkingDir=new t_directory;
+		*m_pWorkingDir=*pWorkingDir;
+		LCS;
+	}
+	if (pWorkingDir)
+	{
+		t_directory *pDirectoryToSend=new t_directory;
+		*pDirectoryToSend=*pWorkingDir;
+		PostMessage(m_hOwnerWnd, m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_LISTDATA, 0), (LPARAM)pDirectoryToSend);
+	}
+
+	return;
 }
 
 bool CMainThread::GetWorkingDirPath(CServerPath &path)
 {
-    ECS;
-    if (m_pWorkingDir)
-    {
-        path = m_pWorkingDir->path;
-        LCS;
-        return true;
-    }
-    LCS;
-
-    return false;
+	ECS;
+	if (m_pWorkingDir)
+	{
+		path = m_pWorkingDir->path;
+		LCS;
+		return true;
+	}
+	LCS;
+
+	return false;
 }
 
 __int64 CMainThread::GetAsyncRequestID() const
 {
-    return m_nAsyncRequestID;
+	return m_nAsyncRequestID;
 }
 
 __int64 CMainThread::GetNextAsyncRequestID()
 {
-    return ++m_nAsyncRequestID;
+	return ++m_nAsyncRequestID;
 }
 
 CMainThread* CMainThread::Create(int nPriority /*=THREAD_PRIORITY_NORMAL*/, DWORD dwCreateFlags /*=0*/)
 {
-    CMainThread *pMainThread=new CMainThread();
-    pMainThread->m_hThread=CreateThread(0, 0, ThreadProc, pMainThread, dwCreateFlags, &pMainThread->m_dwThreadId);
-    if (!pMainThread->m_hThread)
-    {
-        delete pMainThread;
-        return NULL;
-    }
-    ::SetThreadPriority(pMainThread->m_hThread, nPriority);
-    return pMainThread;
+	CMainThread *pMainThread=new CMainThread();
+	pMainThread->m_hThread=CreateThread(0, 0, ThreadProc, pMainThread, dwCreateFlags, &pMainThread->m_dwThreadId);
+	if (!pMainThread->m_hThread)
+	{
+		delete pMainThread;
+		return NULL;
+	}
+	::SetThreadPriority(pMainThread->m_hThread, nPriority);
+	return pMainThread;
 }
 
 BOOL CMainThread::PostThreadMessage(UINT message, WPARAM wParam, LPARAM lParam)
 {
-    return ::PostThreadMessage(m_dwThreadId, message, wParam, lParam);
+	return ::PostThreadMessage(m_dwThreadId, message, wParam, lParam);
 }
 
 DWORD CMainThread::ResumeThread()
 {
-    BOOL res=::ResumeThread(m_hThread);
-    if (res)
-    {
-        m_EventStarted.Lock();
-        m_EventStarted.Unlock();
-    }
-    return res;
+	BOOL res=::ResumeThread(m_hThread);
+	if (res)
+	{
+		m_EventStarted.Lock();
+		m_EventStarted.Unlock();
+	}
+	return res;
 }
 
 DWORD WINAPI CMainThread::ThreadProc(LPVOID lpParameter)
 {
-    return ((CMainThread *)lpParameter)->Run();
+	return ((CMainThread *)lpParameter)->Run();
 }
 
 DWORD CMainThread::Run()
 {
-    ECS;
-    InitInstance();
-    m_EventStarted.SetEvent();
-    LCS;
-    MSG msg;
-    while (GetMessage(&msg, 0, 0, 0))
-    {
-        TranslateMessage(&msg);
-        if (!msg.hwnd)
-            OnThreadMessage(msg.message, msg.wParam, msg.lParam);
-        DispatchMessage(&msg);
-    }
-    DWORD res = ExitInstance();
-    delete this;
-    return res;
+	ECS;
+	InitInstance();
+	m_EventStarted.SetEvent();
+	LCS;
+	MSG msg;
+	while (GetMessage(&msg, 0, 0, 0))
+	{
+		TranslateMessage(&msg);
+		if (!msg.hwnd)
+			OnThreadMessage(msg.message, msg.wParam, msg.lParam);
+		DispatchMessage(&msg);
+	}
+	DWORD res = ExitInstance();
+	delete this;
+	return res;
 }
 
 BOOL CMainThread::IsValid() const
 {
-    if (!this)
-        return FALSE;
+	if (!this)
+		return FALSE;
 
-    if (IsBadWritePtr((VOID *)this, sizeof(CMainThread)) )
-        return FALSE;
+	if (IsBadWritePtr((VOID *)this, sizeof(CMainThread)) )
+		return FALSE;
 
-    if (m_pControlSocket &&
-        m_pControlSocket != m_pFtpControlSocket
+	if (m_pControlSocket &&
+		m_pControlSocket != m_pFtpControlSocket
 #ifndef MPEXT_NO_SFTP
-        &&
-        m_pControlSocket != m_pSFtpControlSocket
+		&&
+		m_pControlSocket != m_pSFtpControlSocket
 #endif
-        )
-        return FALSE;
+		)
+		return FALSE;
 
-    return TRUE;
+	return TRUE;
 }

+ 9 - 1
filezilla/Options.cpp

@@ -13,7 +13,15 @@ CString COptions::GetInstanceOption(CApiLog * Instance, int OptionID)
 
   const TFileZillaIntf * Intf = Intern->GetOwner();
   ASSERT(Intf != NULL);
-  return Intf->Option(OptionID);
+  CString Result = Intf->Option(OptionID);
+  switch (OptionID)
+  {
+    case OPTION_PROXYPASS:
+    case OPTION_FWPASS:
+      Result = CCrypt::encrypt(Result);
+      break;
+  }
+  return Result;
 }
 //---------------------------------------------------------------------------
 int COptions::GetInstanceOptionVal(CApiLog * Instance, int OptionID)

+ 1268 - 1268
filezilla/TransferSocket.cpp

@@ -38,1412 +38,1412 @@ static char THIS_FILE[] = __FILE__;
 
 #define BUFSIZE 16384
 
-#define STATE_WAITING       0
-#define STATE_STARTING      1
-#define STATE_STARTED       2
+#define STATE_WAITING		0
+#define STATE_STARTING		1
+#define STATE_STARTED		2
 
 /////////////////////////////////////////////////////////////////////////////
 // CTransferSocket
 
 CTransferSocket::CTransferSocket(CFtpControlSocket *pOwner, int nMode)
 {
-    ASSERT(pOwner);
-    InitLog(pOwner);
-    m_pOwner = pOwner;
-    m_nMode = nMode;
-    m_nTransferState = STATE_WAITING;
-    m_bCheckTimeout = FALSE;
-    m_pBuffer = 0;
+	ASSERT(pOwner);
+	InitLog(pOwner);
+	m_pOwner = pOwner;
+	m_nMode = nMode;
+	m_nTransferState = STATE_WAITING;
+	m_bCheckTimeout = FALSE;
+	m_pBuffer = 0;
 #ifndef MPEXT_NO_ZLIB
-    m_pBuffer2 = 0;
+	m_pBuffer2 = 0;
 #endif
-    m_bufferpos = 0;
-    m_ReadPos = 0;
-    m_ReadBuffer = 0;
-    m_ReadSize = 0;
-    m_cLastChar = 0;
-    m_pFile = 0;
-    m_bListening = FALSE;
-    m_bSentClose = FALSE;
-    m_nInternalMessageID = 0;
-    m_transferdata.transfersize = 0;
-    m_transferdata.transferleft = 0;
-    m_transferdata.nTransferStart = 0;
-    m_nNotifyWaiting = 0;
-    m_bShutDown = FALSE;
-
-    UpdateStatusBar(true);
-
-    for (int i = 0; i < SPEED_SECONDS; i++)
-    {
-        m_Transfered[i] = 0;
-        m_UsedForTransfer[i] = 0;
-    }
-
-    m_pProxyLayer = NULL;
+	m_bufferpos = 0;
+	m_ReadPos = 0;
+	m_ReadBuffer = 0;
+	m_ReadSize = 0;
+	m_cLastChar = 0;
+	m_pFile = 0;
+	m_bListening = FALSE;
+	m_bSentClose = FALSE;
+	m_nInternalMessageID = 0;
+	m_transferdata.transfersize = 0;
+	m_transferdata.transferleft = 0;
+	m_transferdata.nTransferStart = 0;
+	m_nNotifyWaiting = 0;
+	m_bShutDown = FALSE;
+
+	UpdateStatusBar(true);
+	
+	for (int i = 0; i < SPEED_SECONDS; i++)
+	{
+		m_Transfered[i] = 0;
+		m_UsedForTransfer[i] = 0;
+	}
+
+	m_pProxyLayer = NULL;
 #ifndef MPEXT_NO_SSL
-    m_pSslLayer = NULL;
+	m_pSslLayer = NULL;
 #endif
 #ifndef MPEXT_NO_GSS
-    m_pGssLayer = NULL;
+	m_pGssLayer = NULL;
 #endif
 
-    if (m_nMode & CSMODE_LIST)
-    {
-        m_pListResult = new CFtpListResult(pOwner->m_CurrentServer, &pOwner->m_bUTF8);
-        m_pListResult->InitLog(this);
-    }
-    else
-        m_pListResult = 0;
-    m_LastUpdateTime.QuadPart = 0;
+	if (m_nMode & CSMODE_LIST)
+	{
+		m_pListResult = new CFtpListResult(pOwner->m_CurrentServer, &pOwner->m_bUTF8);
+		m_pListResult->InitLog(this);
+	}
+	else
+		m_pListResult = 0;
+	m_LastUpdateTime.QuadPart = 0;
 
 #ifndef MPEXT_NO_ZLIB
-    memset(&m_zlibStream, 0, sizeof(m_zlibStream));
-    m_useZlib = false;
+	memset(&m_zlibStream, 0, sizeof(m_zlibStream));
+	m_useZlib = false;
 #endif
 }
 
 CTransferSocket::~CTransferSocket()
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("~CTransferSocket()"));
-    delete [] m_pBuffer;
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("~CTransferSocket()"));
+	delete [] m_pBuffer;
 #ifndef MPEXT_NO_ZLIB
-    delete [] m_pBuffer2;
+	delete [] m_pBuffer2;
 #endif
-    if (m_ReadBuffer)
-    {
-        delete [] m_ReadBuffer;
-        m_ReadBuffer = 0;
-    }
-    PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), 0);
-    Close();
-    RemoveAllLayers();
-    delete m_pProxyLayer;
+	if (m_ReadBuffer)
+	{
+		delete [] m_ReadBuffer;
+		m_ReadBuffer = 0;
+	}
+	PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), 0);
+	Close();
+	RemoveAllLayers();
+	delete m_pProxyLayer;
 #ifndef MPEXT_NO_SSL
-    delete m_pSslLayer;
+	delete m_pSslLayer;
 #endif
 #ifndef MPEXT_NO_GSS
-    delete m_pGssLayer;
+	delete m_pGssLayer;
 #endif
-    m_pOwner->RemoveActiveTransfer();
+	m_pOwner->RemoveActiveTransfer();
 
-    delete m_pListResult;
+	delete m_pListResult;
 
 #ifndef MPEXT_NO_ZLIB
-    if (m_useZlib)
-    {
-        if (m_nMode & CSMODE_UPLOAD)
-            deflateEnd(&m_zlibStream);
-        else
-            inflateEnd(&m_zlibStream);
-    }
+	if (m_useZlib)
+	{
+		if (m_nMode & CSMODE_UPLOAD)
+			deflateEnd(&m_zlibStream);
+		else
+			inflateEnd(&m_zlibStream);
+	}
 #endif
 }
 
 /////////////////////////////////////////////////////////////////////////////
-// Member-Funktion CTransferSocket
-void CTransferSocket::OnReceive(int nErrorCode)
+// Member-Funktion CTransferSocket 
+void CTransferSocket::OnReceive(int nErrorCode) 
 {
-    if (GetState() != connected && GetState() != attached && GetState() != closed)
-        return;
-    if (m_nTransferState == STATE_WAITING)
-    {
-        m_nNotifyWaiting |= FD_READ;
-        return;
-    }
-
-    if (m_bSentClose)
-        return;
-    if (m_bListening)
-        return;
-
-    if (m_nMode&CSMODE_LIST)
-    {
-        if (m_nTransferState == STATE_STARTING)
-            OnConnect(0);
-
-        char *buffer = new char[BUFSIZE];
-        int numread = CAsyncSocketEx::Receive(buffer, BUFSIZE);
-        if (numread != SOCKET_ERROR && numread)
-        {
-            m_LastActiveTime = CTime::GetCurrentTime();
-            UpdateRecvLed();
+	if (GetState() != connected && GetState() != attached && GetState() != closed)
+		return;
+	if (m_nTransferState == STATE_WAITING)
+	{
+		m_nNotifyWaiting |= FD_READ;
+		return;
+	}
+
+	if (m_bSentClose)
+		return;
+	if (m_bListening)
+		return;
+
+	if (m_nMode&CSMODE_LIST)
+	{
+		if (m_nTransferState == STATE_STARTING)
+			OnConnect(0);
+		
+		char *buffer = new char[BUFSIZE];
+		int numread = CAsyncSocketEx::Receive(buffer, BUFSIZE);
+		if (numread != SOCKET_ERROR && numread)
+		{
+			m_LastActiveTime = CTime::GetCurrentTime();
+			UpdateRecvLed();
 
 #ifndef MPEXT_NO_ZLIB
-            if (m_useZlib)
-            {
-                m_zlibStream.next_in = (Bytef *)buffer;
-                m_zlibStream.avail_in = numread;
-                char *out = new char[BUFSIZE];
-                m_zlibStream.next_out = (Bytef *)out;
-                m_zlibStream.avail_out = BUFSIZE;
-                int res = inflate(&m_zlibStream, 0);
-                while (res == Z_OK)
-                {
-                    m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
-                    out = new char[BUFSIZE];
-                    m_zlibStream.next_out = (Bytef *)out;
-                    m_zlibStream.avail_out = BUFSIZE;
-                    res = inflate(&m_zlibStream, 0);
-                }
-                delete [] buffer;
-                if (res == Z_STREAM_END)
-                    m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
-                else if (res != Z_OK && res != Z_BUF_ERROR)
-                {
-                    delete [] out;
-                    Close();
-                    if (!m_bSentClose)
-                    {
-                        m_nMode |= CSMODE_TRANSFERERROR;
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                    return;
-                }
-                else
-                    delete [] out;
-            }
-            else
+			if (m_useZlib)
+			{
+				m_zlibStream.next_in = (Bytef *)buffer;
+				m_zlibStream.avail_in = numread;
+				char *out = new char[BUFSIZE];
+				m_zlibStream.next_out = (Bytef *)out;
+				m_zlibStream.avail_out = BUFSIZE;
+				int res = inflate(&m_zlibStream, 0);
+				while (res == Z_OK)
+				{
+					m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
+					out = new char[BUFSIZE];
+					m_zlibStream.next_out = (Bytef *)out;
+					m_zlibStream.avail_out = BUFSIZE;
+					res = inflate(&m_zlibStream, 0);
+				}
+				delete [] buffer;
+				if (res == Z_STREAM_END)
+					m_pListResult->AddData(out, BUFSIZE - m_zlibStream.avail_out);
+				else if (res != Z_OK && res != Z_BUF_ERROR)
+				{
+					delete [] out;
+					Close();
+					if (!m_bSentClose)
+					{
+						m_nMode |= CSMODE_TRANSFERERROR;
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+					return;
+				}
+				else
+					delete [] out;
+			}
+			else
 #endif
-                m_pListResult->AddData(buffer, numread);
-            m_transferdata.transfersize += numread;
-            CTimeSpan timespan = CTime::GetCurrentTime() - m_StartTime;
-            int elapsed = (int)timespan.GetTotalSeconds();
-            //TODO
-            //There are servers which report the total number of
-            //bytes in the list response message, but yet it is not supported by FZ.
-            /*double leftmodifier=(transfersize-transferstart-transferleft);
-            leftmodifier*=100;
-            leftmodifier/=(transfersize-transferstart);
-            if (leftmodifier==0)
-                leftmodifier=1;
-            double leftmodifier2=100-leftmodifier;
-            int left=(int)((elapsed/leftmodifier)*leftmodifier2);
-            int percent=MulDiv(100,transfersize-transferleft,transfersize);*/
-            int transferrate=static_cast<int>( (elapsed && m_transferdata.transfersize)?m_transferdata.transfersize/elapsed:0 );
-            t_ffam_transferstatus *status = new t_ffam_transferstatus;
-            status->bFileTransfer = FALSE;
+				m_pListResult->AddData(buffer, numread);
+			m_transferdata.transfersize += numread;
+			CTimeSpan timespan = CTime::GetCurrentTime() - m_StartTime;
+			int elapsed = (int)timespan.GetTotalSeconds();
+			//TODO
+			//There are servers which report the total number of 
+			//bytes in the list response message, but yet it is not supported by FZ.
+			/*double leftmodifier=(transfersize-transferstart-transferleft); 
+			leftmodifier*=100;
+			leftmodifier/=(transfersize-transferstart);
+			if (leftmodifier==0)
+				leftmodifier=1;
+			double leftmodifier2=100-leftmodifier;
+			int left=(int)((elapsed/leftmodifier)*leftmodifier2);
+			int percent=MulDiv(100,transfersize-transferleft,transfersize);*/
+			int transferrate=static_cast<int>( (elapsed && m_transferdata.transfersize)?m_transferdata.transfersize/elapsed:0 );
+			t_ffam_transferstatus *status = new t_ffam_transferstatus;
+			status->bFileTransfer = FALSE;
 #ifdef MPEXT
-            status->transfersize = -1;
+			status->transfersize = -1;
 #endif
-            status->bytes = m_transferdata.transfersize;
-            status->percent = -1;
-            status->timeelapsed = elapsed;
-            status->timeleft = -1;
-            status->transferrate = transferrate;
-            PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
-        }
-        else
-            delete [] buffer;
-        if (!numread)
-        {
-            Close();
-            if (!m_bSentClose)
-            {
-                m_bSentClose = TRUE;
-                m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-            }
-        }
-        if (numread == SOCKET_ERROR)
-        {
-            int nError = GetLastError();
-            if (nError == WSAENOTCONN)
-            {
-                //Not yet connected
-                return;
-            }
+			status->bytes = m_transferdata.transfersize;
+			status->percent = -1;
+			status->timeelapsed = elapsed;
+			status->timeleft = -1;
+			status->transferrate = transferrate;
+			PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
+		}
+		else
+			delete [] buffer;
+		if (!numread)
+		{
+			Close();
+			if (!m_bSentClose)
+			{
+				m_bSentClose = TRUE;
+				m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+			}
+		}
+		if (numread == SOCKET_ERROR)
+		{
+			int nError = GetLastError();
+			if (nError == WSAENOTCONN)
+			{
+				//Not yet connected
+				return;
+			}
 #ifndef MPEXT_NO_SSL
-            else if (m_pSslLayer && nError == WSAESHUTDOWN)
-            {
-                // Do nothing, wait for shutdown complete notification.
-                return;
-            }
+			else if (m_pSslLayer && nError == WSAESHUTDOWN)
+			{
+				// Do nothing, wait for shutdown complete notification.
+				return;
+			}
 #endif
-            else if (nError != WSAEWOULDBLOCK)
-            {
-                Close();
-                if (!m_bSentClose)
-                {
-                    m_nMode |= CSMODE_TRANSFERERROR;
-                    m_bSentClose = TRUE;
-                    m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                }
-            }
-        }
-    }
-    else if (m_nMode & CSMODE_DOWNLOAD)
-    {
-        if (m_nTransferState == STATE_STARTING)
-            OnConnect(0);
-
-        bool beenWaiting = false;
-        _int64 ableToRead;
-        if (GetState() != closed)
-            ableToRead = m_pOwner->GetAbleToTransferSize(CControlSocket::download, beenWaiting);
-        else
-            ableToRead = BUFSIZE;
-
-        if (!beenWaiting)
-            ASSERT(ableToRead);
-        else if (!ableToRead)
-        {
-            TriggerEvent(FD_READ);
-            return;
-        }
-
-        if (!m_pBuffer)
-            m_pBuffer = new char[BUFSIZE];
-
-        int numread = CAsyncSocketEx::Receive(m_pBuffer, static_cast<int>(ableToRead));
-        if (numread!=SOCKET_ERROR)
-        {
-            Transfered( numread, CTime::GetCurrentTime());
-            m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::download, numread);
-        }
-
-        if (!numread)
-        {
-            Close();
-            if (!m_bSentClose)
-            {
-                m_bSentClose = TRUE;
-                m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-            }
-            return;
-        }
-
-        if (numread == SOCKET_ERROR)
-        {
-            int nError = GetLastError();
-            if (nError == WSAENOTCONN)
-            {
-                //Not yet connected
-                return;
-            }
+			else if (nError != WSAEWOULDBLOCK)
+			{
+				Close();
+				if (!m_bSentClose)
+				{
+					m_nMode |= CSMODE_TRANSFERERROR;
+					m_bSentClose = TRUE;
+					m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+				}
+			}
+		}
+	}
+	else if (m_nMode & CSMODE_DOWNLOAD)
+	{
+		if (m_nTransferState == STATE_STARTING)
+			OnConnect(0);
+		
+		bool beenWaiting = false;
+		_int64 ableToRead;
+		if (GetState() != closed)
+			ableToRead = m_pOwner->GetAbleToTransferSize(CControlSocket::download, beenWaiting);
+		else
+			ableToRead = BUFSIZE;
+
+		if (!beenWaiting)
+			ASSERT(ableToRead);
+		else if (!ableToRead)
+		{
+			TriggerEvent(FD_READ);
+			return;
+		}
+
+		if (!m_pBuffer)
+			m_pBuffer = new char[BUFSIZE];
+
+		int numread = CAsyncSocketEx::Receive(m_pBuffer, static_cast<int>(ableToRead));
+		if (numread!=SOCKET_ERROR)
+		{
+			Transfered( numread, CTime::GetCurrentTime());
+			m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::download, numread);
+		}
+
+		if (!numread)
+		{
+			Close();
+			if (!m_bSentClose)
+			{
+				m_bSentClose = TRUE;
+				m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+			}
+			return;
+		}
+		
+		if (numread == SOCKET_ERROR)
+		{
+			int nError = GetLastError();
+			if (nError == WSAENOTCONN)
+			{
+				//Not yet connected
+				return;
+			}
 #ifndef MPEXT_NO_SSL
-            else if (m_pSslLayer && nError == WSAESHUTDOWN)
-            {
-                // Do nothing, wait for shutdown complete notification.
-                return;
-            }
+			else if (m_pSslLayer && nError == WSAESHUTDOWN)
+			{
+				// Do nothing, wait for shutdown complete notification.
+				return;
+			}
 #endif
-            else if (nError != WSAEWOULDBLOCK)
-            {
-                Close();
-                if (!m_bSentClose)
-                {
-                    m_nMode |= CSMODE_TRANSFERERROR;
-                    m_bSentClose = TRUE;
-                    m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                }
-            }
-
-            UpdateStatusBar(false);
-            return;
-        }
-
-        int written = 0;
-        m_LastActiveTime = CTime::GetCurrentTime();
-        UpdateRecvLed();
-        TRY
-        {
+			else if (nError != WSAEWOULDBLOCK)
+			{
+				Close();
+				if (!m_bSentClose)
+				{
+					m_nMode |= CSMODE_TRANSFERERROR;
+					m_bSentClose = TRUE;
+					m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+				}
+			}
+
+			UpdateStatusBar(false);
+			return;
+		}
+		
+		int written = 0;
+		m_LastActiveTime = CTime::GetCurrentTime();
+		UpdateRecvLed();
+		TRY
+		{
 #ifndef MPEXT_NO_ZLIB
-            if (m_useZlib)
-            {
-                if (!m_pBuffer2)
-                    m_pBuffer2 = new char[BUFSIZE];
-
-                m_zlibStream.next_in = (Bytef *)m_pBuffer;
-                m_zlibStream.avail_in = numread;
-                m_zlibStream.next_out = (Bytef *)m_pBuffer2;
-                m_zlibStream.avail_out = BUFSIZE;
-                int res = inflate(&m_zlibStream, 0);
-                while (res == Z_OK)
-                {
-                    m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
-                    written += BUFSIZE - m_zlibStream.avail_out;
-                    m_zlibStream.next_out = (Bytef *)m_pBuffer2;
-                    m_zlibStream.avail_out = BUFSIZE;
-                    res = inflate(&m_zlibStream, 0);
-                }
-                if (res == Z_STREAM_END)
-                {
-                    m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
-                    written += BUFSIZE - m_zlibStream.avail_out;
-                }
-                else if (res != Z_OK && res != Z_BUF_ERROR)
-                {
-                    Close();
-                    if (!m_bSentClose)
-                    {
-                        m_nMode |= CSMODE_TRANSFERERROR;
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                    return;
-                }
-            }
-            else
+			if (m_useZlib)
+			{
+				if (!m_pBuffer2)
+					m_pBuffer2 = new char[BUFSIZE];
+					
+				m_zlibStream.next_in = (Bytef *)m_pBuffer;
+				m_zlibStream.avail_in = numread;
+				m_zlibStream.next_out = (Bytef *)m_pBuffer2;
+				m_zlibStream.avail_out = BUFSIZE;
+				int res = inflate(&m_zlibStream, 0);
+				while (res == Z_OK)
+				{
+					m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
+					written += BUFSIZE - m_zlibStream.avail_out;
+					m_zlibStream.next_out = (Bytef *)m_pBuffer2;
+					m_zlibStream.avail_out = BUFSIZE;
+					res = inflate(&m_zlibStream, 0);
+				}
+				if (res == Z_STREAM_END)
+				{
+					m_pFile->Write(m_pBuffer2, BUFSIZE - m_zlibStream.avail_out);
+					written += BUFSIZE - m_zlibStream.avail_out;
+				}
+				else if (res != Z_OK && res != Z_BUF_ERROR)
+				{
+					Close();
+					if (!m_bSentClose)
+					{
+						m_nMode |= CSMODE_TRANSFERERROR;
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+					return;
+				}
+			}
+			else
 #endif
-            {
-                m_pFile->Write(m_pBuffer, numread);
-                written = numread;
-            }
-        }
-        CATCH(CFileException,e)
-        {
-            LPTSTR msg = new TCHAR[BUFSIZE];
-            if (e->GetErrorMessage(msg, BUFSIZE))
-                m_pOwner->ShowStatus(msg, 1);
-            delete [] msg;
-            Close();
-            if (!m_bSentClose)
-            {
-                m_nMode |= CSMODE_TRANSFERERROR;
-                m_bSentClose = TRUE;
-                m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-            }
-            return;
-        }
-        END_CATCH;
-        m_transferdata.transferleft -= written;
-
-        UpdateStatusBar(false);
-    }
+			{
+				m_pFile->Write(m_pBuffer, numread);
+				written = numread;
+			}
+		}
+		CATCH(CFileException,e)
+		{
+			LPTSTR msg = new TCHAR[BUFSIZE];
+			if (e->GetErrorMessage(msg, BUFSIZE))
+				m_pOwner->ShowStatus(msg, 1);
+			delete [] msg;
+			Close();
+			if (!m_bSentClose)
+			{
+				m_nMode |= CSMODE_TRANSFERERROR;
+				m_bSentClose = TRUE;
+				m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+			}
+			return;
+		}
+		END_CATCH;
+		m_transferdata.transferleft -= written;
+
+		UpdateStatusBar(false);
+	}
 }
 
-void CTransferSocket::OnAccept(int nErrorCode)
+void CTransferSocket::OnAccept(int nErrorCode) 
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnAccept(%d)"), nErrorCode);
-    m_bListening=FALSE;
-    CAsyncSocketEx tmp;
-    Accept(tmp);
-    SOCKET socket=tmp.Detach();
-    CAsyncSocketEx::Close();
-
-    Attach(socket);
-
-    /* Set internal socket send buffer to twice the programs buffer size
-     * this should fix the speed problems some users have reported
-     */
-    DWORD value;
-    int len = sizeof(value);
-    GetSockOpt(SO_SNDBUF, &value, &len);
-    if (value < (BUFSIZE*2))
-    {
-        value = BUFSIZE * 2;
-        SetSockOpt(SO_SNDBUF, &value, sizeof(value));
-    }
-
-    if (m_nTransferState == STATE_STARTING)
-    {
-        m_nTransferState = STATE_STARTED;
-
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnAccept(%d)"), nErrorCode);
+	m_bListening=FALSE;
+	CAsyncSocketEx tmp;
+	Accept(tmp);
+	SOCKET socket=tmp.Detach();
+	CAsyncSocketEx::Close();
+	
+	Attach(socket);
+
+	/* Set internal socket send buffer to twice the programs buffer size
+	 * this should fix the speed problems some users have reported
+	 */
+	DWORD value;
+	int len = sizeof(value);
+	GetSockOpt(SO_SNDBUF, &value, &len);
+	if (value < (BUFSIZE*2))
+	{
+		value = BUFSIZE * 2;
+		SetSockOpt(SO_SNDBUF, &value, sizeof(value));
+	}
+
+	if (m_nTransferState == STATE_STARTING)
+	{
+		m_nTransferState = STATE_STARTED;	
+		
 #ifndef MPEXT_NO_SSL
-        if (m_pSslLayer)
-        {
-            AddLayer(m_pSslLayer);
-            int res = m_pSslLayer->InitSSLConnection(true);
-            if (res == SSL_FAILURE_LOADDLLS)
-                m_pOwner->ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
-            else if (res == SSL_FAILURE_INITSSL)
-                m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
-
-            if (res)
-            {
-                Close();
-                if (!m_bSentClose)
-                {
-                    m_nMode |= CSMODE_TRANSFERERROR;
-                    m_bSentClose = TRUE;
-                    m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                }
-                return;
-            }
-        }
+		if (m_pSslLayer)
+		{
+			AddLayer(m_pSslLayer);
+			int res = m_pSslLayer->InitSSLConnection(true);
+			if (res == SSL_FAILURE_LOADDLLS)
+				m_pOwner->ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
+			else if (res == SSL_FAILURE_INITSSL)
+				m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
+					
+			if (res)
+			{
+				Close();
+				if (!m_bSentClose)
+				{
+					m_nMode |= CSMODE_TRANSFERERROR;
+					m_bSentClose = TRUE;
+					m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+				}
+				return;
+			}
+		}
 #endif
-
+		
 #ifndef MPEXT_NO_GSS
-        if (m_pGssLayer)
-        {
-            AddLayer(m_pGssLayer);
-        }
+		if (m_pGssLayer)
+		{
+			AddLayer(m_pGssLayer);
+		}
 #endif
-
-        m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
-        m_LastActiveTime = CTime::GetCurrentTime();
-    }
+		
+		m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
+		m_LastActiveTime = CTime::GetCurrentTime();
+	}
 }
 
-void CTransferSocket::OnConnect(int nErrorCode)
+void CTransferSocket::OnConnect(int nErrorCode) 
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnConnect(%d)"), nErrorCode);
-    if (nErrorCode)
-    {
-        TCHAR buffer[1000];
-        memset(buffer,0,1000);
-        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, nErrorCode, 0, buffer, 999, 0);
-        CString str;
-        str.Format(IDS_ERRORMSG_CANTOPENTRANSFERCHANNEL,buffer);
-        str.Replace( _T("\n"), _T("\0") );
-        str.Replace( _T("\r"), _T("\0") );
-        m_pOwner->ShowStatus(str, 1);
-        Close();
-        if (!m_bSentClose)
-        {
-            m_nMode|=CSMODE_TRANSFERERROR;
-            m_bSentClose=TRUE;
-            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-        }
-    }
-    else
-    {
-        /* Set internal socket send buffer to twice the programs buffer size
-         * this should fix the speed problems some users have reported
-         */
-        DWORD value;
-        int len = sizeof(value);
-        GetSockOpt(SO_SNDBUF, &value, &len);
-        if (value < (BUFSIZE*2))
-        {
-            value = BUFSIZE * 2;
-            SetSockOpt(SO_SNDBUF, &value, sizeof(value));
-        }
-    }
-    if (m_nTransferState == STATE_STARTING)
-    {
-        m_nTransferState = STATE_STARTED;
-
-        m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
-        m_LastActiveTime=CTime::GetCurrentTime();
-
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnConnect(%d)"), nErrorCode);
+	if (nErrorCode)
+	{
+		TCHAR buffer[1000];
+		memset(buffer,0,1000);
+		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, nErrorCode, 0, buffer, 999, 0);
+		CString str;
+		str.Format(IDS_ERRORMSG_CANTOPENTRANSFERCHANNEL,buffer);
+		str.Replace( _T("\n"), _T("\0") );
+		str.Replace( _T("\r"), _T("\0") );
+		m_pOwner->ShowStatus(str, 1);
+		Close();
+		if (!m_bSentClose)
+		{
+			m_nMode|=CSMODE_TRANSFERERROR;
+			m_bSentClose=TRUE;
+			m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+		}	
+	}
+	else
+	{
+		/* Set internal socket send buffer to twice the programs buffer size
+		 * this should fix the speed problems some users have reported
+		 */
+		DWORD value;
+		int len = sizeof(value);
+		GetSockOpt(SO_SNDBUF, &value, &len);
+		if (value < (BUFSIZE*2))
+		{
+			value = BUFSIZE * 2;
+			SetSockOpt(SO_SNDBUF, &value, sizeof(value));
+		}
+	}
+	if (m_nTransferState == STATE_STARTING)
+	{
+		m_nTransferState = STATE_STARTED;
+		
+		m_TransferedFirst = m_StartTime = CTime::GetCurrentTime();
+		m_LastActiveTime=CTime::GetCurrentTime();
+		
 #ifndef MPEXT_NO_SSL
-        if (m_pSslLayer)
-        {
-            AddLayer(m_pSslLayer);
-            int res = m_pSslLayer->InitSSLConnection(true);
-            if (res == SSL_FAILURE_LOADDLLS)
-                m_pOwner->ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
-            else if (res == SSL_FAILURE_INITSSL)
-                m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
-
-            if (res)
-            {
-                Close();
-                if (!m_bSentClose)
-                {
-                    m_nMode |= CSMODE_TRANSFERERROR;
-                    m_bSentClose = TRUE;
-                    m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                }
-                return;
-            }
-        }
+		if (m_pSslLayer)
+		{
+			AddLayer(m_pSslLayer);
+			int res = m_pSslLayer->InitSSLConnection(true);
+			if (res == SSL_FAILURE_LOADDLLS)
+				m_pOwner->ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
+			else if (res == SSL_FAILURE_INITSSL)
+				m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
+					
+			if (res)
+			{
+				Close();
+				if (!m_bSentClose)
+				{
+					m_nMode |= CSMODE_TRANSFERERROR;
+					m_bSentClose = TRUE;
+					m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+				}
+				return;
+			}
+		}
 #endif
-
+		
 #ifndef MPEXT_NO_GSS
-        if (m_pGssLayer)
-        {
-            AddLayer(m_pGssLayer);
-        }
+		if (m_pGssLayer)
+		{
+			AddLayer(m_pGssLayer);
+		}
 #endif
-    }
-}
+	}
+}	
 
 
-void CTransferSocket::OnClose(int nErrorCode)
+void CTransferSocket::OnClose(int nErrorCode) 
 {
-    LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("OnClose(%d)"), nErrorCode);
-
-    if (m_nTransferState == STATE_WAITING)
-    {
-        m_nNotifyWaiting |= FD_CLOSE;
-        return;
-    }
-
-    OnReceive(0);
-    Close();
-    if (!m_bSentClose)
-    {
-        m_bSentClose=TRUE;
-        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-    }
+	LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("OnClose(%d)"), nErrorCode);
+
+	if (m_nTransferState == STATE_WAITING)
+	{
+		m_nNotifyWaiting |= FD_CLOSE;
+		return;
+	}
+
+	OnReceive(0);
+	Close();
+	if (!m_bSentClose)
+	{
+		m_bSentClose=TRUE;
+		m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+	}
 }
 
 int CTransferSocket::CheckForTimeout(int delay)
 {
-    UpdateStatusBar(false);
-    if (!m_bCheckTimeout)
-        return 1;
-    CTimeSpan span = CTime::GetCurrentTime()-m_LastActiveTime;
-    if (span.GetTotalSeconds()>=delay)
-    {
-        m_pOwner->ShowStatus(IDS_ERRORMSG_TIMEOUT, 1);
-        Close();
-        if (!m_bSentClose)
-        {
-            m_nMode |= CSMODE_TRANSFERTIMEOUT;
-            m_bSentClose = TRUE;
-            VERIFY(m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode));
-        }
-        return 2;
-    }
-    return 1;
+	UpdateStatusBar(false);
+	if (!m_bCheckTimeout)
+		return 1;
+	CTimeSpan span = CTime::GetCurrentTime()-m_LastActiveTime;
+	if (span.GetTotalSeconds()>=delay)
+	{
+		m_pOwner->ShowStatus(IDS_ERRORMSG_TIMEOUT, 1);
+		Close();
+		if (!m_bSentClose)
+		{
+			m_nMode |= CSMODE_TRANSFERTIMEOUT;
+			m_bSentClose = TRUE;
+			VERIFY(m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode));
+		}
+		return 2;
+	}
+	return 1;
 }
 
 void CTransferSocket::SetActive()
 {
-    LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("SetActive()"));
-
-    if (m_nTransferState == STATE_WAITING)
-        m_nTransferState = STATE_STARTING;
-    m_bCheckTimeout = TRUE;
-    m_LastActiveTime = CTime::GetCurrentTime();
-
-    if (m_nNotifyWaiting & FD_READ)
-        OnReceive(0);
-    if (m_nNotifyWaiting & FD_WRITE)
-        OnSend(0);
-    if (m_nNotifyWaiting & FD_CLOSE)
-        OnClose(0);
+	LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("SetActive()"));
+
+	if (m_nTransferState == STATE_WAITING)
+		m_nTransferState = STATE_STARTING;
+	m_bCheckTimeout = TRUE;
+	m_LastActiveTime = CTime::GetCurrentTime();
+
+	if (m_nNotifyWaiting & FD_READ)
+		OnReceive(0);
+	if (m_nNotifyWaiting & FD_WRITE)
+		OnSend(0);
+	if (m_nNotifyWaiting & FD_CLOSE)
+		OnClose(0);
 }
 
-void CTransferSocket::OnSend(int nErrorCode)
+void CTransferSocket::OnSend(int nErrorCode) 
 {
-    if (m_nTransferState == STATE_WAITING)
-    {
-        m_nNotifyWaiting |= FD_WRITE;
-        return;
-    }
-
-    if (m_bSentClose)
-        return;
-    if (m_bListening)
-        return;
-
-    if (!(m_nMode&CSMODE_UPLOAD))
-        return;
-
-    if (m_nTransferState == STATE_STARTING)
-        OnConnect(0);
+	if (m_nTransferState == STATE_WAITING)
+	{
+		m_nNotifyWaiting |= FD_WRITE;
+		return;
+	}
+
+	if (m_bSentClose)
+		return;
+	if (m_bListening)
+		return;
+	
+	if (!(m_nMode&CSMODE_UPLOAD))
+		return;
+
+	if (m_nTransferState == STATE_STARTING)
+		OnConnect(0);
 
 #ifndef MPEXT_NO_ZLIB
-    if (m_useZlib)
-    {
-        if (!m_pBuffer)
-        {
-            m_pBuffer = new char[BUFSIZE];
-            m_bufferpos = 0;
-
-            m_zlibStream.next_out = (Bytef *)m_pBuffer;
-            m_zlibStream.avail_out = BUFSIZE;
-        }
-        if (!m_pBuffer2)
-        {
-            m_pBuffer2 = new char[BUFSIZE];
-
-            m_zlibStream.next_in = (Bytef *)m_pBuffer2;
-        }
-
-        bool beenWaiting = false;
-        while (true)
-        {
-            int numsend;
-            if (!m_zlibStream.avail_in)
-            {
-                if (m_pFile)
-                {
-                    DWORD numread;
-                    numread = ReadDataFromFile(m_pBuffer2, BUFSIZE);
-                    if (numread < 0)
-                        return;
-
-                    m_transferdata.transferleft -= numread;
-                    m_zlibStream.next_in = (Bytef *)m_pBuffer2;
-                    m_zlibStream.avail_in = numread;
-
-                    if (numread < BUFSIZE)
-                        m_pFile = 0;
-                }
-            }
-            if (!m_zlibStream.avail_out)
-            {
-                if (m_bufferpos >= BUFSIZE)
-                {
-                    m_bufferpos = 0;
-                    m_zlibStream.next_out = (Bytef *)m_pBuffer;
-                    m_zlibStream.avail_out = BUFSIZE;
-                }
-            }
-
-            int res = Z_OK;
-            if (m_zlibStream.avail_out)
-            {
-                res = deflate(&m_zlibStream, m_pFile ? 0 : Z_FINISH);
-                if (res != Z_OK && (!m_pFile && res != Z_STREAM_END))
-                {
-                    m_pOwner->ShowStatus("ZLib error", 1);
-                    Close();
-                    if (!m_bSentClose)
-                    {
-                        m_nMode |= CSMODE_TRANSFERERROR;
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                    return;
-                }
-            }
-
-            numsend = BUFSIZE;
-            int len = BUFSIZE - m_bufferpos - m_zlibStream.avail_out;
-            if (!len && !m_pFile)
-                break;
-
-            if (len < BUFSIZE)
-                numsend = len;
-
-            int nLimit = (int)m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
-            if (nLimit != -1 && GetState() != closed && numsend > nLimit)
-                numsend = nLimit;
-
-            if (!numsend)
-            {
-                TriggerEvent(FD_WRITE);
-                return;
-            }
-
-            int numsent = Send(m_pBuffer + m_bufferpos, numsend);
-            if (numsent == SOCKET_ERROR)
-            {
-                int nError = GetLastError();
-                if (nError == WSAENOTCONN)
-                {
-                    //Not yet connected
-                    return;
-                }
+	if (m_useZlib)
+	{
+		if (!m_pBuffer)
+		{
+			m_pBuffer = new char[BUFSIZE];
+			m_bufferpos = 0;
+
+			m_zlibStream.next_out = (Bytef *)m_pBuffer;
+			m_zlibStream.avail_out = BUFSIZE;
+		}
+		if (!m_pBuffer2)
+		{
+			m_pBuffer2 = new char[BUFSIZE];
+
+			m_zlibStream.next_in = (Bytef *)m_pBuffer2;
+		}
+
+		bool beenWaiting = false;
+		while (true)
+		{
+			int numsend;
+			if (!m_zlibStream.avail_in)
+			{
+				if (m_pFile)
+				{
+					DWORD numread;
+					numread = ReadDataFromFile(m_pBuffer2, BUFSIZE);
+					if (numread < 0)
+						return;
+
+					m_transferdata.transferleft -= numread;					
+					m_zlibStream.next_in = (Bytef *)m_pBuffer2;
+					m_zlibStream.avail_in = numread;
+
+					if (numread < BUFSIZE)
+						m_pFile = 0;
+				}
+			}
+			if (!m_zlibStream.avail_out)
+			{
+				if (m_bufferpos >= BUFSIZE)
+				{
+					m_bufferpos = 0;
+					m_zlibStream.next_out = (Bytef *)m_pBuffer;
+					m_zlibStream.avail_out = BUFSIZE;
+				}
+			}
+
+			int res = Z_OK;
+			if (m_zlibStream.avail_out)
+			{
+				res = deflate(&m_zlibStream, m_pFile ? 0 : Z_FINISH);
+				if (res != Z_OK && (!m_pFile && res != Z_STREAM_END))
+				{
+					m_pOwner->ShowStatus("ZLib error", 1);
+					Close();
+					if (!m_bSentClose)
+					{
+						m_nMode |= CSMODE_TRANSFERERROR;
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+					return;
+				}
+			}
+
+			numsend = BUFSIZE;
+			int len = BUFSIZE - m_bufferpos - m_zlibStream.avail_out;
+			if (!len && !m_pFile)
+				break;
+
+			if (len < BUFSIZE)
+				numsend = len;
+
+			int nLimit = (int)m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
+			if (nLimit != -1 && GetState() != closed && numsend > nLimit)
+				numsend = nLimit;
+
+			if (!numsend)
+			{
+				TriggerEvent(FD_WRITE);
+				return;
+			}
+
+			int numsent = Send(m_pBuffer + m_bufferpos, numsend);
+			if (numsent == SOCKET_ERROR)
+			{
+				int nError = GetLastError();
+				if (nError == WSAENOTCONN)
+				{
+					//Not yet connected
+					return;
+				}
 #ifndef MPEXT_NO_SSL
-                else if (m_pSslLayer && nError == WSAESHUTDOWN)
-                {
-                    // Do nothing, wait for shutdown complete notification.
-                    return;
-                }
+				else if (m_pSslLayer && nError == WSAESHUTDOWN)
+				{
+					// Do nothing, wait for shutdown complete notification.
+					return;
+				}
 #endif
-                else if (nError != WSAEWOULDBLOCK)
-                {
-                    if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                    {
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_nMode |= CSMODE_TRANSFERERROR;
-                            m_bSentClose = TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                    }
-                }
-                UpdateStatusBar(false);
-                return;
-            }
-
-            Transfered( numsent, CTime::GetCurrentTime());
-            m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
-            m_LastActiveTime = CTime::GetCurrentTime();
-            UpdateSendLed();
-
-            m_bufferpos += numsent;
-
-            UpdateStatusBar(false);
-
-            if (!m_zlibStream.avail_in && !m_pFile && m_zlibStream.avail_out &&
-                m_zlibStream.avail_out + m_bufferpos == BUFSIZE && res == Z_STREAM_END)
-            {
-                if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                {
-                    Close();
-                    if (!m_bSentClose)
-                    {
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                }
-                return;
-            }
-
-            //Check if there are other commands in the command queue.
-            MSG msg;
-            if (PeekMessage(&msg,0, 0, 0, PM_NOREMOVE))
-            {
-                TriggerEvent(FD_WRITE);
-                return;
-            }
-        }
-    }
-    else
+				else if (nError != WSAEWOULDBLOCK)
+				{
+					if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+					{
+						Close();
+						if (!m_bSentClose)
+						{
+							m_nMode |= CSMODE_TRANSFERERROR;
+							m_bSentClose = TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+					}
+				}
+				UpdateStatusBar(false);
+				return;
+			}
+
+			Transfered( numsent, CTime::GetCurrentTime());
+			m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
+			m_LastActiveTime = CTime::GetCurrentTime();
+			UpdateSendLed();
+
+			m_bufferpos += numsent;
+
+			UpdateStatusBar(false);
+			
+			if (!m_zlibStream.avail_in && !m_pFile && m_zlibStream.avail_out &&
+				m_zlibStream.avail_out + m_bufferpos == BUFSIZE && res == Z_STREAM_END)
+			{
+				if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+				{
+					Close();
+					if (!m_bSentClose)
+					{
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+				}
+				return;
+			}
+
+			//Check if there are other commands in the command queue.
+			MSG msg;
+			if (PeekMessage(&msg,0, 0, 0, PM_NOREMOVE))
+			{
+				TriggerEvent(FD_WRITE);
+				return;
+			}
+		}
+	}
+	else
 #endif
-    {
-        if (!m_pFile)
-            return;
-        if (!m_pBuffer)
-            m_pBuffer = new char[BUFSIZE];
-
-        int numread;
-
-        bool beenWaiting = false;
-        _int64 currentBufferSize;
-        if (GetState() != closed)
-            currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
-        else
-            currentBufferSize = BUFSIZE;
-
-        if (!currentBufferSize && !m_bufferpos)
-        {
-            // Not allowed to send yet, try later
-            TriggerEvent(FD_WRITE);
-            return;
-        }
-        else if (m_bufferpos < currentBufferSize)
-        {
-            numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
-            if (numread < 0 )
-                return;
-            else if (!numread && !m_bufferpos)
-            {
-                if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                {
-                    Close();
-                    if (!m_bSentClose)
-                    {
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                }
-                return;
-            }
-        }
-        else
-            numread = 0;
-
-        ASSERT((numread+m_bufferpos) <= BUFSIZE);
-        ASSERT(numread>=0);
-        ASSERT(m_bufferpos>=0);
-
-        if (numread+m_bufferpos <= 0)
-        {
-            if (ShutDown() || GetLastError()!=WSAEWOULDBLOCK)
-            {
-                Close();
-                if (!m_bSentClose)
-                {
-                    m_bSentClose=TRUE;
-                    m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                }
-            }
-            return;
-        }
-
-        int numsent = Send(m_pBuffer, numread + m_bufferpos);
-
-        while (TRUE)
-        {
-            if (numsent != SOCKET_ERROR)
-            {
-                Transfered(numsent, CTime::GetCurrentTime());
-                m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
-                m_LastActiveTime = CTime::GetCurrentTime();
-                UpdateSendLed();
-                m_transferdata.transferleft -= numsent;
-            }
-
-            if (numsent==SOCKET_ERROR || !numsent)
-            {
-                int nError = GetLastError();
-                if (nError == WSAENOTCONN)
-                {
-                    //Not yet connected
-                    m_bufferpos += numread;
-                    return;
-                }
-                else if (nError == WSAEWOULDBLOCK)
-                    m_bufferpos += numread;
+	{
+		if (!m_pFile)
+			return;
+		if (!m_pBuffer)
+			m_pBuffer = new char[BUFSIZE];
+		
+		int numread;
+		
+		bool beenWaiting = false;
+		_int64 currentBufferSize;
+		if (GetState() != closed)
+			currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
+		else
+			currentBufferSize = BUFSIZE;
+
+		if (!currentBufferSize && !m_bufferpos)
+		{
+			// Not allowed to send yet, try later
+			TriggerEvent(FD_WRITE);
+			return;
+		}
+		else if (m_bufferpos < currentBufferSize)
+		{
+			numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
+			if (numread < 0 )
+				return;
+			else if (!numread && !m_bufferpos)
+			{
+				if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+				{
+					Close();
+					if (!m_bSentClose)
+					{
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+				}
+				return;
+			}
+		}
+		else
+			numread = 0;
+			
+		ASSERT((numread+m_bufferpos) <= BUFSIZE);
+		ASSERT(numread>=0);
+		ASSERT(m_bufferpos>=0);
+
+		if (numread+m_bufferpos <= 0)
+		{
+			if (ShutDown() || GetLastError()!=WSAEWOULDBLOCK)
+			{
+				Close();
+				if (!m_bSentClose)
+				{
+					m_bSentClose=TRUE;
+					m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+				}
+			}
+			return;
+		}
+			
+		int numsent = Send(m_pBuffer, numread + m_bufferpos);
+			
+		while (TRUE)
+		{
+			if (numsent != SOCKET_ERROR)
+			{
+				Transfered(numsent, CTime::GetCurrentTime());
+				m_pOwner->SpeedLimitAddTransferredBytes(CControlSocket::upload, numsent);
+				m_LastActiveTime = CTime::GetCurrentTime();
+				UpdateSendLed();
+				m_transferdata.transferleft -= numsent;
+			}
+			
+			if (numsent==SOCKET_ERROR || !numsent)
+			{
+				int nError = GetLastError();
+				if (nError == WSAENOTCONN)
+				{
+					//Not yet connected
+					m_bufferpos += numread;
+					return;
+				}
+				else if (nError == WSAEWOULDBLOCK)
+					m_bufferpos += numread;
 #ifndef MPEXT_NO_SSL
-                else if (m_pSslLayer && nError == WSAESHUTDOWN)
-                {
-                    m_bufferpos += numread;
-                    // Do nothing, wait for shutdown complete notification.
-                    return;
-                }
+				else if (m_pSslLayer && nError == WSAESHUTDOWN)
+				{
+					m_bufferpos += numread;
+					// Do nothing, wait for shutdown complete notification.
+					return;
+				}
 #endif
-                else
-                {
-                    if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                    {
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_nMode |= CSMODE_TRANSFERERROR;
-                            m_bSentClose = TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                    }
-                }
-                UpdateStatusBar(false);
-                return;
-            }
-            else
-            {
-                int pos = numread + m_bufferpos - numsent;
-
-                if (pos < 0 || (numsent + pos) > BUFSIZE)
-                {
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Index out of range"));
-                    if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                    {
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_nMode |= CSMODE_TRANSFERERROR;
-                            m_bSentClose = TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                    }
-                    return;
-                }
-                else if (!pos && numread < (currentBufferSize-m_bufferpos) && m_bufferpos != currentBufferSize)
-                {
-                    if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                    {
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_bSentClose = TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                    }
-                    return;
-                }
-                else if (!pos)
-                    m_bufferpos = 0;
-                else
-                {
-                    memmove(m_pBuffer, m_pBuffer+numsent, pos);
-                    m_bufferpos=pos;
-                }
-            }
-            //Check if there are other commands in the command queue.
-            MSG msg;
-            if (PeekMessage(&msg, 0, m_nInternalMessageID, m_nInternalMessageID, PM_NOREMOVE))
-            {
-                //Send resume message
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("Message waiting in queue, resuming later"));
-                TriggerEvent(FD_WRITE);
-                UpdateStatusBar(false);
-                return;
-            }
-            UpdateStatusBar(false);
-
-            if (GetState() != closed)
-                currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
-            else
-                currentBufferSize = BUFSIZE;
-
-            if (m_bufferpos < currentBufferSize)
-            {
-                numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
-                if (numread < 0 )
-                    return;
-                else if (!numread && !m_bufferpos)
-                {
-                    if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-                    {
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_bSentClose = TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                    }
-                    return;
-                }
-            }
-            else
-                numread = 0;
-
-            if (!currentBufferSize && !m_bufferpos)
-            {
-                // Not allowed to send yet, try later
-                TriggerEvent(FD_WRITE);
-                return;
-            }
-
-            ASSERT(numread>=0);
-            ASSERT(m_bufferpos>=0);
-            numsent = Send(m_pBuffer, numread+m_bufferpos);
-        }
-    }
+				else
+				{
+					if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+					{
+						Close();
+						if (!m_bSentClose)
+						{
+							m_nMode |= CSMODE_TRANSFERERROR;
+							m_bSentClose = TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+					}
+				}
+				UpdateStatusBar(false);
+				return;
+			}
+			else
+			{
+				int pos = numread + m_bufferpos - numsent;
+
+				if (pos < 0 || (numsent + pos) > BUFSIZE)
+				{
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Index out of range"));
+					if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+					{
+						Close();
+						if (!m_bSentClose)
+						{
+							m_nMode |= CSMODE_TRANSFERERROR;
+							m_bSentClose = TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+					}
+					return;
+				}
+				else if (!pos && numread < (currentBufferSize-m_bufferpos) && m_bufferpos != currentBufferSize)
+				{
+					if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+					{
+						Close();
+						if (!m_bSentClose)
+						{
+							m_bSentClose = TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+					}
+					return;
+				}
+				else if (!pos)
+					m_bufferpos = 0;
+				else
+				{
+					memmove(m_pBuffer, m_pBuffer+numsent, pos);
+					m_bufferpos=pos;
+				}
+			}
+			//Check if there are other commands in the command queue.
+			MSG msg;
+			if (PeekMessage(&msg, 0, m_nInternalMessageID, m_nInternalMessageID, PM_NOREMOVE))
+			{
+				//Send resume message
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("Message waiting in queue, resuming later"));
+				TriggerEvent(FD_WRITE);
+				UpdateStatusBar(false);
+				return;
+			}
+			UpdateStatusBar(false);
+				
+			if (GetState() != closed)
+				currentBufferSize = m_pOwner->GetAbleToTransferSize(CControlSocket::upload, beenWaiting);
+			else
+				currentBufferSize = BUFSIZE;
+
+			if (m_bufferpos < currentBufferSize)
+			{
+				numread = ReadDataFromFile(m_pBuffer + m_bufferpos, static_cast<int>(currentBufferSize - m_bufferpos));
+				if (numread < 0 )
+					return;
+				else if (!numread && !m_bufferpos)
+				{
+					if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+					{
+						Close();
+						if (!m_bSentClose)
+						{
+							m_bSentClose = TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+					}
+					return;
+				}
+			}
+			else 
+				numread = 0;
+
+			if (!currentBufferSize && !m_bufferpos)
+			{
+				// Not allowed to send yet, try later
+				TriggerEvent(FD_WRITE);
+				return;
+			}
+	
+			ASSERT(numread>=0);
+			ASSERT(m_bufferpos>=0);
+			numsent = Send(m_pBuffer, numread+m_bufferpos);	
+		}
+	}
 }
 
 void CTransferSocket::UpdateStatusBar(bool forceUpdate)
 {
-    if (m_nTransferState != STATE_STARTED)
-        return;
-
-    if (!forceUpdate)
-    {
-        //Don't flood the main window with messages
-        //Else performance would be really low
-        LARGE_INTEGER curtime;
-        LARGE_INTEGER freq;
-        QueryPerformanceFrequency(&freq);
-        QueryPerformanceCounter(&curtime);
-        if (((curtime.QuadPart-m_LastUpdateTime.QuadPart) < (freq.QuadPart/15) ) )
-            return;
-        m_LastUpdateTime = curtime;
-    }
-
-    //Update the statusbar
-    CTimeSpan timespan=CTime::GetCurrentTime()-m_StartTime;
-    int elapsed=(int)timespan.GetTotalSeconds();
-
-    t_ffam_transferstatus *status=new t_ffam_transferstatus;
-    status->bFileTransfer = m_nMode & (CSMODE_DOWNLOAD | CSMODE_UPLOAD);
+	if (m_nTransferState != STATE_STARTED)
+		return;
+
+	if (!forceUpdate)
+	{
+		//Don't flood the main window with messages
+		//Else performance would be really low
+		LARGE_INTEGER curtime;
+		LARGE_INTEGER freq;
+		QueryPerformanceFrequency(&freq);
+		QueryPerformanceCounter(&curtime);
+		if (((curtime.QuadPart-m_LastUpdateTime.QuadPart) < (freq.QuadPart/15) ) )
+			return;
+		m_LastUpdateTime = curtime;
+	}
+	
+	//Update the statusbar
+	CTimeSpan timespan=CTime::GetCurrentTime()-m_StartTime;
+	int elapsed=(int)timespan.GetTotalSeconds();
+
+	t_ffam_transferstatus *status=new t_ffam_transferstatus;
+	status->bFileTransfer = m_nMode & (CSMODE_DOWNLOAD | CSMODE_UPLOAD);
 #ifdef MPEXT
-    status->transfersize = m_transferdata.transfersize;
+	status->transfersize = m_transferdata.transfersize;
 #endif
-    status->timeelapsed=elapsed;
-    status->bytes=m_transferdata.transfersize-m_transferdata.transferleft;
-    if (m_transferdata.transfersize>0 && !(m_nMode&CSMODE_LIST))
-    {
-        double leftmodifier=static_cast<double>(m_transferdata.transfersize-m_transferdata.nTransferStart-m_transferdata.transferleft);
-        leftmodifier*=100;
-        if (m_transferdata.transfersize-m_transferdata.nTransferStart)
-            leftmodifier /= (m_transferdata.transfersize-m_transferdata.nTransferStart);
-        else
-            leftmodifier = 1;
-        if (leftmodifier == 0)
-            leftmodifier = 1;
-        double leftmodifier2 = 100 - leftmodifier;
-        int left=static_cast<int>((elapsed/leftmodifier)*leftmodifier2);
-        double percent=100*static_cast<double>(m_transferdata.transfersize-m_transferdata.transferleft);
-        percent/=m_transferdata.transfersize;
-        status->percent=static_cast<int>(percent);
-        if (status->percent>100)
-            status->percent=100;
-
-        if (left < 0)
-            left = -1;
-        status->timeleft=left;
-    }
-    else
-    {
-        status->percent=-1;
-        status->timeleft=-1;
-    }
-
-    int count = 0;
-    status->transferrate = 0;
-
-    for ( int i = 0; i < SPEED_SECONDS; i++)
-    {
-        if ( m_UsedForTransfer[ i])
-        {
-            status->transferrate += m_Transfered[ i];
-
-            count++;
-        }
-    }
-
-    if ( count > 0)
-        status->transferrate = status->transferrate / count;
-    else if (m_Transfered[0])
-        status->transferrate = m_Transfered[0];
-    else
-        status->timeleft=-1;
-
-    PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
+	status->timeelapsed=elapsed;
+	status->bytes=m_transferdata.transfersize-m_transferdata.transferleft;
+	if (m_transferdata.transfersize>0 && !(m_nMode&CSMODE_LIST))
+	{
+		double leftmodifier=static_cast<double>(m_transferdata.transfersize-m_transferdata.nTransferStart-m_transferdata.transferleft);
+		leftmodifier*=100;
+		if (m_transferdata.transfersize-m_transferdata.nTransferStart)
+			leftmodifier /= (m_transferdata.transfersize-m_transferdata.nTransferStart);
+		else
+			leftmodifier = 1;
+		if (leftmodifier == 0)
+			leftmodifier = 1;
+		double leftmodifier2 = 100 - leftmodifier;
+		int left=static_cast<int>((elapsed/leftmodifier)*leftmodifier2);
+		double percent=100*static_cast<double>(m_transferdata.transfersize-m_transferdata.transferleft);
+		percent/=m_transferdata.transfersize;
+		status->percent=static_cast<int>(percent);
+		if (status->percent>100)
+			status->percent=100;
+		
+		if (left < 0)
+			left = -1;
+		status->timeleft=left;		
+	}
+	else
+	{
+		status->percent=-1;
+		status->timeleft=-1;
+	}
+
+	int count = 0;
+	status->transferrate = 0;
+
+	for ( int i = 0; i < SPEED_SECONDS; i++)
+	{
+		if ( m_UsedForTransfer[ i])
+		{
+			status->transferrate += m_Transfered[ i];
+
+			count++;
+		}
+	}
+
+	if ( count > 0)
+		status->transferrate = status->transferrate / count;
+	else if (m_Transfered[0])
+		status->transferrate = m_Transfered[0];
+	else
+		status->timeleft=-1;
+		
+	PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_TRANSFERSTATUS, 0), (LPARAM)status);
 }
 
 void CTransferSocket::UpdateSendLed()
 {
-    //Don't flood the main window with messages
-    //Else performance would be really low
-    LARGE_INTEGER curtime;
-    LARGE_INTEGER freq;
-    QueryPerformanceFrequency(&freq);
-    QueryPerformanceCounter(&curtime);
-    static LARGE_INTEGER oldtime={0};
-    if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
-        return;
-    oldtime=curtime;
-
-    PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
+	//Don't flood the main window with messages
+	//Else performance would be really low
+	LARGE_INTEGER curtime;
+	LARGE_INTEGER freq;
+	QueryPerformanceFrequency(&freq);
+	QueryPerformanceCounter(&curtime);
+	static LARGE_INTEGER oldtime={0};
+	if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
+		return;
+	oldtime=curtime;
+	
+	PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID,	FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
 }
 
 void CTransferSocket::UpdateRecvLed()
 {
-    //Don't flood the main window with messages
-    //Else performance would be really low
-    LARGE_INTEGER curtime;
-    LARGE_INTEGER freq;
-    QueryPerformanceFrequency(&freq);
-    QueryPerformanceCounter(&curtime);
-    static LARGE_INTEGER oldtime={0};
-    if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
-        return;
-    oldtime=curtime;
-
-    PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_RECV), 0);
+	//Don't flood the main window with messages
+	//Else performance would be really low
+	LARGE_INTEGER curtime;
+	LARGE_INTEGER freq;
+	QueryPerformanceFrequency(&freq);
+	QueryPerformanceCounter(&curtime);
+	static LARGE_INTEGER oldtime={0};
+	if ( ( (curtime.QuadPart-oldtime.QuadPart) < (freq.QuadPart/15) ) )
+		return;
+	oldtime=curtime;
+	
+	PostMessage(m_pOwner->m_pOwner->m_hOwnerWnd, m_pOwner->m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_RECV), 0);
 }
 
 BOOL CTransferSocket::Create(
 #ifndef MPEXT_NO_SSL
   BOOL bUseSsl
 #endif
-    )
+	)
 {
 #ifndef MPEXT_NO_SSL
-    if (bUseSsl)
-        m_pSslLayer = new CAsyncSslSocketLayer;
+	if (bUseSsl)
+		m_pSslLayer = new CAsyncSslSocketLayer;
 #endif
 
-    if (!m_pOwner->m_CurrentServer.fwbypass)
-    {
-        int nProxyType = COptions::GetOptionVal(OPTION_PROXYTYPE);
-        if (nProxyType != PROXYTYPE_NOPROXY)
-        {
-            USES_CONVERSION;
-
-            m_pProxyLayer = new CAsyncProxySocketLayer;
-            if (nProxyType == PROXYTYPE_SOCKS4)
-                m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
-            else if (nProxyType == PROXYTYPE_SOCKS4A)
-                m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
-            else if (nProxyType == PROXYTYPE_SOCKS5)
-                if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
-                    m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
-                                            COptions::GetOptionVal(OPTION_PROXYPORT),
-                                            T2CA(COptions::GetOption(OPTION_PROXYUSER)),
-                                            T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
-                else
-                    m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
-                                            COptions::GetOptionVal(OPTION_PROXYPORT));
-            else if (nProxyType == PROXYTYPE_HTTP11)
-                if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
-                    m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT),
-                                            T2CA(COptions::GetOption(OPTION_PROXYUSER)),
-                                            T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
-                else
-                    m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
-            else
-                ASSERT(FALSE);
-            AddLayer(m_pProxyLayer);
-        }
-    }
-
-    if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
-    {
-        if (!CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
-            return FALSE;
-
-        return TRUE;
-    }
-    else
-    {
-        int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
-        int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
-        if (min>=max)
-        {
-            m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
-            return FALSE;
-        }
-        int startport=static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
-        int port=startport;
-        while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
-        {
-            port++;
-            if (port>max)
-                port=min;
-            if (port==startport)
-            {
-                m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
-                return FALSE;
-            }
-        }
-    }
-
-    return TRUE;
+	if (!m_pOwner->m_CurrentServer.fwbypass)
+	{
+		int nProxyType = COptions::GetOptionVal(OPTION_PROXYTYPE);
+		if (nProxyType != PROXYTYPE_NOPROXY)
+		{
+			USES_CONVERSION;
+			
+			m_pProxyLayer = new CAsyncProxySocketLayer;
+			if (nProxyType == PROXYTYPE_SOCKS4)
+				m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
+			else if (nProxyType == PROXYTYPE_SOCKS4A)
+				m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS4A, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
+			else if (nProxyType == PROXYTYPE_SOCKS5)
+				if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
+					m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
+											COptions::GetOptionVal(OPTION_PROXYPORT),
+											T2CA(COptions::GetOption(OPTION_PROXYUSER)),
+											T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
+				else
+					m_pProxyLayer->SetProxy(PROXYTYPE_SOCKS5, T2CA(COptions::GetOption(OPTION_PROXYHOST)),
+											COptions::GetOptionVal(OPTION_PROXYPORT));
+			else if (nProxyType == PROXYTYPE_HTTP11)
+				if (COptions::GetOptionVal(OPTION_PROXYUSELOGON))
+					m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT),
+											T2CA(COptions::GetOption(OPTION_PROXYUSER)),
+											T2CA(CCrypt::decrypt(COptions::GetOption(OPTION_PROXYPASS))));
+				else
+					m_pProxyLayer->SetProxy(PROXYTYPE_HTTP11, T2CA(COptions::GetOption(OPTION_PROXYHOST)), COptions::GetOptionVal(OPTION_PROXYPORT));
+			else
+				ASSERT(FALSE);
+			AddLayer(m_pProxyLayer);
+		}
+	}
+
+	if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
+	{
+		if (!CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
+			return FALSE;
+
+		return TRUE;
+	}
+	else
+	{
+		int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
+		int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
+		if (min>=max)
+		{
+			m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
+			return FALSE;
+		}
+		int startport=static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
+		int port=startport;
+		while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetFamily()))
+		{
+			port++;
+			if (port>max)
+				port=min;
+			if (port==startport)
+			{
+				m_pOwner->ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
+				return FALSE;
+			}
+		}
+	}
+	
+	return TRUE;
 }
 
 void CTransferSocket::Close()
 {
-    LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Close()"));
-    m_bCheckTimeout = FALSE;
-    CAsyncSocketEx::Close();
+	LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Close()"));
+	m_bCheckTimeout = FALSE;
+	CAsyncSocketEx::Close();
 }
 
 int CTransferSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
 {
-    for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
-    {
-        if (iter->nType == LAYERCALLBACK_STATECHANGE)
-        {
-            if (iter->pLayer == m_pProxyLayer)
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pProxyLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
+	for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
+	{
+		if (iter->nType == LAYERCALLBACK_STATECHANGE)
+		{
+			if (iter->pLayer == m_pProxyLayer)
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pProxyLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
 #ifndef MPEXT_NO_SSL
-            else if (iter->pLayer == m_pSslLayer)
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pSslLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
+			else if (iter->pLayer == m_pSslLayer)
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pSslLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
 #endif
 #ifndef MPEXT_NO_GSS
-            else if (iter->pLayer == m_pGssLayer)
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pGssLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
+			else if (iter->pLayer == m_pGssLayer)
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pGssLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
 #endif
-            else
-                LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %d to %d"), iter->pLayer, iter->nParam2, iter->nParam1);
-        }
-        else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
-        {
-            if (iter->pLayer == m_pProxyLayer)
-            {
-                switch (iter->nParam1)
-                {
-                case PROXYERROR_NOCONN:
-                    m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, 1);
-                    break;
-                case PROXYERROR_REQUESTFAILED:
-                    m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, 1);
-                    break;
-                case PROXYERROR_AUTHTYPEUNKNOWN:
-                    m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, 1);
-                    break;
-                case PROXYERROR_AUTHFAILED:
-                    m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, 1);
-                    break;
-                case PROXYERROR_AUTHNOLOGON:
-                    m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, 1);
-                    break;
-                case PROXYERROR_CANTRESOLVEHOST:
-                    m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, 1);
-                    break;
-                default:
-                    LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error"));
-                }
-            }
+			else
+				LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("Layer @ %d changed state from %d to %d"), iter->pLayer, iter->nParam2, iter->nParam1);
+		}
+		else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
+		{
+			if (iter->pLayer == m_pProxyLayer)
+			{
+				switch (iter->nParam1)
+				{
+				case PROXYERROR_NOCONN:
+					m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, 1);
+					break;
+				case PROXYERROR_REQUESTFAILED:
+					m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, 1);
+					break;
+				case PROXYERROR_AUTHTYPEUNKNOWN:
+					m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, 1);
+					break;
+				case PROXYERROR_AUTHFAILED:
+					m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, 1);
+					break;
+				case PROXYERROR_AUTHNOLOGON:
+					m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, 1);
+					break;
+				case PROXYERROR_CANTRESOLVEHOST:
+					m_pOwner->ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, 1);
+					break;
+				default:
+					LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Unknown proxy error"));
+				}
+			}
 #ifndef MPEXT_NO_SSL
-            else if (iter->pLayer == m_pSslLayer)
-            {
-                switch (iter->nParam1)
-                {
-                case SSL_INFO:
-                    switch(iter->nParam2)
-                    {
-                    case SSL_INFO_SHUTDOWNCOMPLETE:
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_bSentClose=TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                        break;
-                    case SSL_INFO_ESTABLISHED:
-                        m_pOwner->ShowStatus(IDS_STATUSMSG_SSLESTABLISHEDTRANSFER, 0);
-                        TriggerEvent(FD_FORCEREAD);
-                        break;
-                    }
-                    break;
-                case SSL_FAILURE:
-                    switch (iter->nParam2)
-                    {
-                    case SSL_FAILURE_ESTABLISH:
-                        m_pOwner->ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, 1);
-                        break;
-                    case SSL_FAILURE_LOADDLLS:
-                        m_pOwner->ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
-                        break;
-                    case SSL_FAILURE_INITSSL:
-                        m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
-                        break;
-                    }
-                    if (!m_bSentClose)
-                    {
-                        m_nMode |= CSMODE_TRANSFERERROR;
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                    break;
-                case SSL_VERIFY_CERT:
-                    t_SslCertData data;
-                    if (m_pSslLayer->GetPeerCertificateData(data))
-                        m_pSslLayer->SetNotifyReply(data.priv_data, SSL_VERIFY_CERT, 1);
-                    else
-                    {
-                        Close();
-                        if (!m_bSentClose)
-                        {
-                            m_nMode |= CSMODE_TRANSFERERROR;
-                            m_bSentClose = TRUE;
-                            m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                        }
-                    }
-                    break;
-                }
-            }
+			else if (iter->pLayer == m_pSslLayer)
+			{
+				switch (iter->nParam1)
+				{
+				case SSL_INFO:
+					switch(iter->nParam2)
+					{
+					case SSL_INFO_SHUTDOWNCOMPLETE:
+						Close();
+						if (!m_bSentClose)
+						{
+							m_bSentClose=TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+						break;
+					case SSL_INFO_ESTABLISHED:
+						m_pOwner->ShowStatus(IDS_STATUSMSG_SSLESTABLISHEDTRANSFER, 0);
+						TriggerEvent(FD_FORCEREAD);
+						break;
+					}
+					break;
+				case SSL_FAILURE:
+					switch (iter->nParam2)
+					{
+					case SSL_FAILURE_ESTABLISH:
+						m_pOwner->ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, 1);
+						break;
+					case SSL_FAILURE_LOADDLLS:
+						m_pOwner->ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
+						break;
+					case SSL_FAILURE_INITSSL:
+						m_pOwner->ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
+						break;
+					}
+					if (!m_bSentClose)
+					{
+						m_nMode |= CSMODE_TRANSFERERROR;
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+					break;
+				case SSL_VERIFY_CERT:
+					t_SslCertData data;
+					if (m_pSslLayer->GetPeerCertificateData(data))
+						m_pSslLayer->SetNotifyReply(data.priv_data, SSL_VERIFY_CERT, 1);
+					else
+					{
+						Close();
+						if (!m_bSentClose)
+						{
+							m_nMode |= CSMODE_TRANSFERERROR;
+							m_bSentClose = TRUE;
+							m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+						}
+					}
+					break;
+				}
+			}
 #endif
 #ifndef MPEXT_NO_GSS
-            else if (iter->pLayer == m_pGssLayer)
-            {
-                USES_CONVERSION;
-                switch (iter->nParam1)
-                {
-                case GSS_INFO:
-                    LogMessage(FZ_LOG_INFO, A2CT(iter->str));
-                    break;
-                case GSS_ERROR:
-                    LogMessage(FZ_LOG_APIERROR, A2CT(iter->str));
-                    break;
-                case GSS_SHUTDOWN_COMPLETE:
-                    Close();
-                    if (!m_bSentClose)
-                    {
-                        m_bSentClose = TRUE;
-                        m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-                    }
-                    break;
-                }
-            }
+			else if (iter->pLayer == m_pGssLayer)
+			{
+				USES_CONVERSION;
+				switch (iter->nParam1)
+				{
+				case GSS_INFO:
+					LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
+					break;
+				case GSS_ERROR:
+					LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
+					break;
+				case GSS_SHUTDOWN_COMPLETE:
+					Close();
+					if (!m_bSentClose)
+					{
+						m_bSentClose = TRUE;
+						m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+					}
+					break;
+				}
+			}
 #endif
-        }
-        delete [] iter->str;
-    }
-    return 0;
+		}
+		delete [] iter->str;
+	}
+	return 0;
 }
 
 void CTransferSocket::Transfered(int count, CTime time)
 {
-    CTimeSpan ts = time - m_TransferedFirst;
-    int diff = (int)ts.GetTotalSeconds();
-    if (diff < 0)
-        diff = 0;
-
-    if ( diff >= SPEED_SECONDS)
-    {
-        int move = diff - SPEED_SECONDS + 1;
-        int start = SPEED_SECONDS - move;
-
-        if ( start <= 0)
-            start = 0;
-        else
-        {
-            for ( int i = 0; i < SPEED_SECONDS - move; i++)
-            {
-                m_Transfered[ i] = m_Transfered[ i + move];
-                m_UsedForTransfer[ i] = m_UsedForTransfer[ i + move];
-            }
-        }
-
-        for ( int i = start; i < SPEED_SECONDS; i++)
-        {
-            m_Transfered[ i] = 0;
-            m_UsedForTransfer[ i] = false;
-        }
-
-        if (move >= SPEED_SECONDS)
-        {
-            m_TransferedFirst = time;
-            diff = 0;
-        }
-        else
-        {
-            m_TransferedFirst += CTimeSpan( move);
-            ts = time - m_TransferedFirst;
-            diff = (int)(ts.GetTotalSeconds() % 60);
-        }
-    }
-
-    m_Transfered[ diff] += count;
-
-    for ( int i = 0; i < diff - 1; i++)
-        m_UsedForTransfer[ i] = true;
+	CTimeSpan ts = time - m_TransferedFirst;
+	int diff = (int)ts.GetTotalSeconds();
+	if (diff < 0)
+		diff = 0;
+	
+	if ( diff >= SPEED_SECONDS)
+	{
+		int move = diff - SPEED_SECONDS + 1;
+		int start = SPEED_SECONDS - move;
+
+		if ( start <= 0)
+			start = 0;
+		else
+		{
+			for ( int i = 0; i < SPEED_SECONDS - move; i++)
+			{
+				m_Transfered[ i] = m_Transfered[ i + move];
+				m_UsedForTransfer[ i] = m_UsedForTransfer[ i + move];
+			}
+		}
+
+		for ( int i = start; i < SPEED_SECONDS; i++)
+		{
+			m_Transfered[ i] = 0;
+			m_UsedForTransfer[ i] = false;
+		}
+
+		if (move >= SPEED_SECONDS)
+		{
+			m_TransferedFirst = time;
+			diff = 0;
+		}
+		else
+		{
+			m_TransferedFirst += CTimeSpan( move);
+			ts = time - m_TransferedFirst;
+			diff = (int)(ts.GetTotalSeconds() % 60);
+		}
+	}
+
+	m_Transfered[ diff] += count;
+
+	for ( int i = 0; i < diff - 1; i++)
+		m_UsedForTransfer[ i] = true;
 }
 
 #ifndef MPEXT_NO_GSS
 void CTransferSocket::UseGSS(CAsyncGssSocketLayer *pGssLayer)
 {
-    m_pGssLayer = new CAsyncGssSocketLayer;
-    m_pGssLayer->InitTransferChannel(pGssLayer);
+	m_pGssLayer = new CAsyncGssSocketLayer;
+	m_pGssLayer->InitTransferChannel(pGssLayer);
 }
 #endif
 
 #ifndef MPEXT_NO_ZLIB
 bool CTransferSocket::InitZlib(int level)
 {
-    int res;
-    if (m_nMode & CSMODE_UPLOAD)
-        res = deflateInit2(&m_zlibStream, level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
-    else
-        res = inflateInit2(&m_zlibStream, 15);
-
-    if (res == Z_OK)
-        m_useZlib = true;
-
-    return res == Z_OK;
+	int res;
+	if (m_nMode & CSMODE_UPLOAD)
+		res = deflateInit2(&m_zlibStream, level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
+	else
+		res = inflateInit2(&m_zlibStream, 15);
+	
+	if (res == Z_OK)
+		m_useZlib = true;
+
+	return res == Z_OK;
 }
 #endif
 
 int CTransferSocket::ReadDataFromFile(char *buffer, int len)
 {
-    TRY
-    {
-        if (!m_transferdata.bType)
-            return m_pFile->Read(buffer, len);
-        else
-        {   //Read the file as ASCII file with CRLF line end
-            if (!m_ReadBuffer)
-                m_ReadBuffer = new char[BUFSIZE];
-            if (!m_ReadSize)
-                m_ReadSize = m_pFile->Read(m_ReadBuffer, len);
-            int numread = 0;
-            while (numread < len)
-            {
-                if (m_ReadPos >= m_ReadSize)
-                {
-                    m_ReadSize = m_pFile->Read(m_ReadBuffer, len);
-                    m_ReadPos = 0;
-                    if (!m_ReadSize)
-                        break;
-                }
-                if (m_ReadBuffer[m_ReadPos] == '\n' && m_cLastChar != '\r')
-                {
-                    buffer[numread++] = '\r';
-                    m_cLastChar = '\r';
-                    if (numread == len)
-                        break;
-                }
-
-                buffer[numread] = m_ReadBuffer[m_ReadPos];
-                m_cLastChar = buffer[numread];
-                numread++;
-                m_ReadPos++;
-            }
-            ASSERT(numread <= len);
-            return numread;
-        }
-    }
-    CATCH_ALL(e)
-    {
-        TCHAR error[BUFSIZE];
-        if (e->GetErrorMessage(error, BUFSIZE))
-            m_pOwner->ShowStatus(error, 1);
-        if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
-        {
-            Close();
-            if (!m_bSentClose)
-            {
-                m_nMode |= CSMODE_TRANSFERERROR;
-                m_bSentClose = TRUE;
-                m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
-            }
-        }
-        return -1;
-    }
-    END_CATCH_ALL;
+	TRY
+	{
+		if (!m_transferdata.bType)
+			return m_pFile->Read(buffer, len);
+		else
+		{   //Read the file as ASCII file with CRLF line end
+			if (!m_ReadBuffer)
+				m_ReadBuffer = new char[BUFSIZE];
+			if (!m_ReadSize)
+				m_ReadSize = m_pFile->Read(m_ReadBuffer, len);
+			int numread = 0;
+			while (numread < len)
+			{
+				if (m_ReadPos >= m_ReadSize)
+				{
+					m_ReadSize = m_pFile->Read(m_ReadBuffer, len);
+					m_ReadPos = 0;
+					if (!m_ReadSize)
+					    break;
+				}
+				if (m_ReadBuffer[m_ReadPos] == '\n' && m_cLastChar != '\r')
+				{
+					buffer[numread++] = '\r';
+					m_cLastChar = '\r';
+					if (numread == len)
+					    break;
+				}
+
+				buffer[numread] = m_ReadBuffer[m_ReadPos];
+				m_cLastChar = buffer[numread];
+				numread++;
+				m_ReadPos++;
+			}
+			ASSERT(numread <= len);
+			return numread;
+		}
+	}
+	CATCH_ALL(e)
+	{
+		TCHAR error[BUFSIZE];
+		if (e->GetErrorMessage(error, BUFSIZE))
+			m_pOwner->ShowStatus(error, 1);
+		if (ShutDown() || GetLastError() != WSAEWOULDBLOCK)
+		{
+			Close();
+			if (!m_bSentClose)
+			{
+				m_nMode |= CSMODE_TRANSFERERROR;
+				m_bSentClose = TRUE;
+				m_pOwner->m_pOwner->PostThreadMessage(m_nInternalMessageID, FZAPI_THREADMSG_TRANSFEREND, m_nMode);
+			}
+		}
+		return -1;
+	}
+	END_CATCH_ALL;
 }

+ 4 - 6
filezilla/misc/CBase64Coding.cpp

@@ -21,10 +21,10 @@
 **
 ** Copyright, 2000, Samuel R. Blackburn
 **
-** $Workfile: CBase64Coding.cpp $
-** $Revision: 1.3 $
-** $Modtime: 5/12/00 3:39p $
-** $Reuse Tracing Code: 1 $
+** Workfile: CBase64Coding.cpp
+** Revision: 1.3
+** Modtime: 5/12/00 3:39p
+** Reuse Tracing Code: 1
 */
 
 //Modified for use with CAsyncProxySocket, removed tracing code
@@ -273,5 +273,3 @@ $Modtime: 5/12/00 3:39p $
 
 </HTML>
 #endif
-
-

+ 3 - 3
filezilla/misc/CBase64Coding.hpp

@@ -12,9 +12,9 @@
 **
 ** Copyright, 2000, Samuel R. Blackburn
 **
-** $Workfile: CBase64Coding.hpp $
-** $Revision: 1.2 $
-** $Modtime: 1/04/00 4:39a $
+** Workfile: CBase64Coding.hpp
+** Revision: 1.2
+** Modtime: 1/04/00 4:39a
 */
 
 #define BASE_64_CODING_CLASS_HEADER

+ 19 - 0
forms/About.cpp

@@ -104,6 +104,25 @@ __fastcall TAboutDialog::TAboutDialog(TComponent * AOwner,
     TranslatorLabel->Caption = LoadStr(TRANSLATOR_INFO);
     LinkLabel(TranslatorUrlLabel, LoadStr(TRANSLATOR_URL));
   }
+
+  #ifdef NO_FILEZILLA
+  int FileZillaHeight = Label1->Top - FileZillaVersionLabel->Top;
+  FileZillaVersionLabel->Visible = false;
+  FileZillaCopyrightLabel->Visible = false;
+  FileZillaHomepageLabel->Visible = false;
+
+  for (int Index = 0; Index < ThirdPartyBox->ControlCount; Index++)
+  {
+    TControl * Control = ThirdPartyBox->Controls[Index];
+    if (Control->Top > FileZillaHomepageLabel->Top)
+    {
+      Control->Top = Control->Top - FileZillaHeight;
+    }
+  }
+
+  ThirdPartyBox->VertScrollBar->Range = ThirdPartyBox->VertScrollBar->Range - FileZillaHeight;
+  #endif
+
   LicenceButton->Visible = AllowLicence;
   LoadData();
 }

+ 3 - 3
forms/CustomScpExplorer.cpp

@@ -5712,9 +5712,10 @@ void __fastcall TCustomScpExplorerForm::StatusBarPanelDblClick(
 //---------------------------------------------------------------------------
 void __fastcall TCustomScpExplorerForm::LockWindow()
 {
-  if (FLockLevel == 0)
+  // workaround: for unknown reason, disabling window, while minimized,
+  // prevents it from restoring, even if it was enabled again meanwhile
+  if (!IsIconic(Application->Handle))
   {
-    assert(Enabled);
     Enabled = false;
   }
 
@@ -5723,7 +5724,6 @@ void __fastcall TCustomScpExplorerForm::LockWindow()
 //---------------------------------------------------------------------------
 void __fastcall TCustomScpExplorerForm::UnlockWindow()
 {
-  assert(!Enabled);
   assert(FLockLevel > 0);
   FLockLevel--;
 

+ 1 - 1
forms/FileSystemInfo.cpp

@@ -120,7 +120,7 @@ void __fastcall TFileSystemInfoDialog::Feed(TFeedFileSystemData AddItem)
   }
   else
   {
-    CapabilityStr(fcAnyCommand);
+    AnyCommand = CapabilityStr(fcAnyCommand);
   }
   AddItem(ProtocolView, FSINFO_ANY_COMMAND, AnyCommand);
   AddItem(ProtocolView, FSINFO_SYMBOLIC_HARD_LINK, CapabilityStr(fcSymbolicLink, fcHardLink));

+ 0 - 1
forms/LogSettings.cpp

@@ -144,7 +144,6 @@ void __fastcall TLoggingFrame::LogFileNameEditBeforeDialog(TObject * /*Sender*/,
   Name = ExpandEnvironmentVariables(Name);
 }
 //---------------------------------------------------------------------------
-
 void __fastcall TLoggingFrame::LogFileNameEditAfterDialog(TObject * /*Sender*/,
   AnsiString & Name, bool & /*Action*/)
 {

+ 77 - 39
forms/Login.cpp

@@ -165,6 +165,12 @@ void __fastcall TLoginDialog::Init()
     TransferProtocolCombo->Items->Delete(TransferProtocolCombo->Items->Count - 1);
   }
 
+  #ifdef NO_FILEZILLA
+  assert(FLAGCLEAR(Options, loExternalProtocols));
+  assert(TransferProtocolCombo->Items->Count == FSPROTOCOL_COUNT - 2 - 1);
+  TransferProtocolCombo->Items->Delete(TransferProtocolCombo->Items->Count - 1);
+  #endif
+
   ShowTabs(false);
 
   if (StoredSessions && StoredSessions->Count &&
@@ -181,8 +187,7 @@ void __fastcall TLoginDialog::Init()
   }
   else
   {
-    ChangePage(BasicSheet);
-    HostNameEdit->SetFocus();
+    EditSession();
   }
 
   UpdateControls();
@@ -249,9 +254,14 @@ void __fastcall TLoginDialog::Default()
 //---------------------------------------------------------------------
 void __fastcall TLoginDialog::LoadSession(TSessionData * aSessionData)
 {
+  // it was always true, and now must be true because of ping/keepalive settings
+  assert(aSessionData == FSessionData);
+
   NoUpdate++;
   try
   {
+    FFSProtocol = aSessionData->FSProtocol;
+
     // Basic tab
     UserNameEdit->Text = aSessionData->UserName;
     PortNumberEdit->AsInteger = aSessionData->PortNumber;
@@ -358,21 +368,8 @@ void __fastcall TLoginDialog::LoadSession(TSessionData * aSessionData)
 
     // Connection tab
     FtpPasvModeCheck->Checked = aSessionData->FtpPasvMode;
-    switch (aSessionData->PingType)
-    {
-      case ptNullPacket:
-        PingNullPacketButton->Checked = true;
-        break;
 
-      case ptDummyCommand:
-        PingDummyCommandButton->Checked = true;
-        break;
-
-      default:
-        PingOffButton->Checked = true;
-        break;
-    }
-    PingIntervalSecEdit->AsInteger = aSessionData->PingInterval;
+    LoadPing(aSessionData);
     TimeoutEdit->AsInteger = aSessionData->Timeout;
 
     switch (aSessionData->AddressFamily)
@@ -489,8 +486,31 @@ void __fastcall TLoginDialog::LoadSession(TSessionData * aSessionData)
   FCurrentSessionName = aSessionData->Name;
 }
 //---------------------------------------------------------------------
+void __fastcall TLoginDialog::LoadPing(TSessionData * aSessionData)
+{
+  switch (FFSProtocol == fsFTP ? aSessionData->FtpPingType : aSessionData->PingType)
+  {
+    case ptNullPacket:
+      PingNullPacketButton->Checked = true;
+      break;
+
+    case ptDummyCommand:
+      PingDummyCommandButton->Checked = true;
+      break;
+
+    default:
+      PingOffButton->Checked = true;
+      break;
+  }
+  PingIntervalSecEdit->AsInteger =
+    (FFSProtocol == fsFTP ? aSessionData->FtpPingInterval : aSessionData->PingInterval);
+}
+//---------------------------------------------------------------------
 void __fastcall TLoginDialog::SaveSession(TSessionData * aSessionData)
 {
+  // it was always true, and now must be true because of ping/keepalive settings
+  assert(aSessionData == FSessionData);
+
   aSessionData->Name = FCurrentSessionName;
   // Basic tab
   aSessionData->UserName = UserNameEdit->Text.Trim();
@@ -541,19 +561,7 @@ void __fastcall TLoginDialog::SaveSession(TSessionData * aSessionData)
 
   // Connection tab
   aSessionData->FtpPasvMode = FtpPasvModeCheck->Checked;
-  if (PingNullPacketButton->Checked)
-  {
-    aSessionData->PingType = ptNullPacket;
-  }
-  else if (PingDummyCommandButton->Checked)
-  {
-    aSessionData->PingType = ptDummyCommand;
-  }
-  else
-  {
-    aSessionData->PingType = ptOff;
-  }
-  aSessionData->PingInterval = PingIntervalSecEdit->AsInteger;
+  SavePing(aSessionData);
   aSessionData->Timeout = TimeoutEdit->AsInteger;
 
   if (IPv4Button->Checked)
@@ -665,6 +673,27 @@ void __fastcall TLoginDialog::SaveSession(TSessionData * aSessionData)
   }
 }
 //---------------------------------------------------------------------
+void __fastcall TLoginDialog::SavePing(TSessionData * aSessionData)
+{
+  TPingType PingType;
+  if (PingNullPacketButton->Checked)
+  {
+    PingType = ptNullPacket;
+  }
+  else if (PingDummyCommandButton->Checked)
+  {
+    PingType = ptDummyCommand;
+  }
+  else
+  {
+    PingType = ptOff;
+  }
+  (FFSProtocol == fsFTP ? aSessionData->FtpPingType : aSessionData->PingType) =
+    PingType;
+  (FFSProtocol == fsFTP ? aSessionData->FtpPingInterval : aSessionData->PingInterval) =
+    PingIntervalSecEdit->AsInteger;
+}
+//---------------------------------------------------------------------
 void __fastcall TLoginDialog::UpdateNavigationTree()
 {
   TTreeNode * ActiveNode = NULL;
@@ -1026,10 +1055,7 @@ void __fastcall TLoginDialog::SessionListViewDblClick(TObject * /*Sender*/)
       else
     {
       SessionData = SelectedSession;
-      ChangePage(BasicSheet);
-      if (HostNameEdit->Text.IsEmpty()) HostNameEdit->SetFocus();
-        else
-      assert(false);
+      EditSession();
     }
   }
 }
@@ -1085,12 +1111,18 @@ void __fastcall TLoginDialog::SessionListViewKeyDown(TObject * /*Sender*/,
   }
 }
 //---------------------------------------------------------------------------
+void __fastcall TLoginDialog::EditSession()
+{
+  ChangePage(BasicSheet);
+  HostNameEdit->SetFocus();
+}
+//---------------------------------------------------------------------------
 void __fastcall TLoginDialog::EditSessionActionExecute(TObject * /*Sender*/)
 {
   if (SelectedSession)
   {
     SessionData = SelectedSession;
-    ChangePage(BasicSheet);
+    EditSession();
   }
 }
 //---------------------------------------------------------------------------
@@ -1110,6 +1142,7 @@ void __fastcall TLoginDialog::SaveSessionActionExecute(TObject * /*Sender*/)
       TSessionData *NewSession =
         StoredSessions->NewSession(SessionName, FSessionData);
       StoredSessions->Save();
+      SaveConfiguration();
       // by now list must contais same number of items or one less
       assert(StoredSessions->Count == SessionListView->Items->Count ||
         StoredSessions->Count == SessionListView->Items->Count+1);
@@ -1267,7 +1300,7 @@ void __fastcall TLoginDialog::ShowPreferencesDialog()
 void __fastcall TLoginDialog::NewSessionActionExecute(TObject * /*Sender*/)
 {
   Default();
-  ChangePage(BasicSheet);
+  EditSession();
 }
 //---------------------------------------------------------------------------
 void __fastcall TLoginDialog::NavigationTreeChange(TObject * /*Sender*/,
@@ -1829,12 +1862,13 @@ int __fastcall TLoginDialog::FSProtocolToIndex(TFSProtocol FSProtocol,
     AllowScpFallback = false;
     for (int Index = 0; Index < LENOF(FSOrder); Index++)
     {
-      if (FSOrder[Index] == FSProtocol)
+      if ((FSOrder[Index] == FSProtocol) &&
+          (Index < TransferProtocolCombo->Items->Count))
       {
         return Index;
       }
     }
-    assert(false);
+    // SFTP is always present
     return FSProtocolToIndex(fsSFTP, AllowScpFallback);
   }
 }
@@ -1860,9 +1894,13 @@ void __fastcall TLoginDialog::TransferProtocolComboChange(TObject * Sender)
 {
   if (!NoUpdate)
   {
-    TFSProtocol FSProtocol = IndexToFSProtocol(
+    SavePing(FSessionData);
+
+    FFSProtocol = IndexToFSProtocol(
       TransferProtocolCombo->ItemIndex, AllowScpFallbackCheck->Checked);
-    if (FSProtocol == fsFTP)
+
+    LoadPing(FSessionData);
+    if (FFSProtocol == fsFTP)
     {
       if (PortNumberEdit->AsInteger == 22)
       {

+ 6 - 6
forms/Login.dfm

@@ -1235,7 +1235,7 @@ object LoginDialog: TLoginDialog
             FocusControl = ProxyHostEdit
           end
           object ProxyPortLabel: TLabel
-            Left = 240
+            Left = 252
             Top = 41
             Width = 57
             Height = 13
@@ -1269,9 +1269,9 @@ object LoginDialog: TLoginDialog
             OnClick = DataChange
           end
           object ProxyPortEdit: TUpDownEdit
-            Left = 240
+            Left = 252
             Top = 58
-            Width = 94
+            Width = 82
             Height = 21
             Alignment = taRightJustify
             MaxValue = 65535
@@ -1283,7 +1283,7 @@ object LoginDialog: TLoginDialog
           object ProxyHostEdit: TEdit
             Left = 11
             Top = 58
-            Width = 214
+            Width = 226
             Height = 21
             Anchors = [akLeft, akTop, akRight]
             MaxLength = 50
@@ -1438,7 +1438,7 @@ object LoginDialog: TLoginDialog
           Height = 169
           Anchors = [akLeft, akTop, akRight]
           Caption = 'Host to setup tunnel on'
-          TabOrder = 0
+          TabOrder = 1
           DesignSize = (
             345
             169)
@@ -1550,7 +1550,7 @@ object LoginDialog: TLoginDialog
           Width = 307
           Height = 17
           Caption = '&Connect through SSH tunnel'
-          TabOrder = 1
+          TabOrder = 0
           OnClick = DataChange
         end
         object TunnelOptionsGroup: TGroupBox

+ 4 - 0
forms/Login.h

@@ -349,6 +349,7 @@ private:
   TColor FColor;
   AnsiString FBeforeDialogPath;
   TStringList * FTreeLabels;
+  TFSProtocol FFSProtocol;
 
   void __fastcall LoadSession(TSessionData * aSessionData);
   void __fastcall UpdateControls();
@@ -366,6 +367,8 @@ private:
   int __fastcall FSProtocolToIndex(TFSProtocol FSProtocol, bool & AllowScpFallback);
   TFSProtocol __fastcall IndexToFSProtocol(int Index, bool AllowScpFallback);
   void __fastcall UpdateNavigationTree();
+  void __fastcall LoadPing(TSessionData * aSessionData);
+  void __fastcall SavePing(TSessionData * aSessionData);
 
 protected:
   void __fastcall Default();
@@ -383,6 +386,7 @@ protected:
   void __fastcall InitControls();
   void __fastcall ShowTabs(bool Show);
   void __fastcall VerifyKey(AnsiString FileName, bool TypeOnly);
+  void __fastcall EditSession();
 
 public:
   virtual __fastcall TLoginDialog(TComponent* AOwner);

+ 0 - 2
forms/NonVisual.cpp

@@ -721,7 +721,6 @@ void __fastcall TNonVisualDataModule::ExplorerShortcuts()
   CurrentRenameAction->ShortCut = ShortCut(VK_F2, NONE);
   CurrentEditAction->ShortCut = ShortCut('E', CTRL);
   AddEditLinkAction->ShortCut = ShortCut('L', CTRLALT);
-  NewLinkAction->ShortCut = AddEditLinkAction->ShortCut;
   // Focused operation
   CurrentCopyFocusedAction->ShortCut = ShortCut('C', CTRL);
   CurrentMoveFocusedAction->ShortCut = ShortCut('M', CTRL);
@@ -761,7 +760,6 @@ void __fastcall TNonVisualDataModule::CommanderShortcuts()
   CurrentRenameAction->ShortCut = ShortCut(VK_F2, NONE);
   CurrentEditAction->ShortCut = ShortCut(VK_F4, NONE);
   AddEditLinkAction->ShortCut = ShortCut(VK_F6, ALT);
-  NewLinkAction->ShortCut = AddEditLinkAction->ShortCut;
   // Focused operation
   CurrentCopyFocusedAction->ShortCut = ShortCut(VK_F5, NONE);
   CurrentMoveFocusedAction->ShortCut = ShortCut(VK_F6, NONE);

+ 24 - 1
forms/Progress.cpp

@@ -42,12 +42,22 @@ __fastcall TProgressForm::TProgressForm(TComponent* AOwner)
   FReadOnly = false;
   FShowAsModalStorage = NULL;
   UseSystemSettings(this);
+  if (!IsGlobalMinimizeHandler())
+  {
+    SetGlobalMinimizeHandler(GlobalMinimize);
+  };
 }
 //---------------------------------------------------------------------------
 __fastcall TProgressForm::~TProgressForm()
 {
   // to prevent raising assertion (e.g. IsProgress == True)
   FData.Clear();
+
+  if (GetGlobalMinimizeHandler() == GlobalMinimize)
+  {
+    SetGlobalMinimizeHandler(NULL);
+  }
+
   if (IsIconic(Application->Handle) && FMinimizedByMe)
   {
     Application->Restore();
@@ -300,7 +310,15 @@ void __fastcall TProgressForm::CancelButtonClick(TObject * /*Sender*/)
 //---------------------------------------------------------------------------
 void __fastcall TProgressForm::MinimizeButtonClick(TObject * /*Sender*/)
 {
-  MinimizeApp();
+  TNotifyEvent OnMinimize = GetGlobalMinimizeHandler();
+  if (OnMinimize != NULL)
+  {
+    OnMinimize(this);
+  }
+  else
+  {
+    MinimizeApp();
+  }
 }
 //---------------------------------------------------------------------------
 void __fastcall TProgressForm::CancelOperation()
@@ -354,6 +372,11 @@ void __fastcall TProgressForm::MinimizeApp()
   FMinimizedByMe = true;
 }
 //---------------------------------------------------------------------------
+void __fastcall TProgressForm::GlobalMinimize(TObject * /*Sender*/)
+{
+  MinimizeApp();
+}
+//---------------------------------------------------------------------------
 void __fastcall TProgressForm::SetDisconnectWhenComplete(bool value)
 {
   DisconnectWhenCompleteCheck->Checked = value;

+ 1 - 0
forms/Progress.h

@@ -77,6 +77,7 @@ private:
   void __fastcall SetAllowMinimize(bool value);
   bool __fastcall GetAllowMinimize();
   void __fastcall SetReadOnly(bool value);
+  void __fastcall GlobalMinimize(TObject * Sender);
 
 protected:
   void __fastcall CancelOperation();

+ 20 - 0
forms/Synchronize.cpp

@@ -73,10 +73,20 @@ __fastcall TSynchronizeDialog::TSynchronizeDialog(TComponent * Owner,
 
   InstallPathWordBreakProc(LocalDirectoryEdit);
   InstallPathWordBreakProc(RemoteDirectoryEdit);
+
+  if (!IsGlobalMinimizeHandler())
+  {
+    SetGlobalMinimizeHandler(GlobalMinimize);
+  };
 }
 //---------------------------------------------------------------------------
 __fastcall TSynchronizeDialog::~TSynchronizeDialog()
 {
+  if (GetGlobalMinimizeHandler() == GlobalMinimize)
+  {
+    SetGlobalMinimizeHandler(NULL);
+  }
+
   delete FSynchronizeOptions;
   delete FPresetsMenu;
 }
@@ -369,6 +379,16 @@ void __fastcall TSynchronizeDialog::Stop()
 }
 //---------------------------------------------------------------------------
 void __fastcall TSynchronizeDialog::MinimizeButtonClick(TObject * /*Sender*/)
+{
+  MinimizeApp();
+}
+//---------------------------------------------------------------------------
+void __fastcall TSynchronizeDialog::GlobalMinimize(TObject * /*Sender*/)
+{
+  MinimizeApp();
+}
+//---------------------------------------------------------------------------
+void __fastcall TSynchronizeDialog::MinimizeApp()
 {
   Application->Minimize();
   FMinimizedByMe = true;

+ 2 - 0
forms/Synchronize.h

@@ -92,6 +92,8 @@ protected:
   void __fastcall ClearLog();
   void __fastcall CopyLog();
   int __fastcall ActualCopyParamAttrs();
+  void __fastcall GlobalMinimize(TObject * Sender);
+  void __fastcall MinimizeApp();
 
 public:
   __fastcall TSynchronizeDialog(TComponent * Owner,

+ 32 - 2
forms/SynchronizeProgress.cpp

@@ -31,17 +31,29 @@ __fastcall TSynchronizeProgressForm::TSynchronizeProgressForm(TComponent * Owner
       (MinimizeButton->Left - CancelButton->Left) / 2;
     MinimizeButton->Visible = false;
   }
+  else
+  {
+    if (!IsGlobalMinimizeHandler())
+    {
+      SetGlobalMinimizeHandler(GlobalMinimize);
+    };
+  }
 }
 //---------------------------------------------------------------------------
 __fastcall TSynchronizeProgressForm::~TSynchronizeProgressForm()
 {
+  if (GetGlobalMinimizeHandler() == GlobalMinimize)
+  {
+    SetGlobalMinimizeHandler(NULL);
+  }
+
+  ReleaseAsModal(this, FShowAsModalStorage);
+
   if (IsIconic(Application->Handle) && FMinimizedByMe)
   {
     Application->Restore();
     Application->BringToFront();
   }
-
-  ReleaseAsModal(this, FShowAsModalStorage);
 }
 //---------------------------------------------------------------------------
 void __fastcall TSynchronizeProgressForm::Start()
@@ -98,6 +110,24 @@ void __fastcall TSynchronizeProgressForm::UpdateTimerTimer(TObject * /*Sender*/)
 //---------------------------------------------------------------------------
 void __fastcall TSynchronizeProgressForm::MinimizeButtonClick(
   TObject * /*Sender*/)
+{
+  TNotifyEvent OnMinimize = GetGlobalMinimizeHandler();
+  if (OnMinimize != NULL)
+  {
+    OnMinimize(this);
+  }
+  else
+  {
+    MinimizeApp();
+  }
+}
+//---------------------------------------------------------------------------
+void __fastcall TSynchronizeProgressForm::GlobalMinimize(TObject * /*Sender*/)
+{
+  MinimizeApp();
+}
+//---------------------------------------------------------------------------
+void __fastcall TSynchronizeProgressForm::MinimizeApp()
 {
   Application->Minimize();
   FMinimizedByMe = true;

+ 2 - 0
forms/SynchronizeProgress.h

@@ -49,6 +49,8 @@ private:
   bool FCompareOnly;
 
   void __fastcall UpdateControls();
+  void __fastcall GlobalMinimize(TObject * Sender);
+  void __fastcall MinimizeApp();
 };
 //---------------------------------------------------------------------------
 #endif

+ 1 - 3
lib.bmk

@@ -30,7 +30,7 @@ OTHERFILES = %OTHERFILES%
 LINKER = %LINKER%
 DEBUGLIBPATH = %DEBUGLIBPATH%
 RELEASELIBPATH = %RELEASELIBPATH%
-USERDEFINES = %USERDEFINES%
+USERDEFINES = $(EXTERNALDEFINES)%USERDEFINES%
 SYSDEFINES = %SYSDEFINES%
 INCLUDEPATH = %INCLUDEPATH%
 LIBPATH = %LIBPATH%
@@ -221,5 +221,3 @@ $(PROJECT):  $(OTHERFILES) $(IDLGENFILES) $(OBJFILES) $(DEFFILE)
 # ---------------------------------------------------------------------------
 
 %FILES%
-
-

+ 17 - 6
makefile

@@ -3,7 +3,11 @@
 ROOT = $(MAKEDIR)\..
 !endif
 #------------------------------------------------------------------------------
-MAKE = $(ROOT)\bin\make.exe -$(MAKEFLAGS) -f$&.mak
+!ifdef NO_FILEZILLA
+EXTERNALDEFINES = NO_FILEZILLA;
+!endif
+#------------------------------------------------------------------------------
+MAKE = $(ROOT)\bin\make.exe -$(MAKEFLAGS) -DEXTERNALDEFINES=$(EXTERNALDEFINES) -f$&.mak
 BPR2MAK = $(ROOT)\bin\bpr2mak
 #------------------------------------------------------------------------------
 default: WinSCP.exe DragExt.dll WinSCP.com lib\DiscMon_B5.lib
@@ -13,28 +17,35 @@ WinSCP.exe: lib\Moje_B5.lib lib\DragDrop_B5.lib lib\DriveDir_B5.lib
 WinSCP.exe: lib\tb2k_cb6.lib lib\tbx_cb6.lib lib\ThemeManagerC6.lib
 WinSCP.exe: lib\Putty.lib lib\FileZilla.lib
 WinSCP.exe: lib\ScpCore.lib lib\RScpComp.lib lib\ScpForms.lib
- $(BPR2MAK) WinSCP.bpr
+ $(BPR2MAK) -tdefault.bmk WinSCP.bpr
  $(MAKE)
 
 DragExt.dll: DragExt.bpr
- $(BPR2MAK) DragExt.bpr
+ $(BPR2MAK) -tdefault.bmk DragExt.bpr
  $(MAKE)
 
 WinSCP.com: Console.com
  ren Console.com WinSCP.com
 
 Console.com: Console.bpr
- $(BPR2MAK) Console.bpr
+ $(BPR2MAK) -tdefault.bmk Console.bpr
  $(MAKE)
 
 {packages}.bpk{lib}.lib:
  cd packages
- $(BPR2MAK) $.
+ $(BPR2MAK) -t..\default.bmk $.
  $(MAKE)
  cd ..
 
+!ifdef NO_FILEZILLA
+lib\FileZilla.lib:
+ echo. > Fake.cpp
+ $(ROOT)\bin\bcc32 -c Fake.cpp
+ $(ROOT)\bin\tlib lib\FileZilla.lib +Fake.o
+!endif
+
 {}.bpk{lib}.lib:
- $(BPR2MAK) $.
+ $(BPR2MAK) -tdefault.bmk $.
  $(MAKE)
 
 {}.bpr{lib}.lib:

+ 0 - 27
packages/DiscMon_B5.bpk

@@ -55,33 +55,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=1
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

BIN
packages/DiscMon_B5.res


+ 0 - 27
packages/DragDrop_B5.bpk

@@ -72,33 +72,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=1
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

BIN
packages/DragDrop_B5.res


+ 0 - 27
packages/DriveDir_B5.bpk

@@ -84,33 +84,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=1
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

BIN
packages/DriveDir_B5.res


+ 0 - 27
packages/Moje_B5.bpk

@@ -78,33 +78,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=1
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

BIN
packages/Moje_B5.res


+ 0 - 27
packages/ThemeManagerC6.bpk

@@ -61,33 +61,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=1
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

BIN
packages/ThemeManagerC6.res


+ 0 - 27
packages/ThemeManagerC6D.bpk

@@ -58,33 +58,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

BIN
packages/ThemeManagerC6D.res


+ 0 - 27
packages/tb2k_cb6.bpk

@@ -65,33 +65,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1033
-CodePage=1252
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 27
packages/tb2kdsgn_cb6.bpk

@@ -64,33 +64,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1033
-CodePage=1252
-
-[Version Info Keys]
-CompanyName=
-FileDescription=
-FileVersion=1.0.0.0
-InternalName=
-LegalCopyright=
-LegalTrademarks=
-OriginalFilename=
-ProductName=
-ProductVersion=1.0.0.0
-Comments=
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 15
packages/tbx_cb6.bpk

@@ -70,21 +70,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1033
-CodePage=1252
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 0 - 15
packages/tbxdsgn_cb6.bpk

@@ -63,21 +63,6 @@
   </BUILDTOOLS>
 
   <IDEOPTIONS>
-[Version Info]
-IncludeVerInfo=0
-AutoIncBuild=0
-MajorVer=1
-MinorVer=0
-Release=0
-Build=0
-Debug=0
-PreRelease=0
-Special=0
-Private=0
-DLL=0
-Locale=1029
-CodePage=1250
-
 [Compiler]
 ShowInfoMsgs=0
 LinkDebugVcl=0

+ 4 - 2
readme

@@ -1,9 +1,11 @@
 This is the README file for source code package of WinSCP.
 
+To build full version of WinSCP you need Borland C++ Builder 6 Professional.
+You can build version without FTP support with Borland C++ Builder 6 Personal.
+
 To build WinSCP from source by yourself, type 'make' in root
 folder of source code package (directory where 'makefile' file resides).
-
-To build WinSCP you need Borland C++ Builder 6.
+To build version without FTP support, use 'make -DNO_FILEZILLA'.
 
 Directory structure:
 /            project files of all native libraries and executables

+ 1 - 1
release/winscp.isl

@@ -14,7 +14,7 @@ RegisterAsUrlHandler=Register to handle sftp:// and scp:// &addresses
 AddSearchPath=Add installation directory to &search path (%PATH%)
 EnableUpdates=Enable automatic &check for application updates (recommended)
 
-RegisteringAsUrlHandler=Registering to handle scp:// and sftp:// addresses
+RegisteringAsUrlHandler=Registering to handle sftp:// and scp:// addresses
 AddingSearchPath=Adding installation directory to search path (%PATH%)
 RemovingInvalidDefaultTranslation=Looking for obsolete default translation
 

+ 1 - 1
release/winscp.u3i

@@ -1,6 +1,6 @@
 <?xml version="1.0"?>
 <u3manifest version="1.0">
-  <application uuid="48b341d1-d411-4b5a-a82c-f3b5d65602fc" version="4.0">
+  <application uuid="48b341d1-d411-4b5a-a82c-f3b5d65602fc" version="4.0.1">
     <icon>winscp.ico</icon>
     <name>WinSCP</name>
     <description>Freeware SFTP (SSH File Transfer Protocol), FTP (File Transfer Protocol) and SCP (Secure CoPy) client for Windows using SSH (Secure SHell). Its main function is safe copying of files between a local and a remote computer.</description>

+ 1 - 0
release/winscpsetup.iss

@@ -184,6 +184,7 @@ Name: "{sendto}\{cm:SendToHookNew}"; Filename: "{app}\WinSCP.exe"; \
   Parameters: "/upload"; Tasks: sendtohook
 
 [InstallDelete]
+; Legacy sendto hook (SCP-only), only english link is removed
 Type: files; Name: "{sendto}\WinSCP3 (upload using SCP).lnk"
 Type: files; Name: "{group}\{cm:RSAKeyTools}\{cm:KeysManual}.lnk"
 Type: files; Name: "{app}\{cm:SupportForum}.url"

+ 26 - 26
resource/LicencePuTTY.txt

@@ -1,26 +1,26 @@
-PuTTY
-PuTTY is copyright 1997-2005 Simon Tatham.
-
-Portions copyright Robert de Bath, Joris van Rantwijk, Delian
-Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas Barry,
-Justin Bradford, Ben Harris, Malcolm Smith, Markus Kuhn, and
-CORE SDI S.A.
-
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation files
-(the "Software"), to deal in the Software without restriction,
-including without limitation the rights to use, copy, modify, merge,
-publish, distribute, sublicense, and/or sell copies of the Software,
-and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
-FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+PuTTY
+PuTTY is copyright 1997-2005 Simon Tatham.
+
+Portions copyright Robert de Bath, Joris van Rantwijk, Delian
+Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas Barry,
+Justin Bradford, Ben Harris, Malcolm Smith, Markus Kuhn, and
+CORE SDI S.A.
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation files
+(the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 1 - 0
resource/TextsCore.h

@@ -183,6 +183,7 @@
 #define FTP_ACCESS_DENIED       256
 #define FTP_CREDENTIAL_PROMPT   257
 #define FTP_PWD_RESPONSE_ERROR  258
+#define FTP_UNSUPPORTED         259
 
 #define CORE_CONFIRMATION_STRINGS 300
 #define CONFIRM_PROLONG_TIMEOUT2 301

+ 2 - 1
resource/TextsCore1.rc

@@ -156,6 +156,7 @@ BEGIN
   FTP_ACCESS_DENIED, "Access denied."
   FTP_CREDENTIAL_PROMPT, "Prompting for credentials..."
   FTP_PWD_RESPONSE_ERROR, "Invalid response to PWD command '%s'."
+  FTP_UNSUPPORTED, "This version does not support FTP protocol."
 
   CORE_CONFIRMATION_STRINGS, "CORE_CONFIRMATION"
   CONFIRM_PROLONG_TIMEOUT2, "Host has not answered for %d seconds.\n\nWait for another %0:d seconds?"
@@ -287,7 +288,7 @@ BEGIN
   PUTTY_COPYRIGHT, "Copyright © 1997-2005 Simon Tatham"
   PUTTY_URL, "http://www.chiark.greenend.org.uk/~sgtatham/putty/"
   FILEZILLA_BASED_ON, "FTP code based on FileZilla %s"
-  FILEZILLA_VERSION, "2.2.31"
+  FILEZILLA_VERSION, "2.2.32"
   FILEZILLA_COPYRIGHT, "Copyright © 2001-2007 Tim Kosse"
   FILEZILLA_URL, "http://filezilla.sourceforge.net/"
 END

+ 12 - 12
windows/GUIConfiguration.cpp

@@ -748,11 +748,11 @@ void __fastcall TGUIConfiguration::Saved()
 }
 //---------------------------------------------------------------------------
 //---------------------------------------------------------------------------
-HANDLE __fastcall TGUIConfiguration::LoadNewResourceModule(LCID ALocale,
+HINSTANCE __fastcall TGUIConfiguration::LoadNewResourceModule(LCID ALocale,
   AnsiString * FileName)
 {
   AnsiString LibraryFileName;
-  HANDLE NewInstance = 0;
+  HINSTANCE NewInstance = 0;
   bool Internal = (ALocale == InternalLocale());
   if (!Internal)
   {
@@ -842,7 +842,7 @@ void __fastcall TGUIConfiguration::SetLocale(LCID value)
 {
   if (Locale != value)
   {
-    HANDLE Module = LoadNewResourceModule(value);
+    HINSTANCE Module = LoadNewResourceModule(value);
     if (Module != NULL)
     {
       FLocale = value;
@@ -859,7 +859,7 @@ void __fastcall TGUIConfiguration::SetLocaleSafe(LCID value)
 {
   if (Locale != value)
   {
-    HANDLE Module;
+    HINSTANCE Module;
 
     try
     {
@@ -879,36 +879,36 @@ void __fastcall TGUIConfiguration::SetLocaleSafe(LCID value)
   }
 }
 //---------------------------------------------------------------------------
-void __fastcall TGUIConfiguration::FreeResourceModule(HANDLE Instance)
+void __fastcall TGUIConfiguration::FreeResourceModule(HINSTANCE Instance)
 {
   TPasLibModule * MainModule = FindModule(HInstance);
   if (Instance != MainModule->Instance)
   {
-    FreeLibrary(static_cast<HMODULE>(Instance));
+    FreeLibrary(Instance);
   }
 }
 //---------------------------------------------------------------------------
-HANDLE __fastcall TGUIConfiguration::ChangeResourceModule(HANDLE Instance)
+HINSTANCE __fastcall TGUIConfiguration::ChangeResourceModule(HINSTANCE Instance)
 {
   if (Instance == NULL)
   {
     Instance = HInstance;
   }
   TPasLibModule * MainModule = FindModule(HInstance);
-  HANDLE Result = MainModule->ResInstance;
+  HINSTANCE Result = static_cast<HINSTANCE>(MainModule->ResInstance);
   MainModule->ResInstance = Instance;
   CoreSetResourceModule(Instance);
   return Result;
 }
 //---------------------------------------------------------------------------
-HANDLE __fastcall TGUIConfiguration::GetResourceModule()
+HINSTANCE __fastcall TGUIConfiguration::GetResourceModule()
 {
-  return FindModule(HInstance)->ResInstance;
+  return static_cast<HINSTANCE>(FindModule(HInstance)->ResInstance);
 }
 //---------------------------------------------------------------------------
-void __fastcall TGUIConfiguration::SetResourceModule(HANDLE Instance)
+void __fastcall TGUIConfiguration::SetResourceModule(HINSTANCE Instance)
 {
-  HANDLE PrevHandle = ChangeResourceModule(Instance);
+  HINSTANCE PrevHandle = ChangeResourceModule(Instance);
   FreeResourceModule(PrevHandle);
 
   DefaultLocalized();

+ 5 - 5
windows/GUIConfiguration.h

@@ -184,13 +184,13 @@ protected:
   virtual LCID __fastcall GetLocale();
   void __fastcall SetLocale(LCID value);
   void __fastcall SetLocaleSafe(LCID value);
-  virtual HANDLE __fastcall LoadNewResourceModule(LCID Locale,
+  virtual HINSTANCE __fastcall LoadNewResourceModule(LCID Locale,
     AnsiString * FileName = NULL);
-  HANDLE __fastcall GetResourceModule();
-  virtual void __fastcall SetResourceModule(HANDLE Instance);
+  HINSTANCE __fastcall GetResourceModule();
+  virtual void __fastcall SetResourceModule(HINSTANCE Instance);
   TStrings * __fastcall GetLocales();
   LCID __fastcall InternalLocale();
-  void __fastcall FreeResourceModule(HANDLE Instance);
+  void __fastcall FreeResourceModule(HINSTANCE Instance);
   void __fastcall SetDefaultCopyParam(const TGUICopyParamType & value);
   virtual bool __fastcall GetRememberPassword();
   const TCopyParamList * __fastcall GetCopyParamList();
@@ -210,7 +210,7 @@ public:
   virtual __fastcall ~TGUIConfiguration();
   virtual void __fastcall Default();
 
-  HANDLE __fastcall ChangeResourceModule(HANDLE Instance);
+  HINSTANCE __fastcall ChangeResourceModule(HINSTANCE Instance);
 
   __property bool CopyParamDialogExpanded = { read = FCopyParamDialogExpanded, write = FCopyParamDialogExpanded };
   __property bool ErrorDialogExpanded = { read = FErrorDialogExpanded, write = FErrorDialogExpanded };

+ 24 - 14
windows/TerminalManager.cpp

@@ -639,8 +639,13 @@ void __fastcall TTerminalManager::ApplicationShowHint(AnsiString & HintStr,
 //---------------------------------------------------------------------------
 void __fastcall TTerminalManager::ApplicationActivate(TObject * /*Sender*/)
 {
-  // make sure the taskbar button is pressed
-  SetActiveWindow(Application->Handle);
+  // make sure the taskbar button of main window is pressed
+  // (but only if main window is our application focused window,
+  // note that there can also be an editor window)
+  if ((ScpExplorer != NULL) && (Screen->ActiveForm == ScpExplorer))
+  {
+    SetActiveWindow(Application->Handle);
+  }
 }
 //---------------------------------------------------------------------------
 void __fastcall TTerminalManager::DeleteLocalFile(const AnsiString FileName)
@@ -708,15 +713,6 @@ void __fastcall TTerminalManager::TerminalPromptUser(
     {
       AuthenticateForm = new TAuthenticateForm(Application,
         Terminal->SessionData->SessionName);
-      // when opening session, keep the form opened afterwards
-      // (the form is initiated by prompt for FTP sesiones, where username is not
-      // specified on login dialog)
-      if (Terminal->Status == ssOpening)
-      {
-        FAuthenticateForm = AuthenticateForm;
-        // see TerminalInformation
-        Busy(true);
-      }
     }
 
     try
@@ -1024,9 +1020,23 @@ bool __fastcall TTerminalManager::CanOpenInPutty()
 //---------------------------------------------------------------------------
 void __fastcall TTerminalManager::OpenInPutty()
 {
-  assert(ActiveTerminal != NULL);
-  OpenSessionInPutty(GUIConfiguration->PuttyPath, ActiveTerminal->SessionData,
-    GUIConfiguration->PuttyPassword ? ActiveTerminal->Password : AnsiString());
+  TSessionData * Data = new TSessionData("");
+  try
+  {
+    Data->Assign(ActiveTerminal->SessionData);
+    if (ActiveTerminal->TunnelLocalPortNumber != 0)
+    {
+      Data->ConfigureTunnel(ActiveTerminal->TunnelLocalPortNumber);
+    }
+
+    assert(ActiveTerminal != NULL);
+    OpenSessionInPutty(GUIConfiguration->PuttyPath, Data,
+      GUIConfiguration->PuttyPassword ? ActiveTerminal->Password : AnsiString());
+  }
+  __finally
+  {
+    delete Data;
+  }
 }
 //---------------------------------------------------------------------------
 bool __fastcall TTerminalManager::NewSession()

+ 56 - 41
windows/UserInterface.cpp

@@ -342,56 +342,71 @@ void __fastcall AddMenuSeparator(TTBCustomItem * Menu)
 void __fastcall MenuPopup(TPopupMenu * AMenu, TPoint Point,
   TComponent * PopupComponent)
 {
-  TTBXPopupMenu * Menu = reinterpret_cast<TTBXPopupMenu *>(AMenu->Tag);
-  delete Menu;
+  static TComponent * LastPopupComponent = NULL;
+  static TDateTime LastCloseUp;
 
-  Menu = CreateTBXPopupMenu(AMenu->Owner);
-  Menu->OnPopup = AMenu->OnPopup;
-  Menu->Items->SubMenuImages = AMenu->Images;
-  AMenu->Tag = reinterpret_cast<int>(Menu);
-
-  for (int Index = 0; Index < AMenu->Items->Count; Index++)
+  // pressing the same button within 200ms after closing its popup menu
+  // does nothing.
+  // it is to immitate close-by-click behaviour. note that menu closes itself
+  // before onclick handler of button occurs
+  if ((PopupComponent == LastPopupComponent) &&
+      (Now() - LastCloseUp < TDateTime(0, 0, 0, 200)))
   {
-    TMenuItem * AItem = AMenu->Items->Items[Index];
-    TTBCustomItem * Item;
-
-    // recurse not implemented yet
-    assert(AItem->Count == 0);
+    LastPopupComponent = NULL;
+  }
+  else
+  {
+    TTBXPopupMenu * Menu = Menu = CreateTBXPopupMenu(AMenu->Owner);
+    Menu->OnPopup = AMenu->OnPopup;
+    Menu->Items->SubMenuImages = AMenu->Images;
 
-    // see TB2DsgnConverter.pas DoConvert
-    if (AItem->Caption == "-")
+    for (int Index = 0; Index < AMenu->Items->Count; Index++)
     {
-      Item = new TTBXSeparatorItem(Menu);
-    }
-    else
-    {
-      Item = new TTBXItem(Menu);
-      Item->Action = AItem->Action;
-      Item->AutoCheck = AItem->AutoCheck;
-      Item->Caption = AItem->Caption;
-      Item->Checked = AItem->Checked;
-      if (AItem->Default)
+      TMenuItem * AItem = AMenu->Items->Items[Index];
+      TTBCustomItem * Item;
+
+      // recurse not implemented yet
+      assert(AItem->Count == 0);
+
+      // see TB2DsgnConverter.pas DoConvert
+      if (AItem->Caption == "-")
+      {
+        Item = new TTBXSeparatorItem(Menu);
+      }
+      else
       {
-        Item->Options = Item->Options << tboDefault;
+        Item = new TTBXItem(Menu);
+        Item->Action = AItem->Action;
+        Item->AutoCheck = AItem->AutoCheck;
+        Item->Caption = AItem->Caption;
+        Item->Checked = AItem->Checked;
+        if (AItem->Default)
+        {
+          Item->Options = Item->Options << tboDefault;
+        }
+        Item->Enabled = AItem->Enabled;
+        Item->GroupIndex = AItem->GroupIndex;
+        Item->HelpContext = AItem->HelpContext;
+        Item->ImageIndex = AItem->ImageIndex;
+        Item->RadioItem = AItem->RadioItem;
+        Item->ShortCut = AItem->ShortCut;
+        Item->SubMenuImages = AItem->SubMenuImages;
+        Item->OnClick = AItem->OnClick;
       }
-      Item->Enabled = AItem->Enabled;
-      Item->GroupIndex = AItem->GroupIndex;
-      Item->HelpContext = AItem->HelpContext;
-      Item->ImageIndex = AItem->ImageIndex;
-      Item->RadioItem = AItem->RadioItem;
-      Item->ShortCut = AItem->ShortCut;
-      Item->SubMenuImages = AItem->SubMenuImages;
-      Item->OnClick = AItem->OnClick;
+      Item->Hint = AItem->Hint;
+      Item->Tag = AItem->Tag;
+      Item->Visible = AItem->Visible;
+
+      Menu->Items->Add(Item);
     }
-    Item->Hint = AItem->Hint;
-    Item->Tag = AItem->Tag;
-    Item->Visible = AItem->Visible;
 
-    Menu->Items->Add(Item);
-  }
+    Menu->PopupComponent = PopupComponent;
+    Menu->Popup(Point.x, Point.y);
+    delete Menu;
 
-  Menu->PopupComponent = PopupComponent;
-  Menu->Popup(Point.x, Point.y);
+    LastPopupComponent = PopupComponent;
+    LastCloseUp = Now();
+  }
 }
 //---------------------------------------------------------------------------
 void __fastcall UpgradeSpeedButton(TSpeedButton * /*Button*/)

+ 3 - 3
windows/WinConfiguration.cpp

@@ -1441,7 +1441,7 @@ LCID __fastcall TWinConfiguration::GetLocale()
   return TCustomWinConfiguration::GetLocale();
 }
 //---------------------------------------------------------------------------
-HANDLE __fastcall TWinConfiguration::LoadNewResourceModule(LCID ALocale,
+HINSTANCE __fastcall TWinConfiguration::LoadNewResourceModule(LCID ALocale,
   AnsiString * FileName)
 {
   AnsiString FileNameStorage;
@@ -1450,7 +1450,7 @@ HANDLE __fastcall TWinConfiguration::LoadNewResourceModule(LCID ALocale,
     FileName = &FileNameStorage;
   }
 
-  HANDLE Instance = TCustomWinConfiguration::LoadNewResourceModule(ALocale, FileName);
+  HINSTANCE Instance = TCustomWinConfiguration::LoadNewResourceModule(ALocale, FileName);
   if (Instance != NULL)
   {
     try
@@ -1466,7 +1466,7 @@ HANDLE __fastcall TWinConfiguration::LoadNewResourceModule(LCID ALocale,
   return Instance;
 }
 //---------------------------------------------------------------------------
-void __fastcall TWinConfiguration::SetResourceModule(HANDLE Instance)
+void __fastcall TWinConfiguration::SetResourceModule(HINSTANCE Instance)
 {
   TCustomWinConfiguration::SetResourceModule(Instance);
 

+ 3 - 3
windows/WinConfiguration.h

@@ -354,12 +354,12 @@ protected:
   virtual void __fastcall Saved();
   bool __fastcall SameStringLists(TStrings * Strings1, TStrings * Strings2);
   bool __fastcall InternalReloadComponentRes(const AnsiString ResName,
-    HANDLE HInst, TComponent * Instance);
+    HINSTANCE HInst, TComponent * Instance);
   bool __fastcall InitComponent(TComponent * Instance,
     TClass RootAncestor, TClass ClassType);
-  virtual HANDLE __fastcall LoadNewResourceModule(LCID Locale,
+  virtual HINSTANCE __fastcall LoadNewResourceModule(LCID Locale,
     AnsiString * FileName = NULL);
-  virtual void __fastcall SetResourceModule(HANDLE Instance);
+  virtual void __fastcall SetResourceModule(HINSTANCE Instance);
   virtual LCID __fastcall GetLocale();
   void __fastcall CheckTranslationVersion(const AnsiString FileName,
     bool InternalLocaleOnError);

+ 16 - 0
windows/WinInterface.cpp

@@ -25,6 +25,7 @@
 //---------------------------------------------------------------------
 // initialize an instance
 TProgramParams ProgramParams;
+TNotifyEvent GlobalOnMinimize = NULL;
 //---------------------------------------------------------------------
 void __fastcall FormHelp(TForm * Form)
 {
@@ -806,6 +807,21 @@ void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Hand
   Handled = true;
 }
 //---------------------------------------------------------------------------
+void __fastcall SetGlobalMinimizeHandler(TNotifyEvent OnMinimize)
+{
+  GlobalOnMinimize = OnMinimize;
+}
+//---------------------------------------------------------------------------
+TNotifyEvent __fastcall GetGlobalMinimizeHandler()
+{
+  return GlobalOnMinimize;
+}
+//---------------------------------------------------------------------------
+bool __fastcall IsGlobalMinimizeHandler()
+{
+  return (GlobalOnMinimize != NULL);
+}
+//---------------------------------------------------------------------------
 struct TNotifyIconData5
 {
   DWORD cbSize;

+ 4 - 0
windows/WinInterface.h

@@ -337,6 +337,10 @@ void __fastcall MenuPopup(TObject * Sender, const TPoint & MousePos, bool & Hand
 
 void __fastcall UpgradeSpeedButton(TSpeedButton * Button);
 
+void __fastcall SetGlobalMinimizeHandler(TNotifyEvent OnMinimize);
+TNotifyEvent __fastcall GetGlobalMinimizeHandler();
+bool __fastcall IsGlobalMinimizeHandler();
+
 //---------------------------------------------------------------------------
 class TWinInteractiveCustomCommand : public TInteractiveCustomCommand
 {

+ 7 - 3
windows/WinMain.cpp

@@ -209,7 +209,7 @@ int __fastcall Execute()
   try
   {
     TerminalManager = TTerminalManager::Instance();
-    HANDLE ResourceModule = GUIConfiguration->ChangeResourceModule(NULL);
+    HINSTANCE ResourceModule = GUIConfiguration->ChangeResourceModule(NULL);
     try
     {
       GlyphsModule = new TGlyphsModule(Application);
@@ -384,8 +384,12 @@ int __fastcall Execute()
             {
               if (!TerminalManager->ConnectActiveTerminal())
               {
-                AutoStartSession = "";
-                Retry = true;
+                // do not prompt with login dialog, if connection of
+                // auto-start session (typically from command line) failed
+                if (AutoStartSession.IsEmpty())
+                {
+                  Retry = true;
+                }
               }
               else
               {