Skip to content

Added SFTP support to the current master branch code. Needs testing. #607

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion AutoUpdater.NET/AutoUpdater.NET.csproj
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@
<Version>1.7.7.0</Version>
<AssemblyVersion>1.7.7.0</AssemblyVersion>
<FileVersion>1.7.7.0</FileVersion>
<SignAssembly>true</SignAssembly>
<SignAssembly>False</SignAssembly>
<AssemblyOriginatorKeyFile>AutoUpdater.NET.snk</AssemblyOriginatorKeyFile>
<NeutralLanguage>en</NeutralLanguage>
<PackageId>Autoupdater.NET.Official</PackageId>
@@ -51,6 +51,11 @@
<PackageReference Include="Resource.Embedder" Version="1.2.8" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.1587.40" />
<PackageReference Include="SSH.NET" Version="2020.0.2" />
</ItemGroup>
</Project>
104 changes: 75 additions & 29 deletions AutoUpdater.NET/AutoUpdater.cs
Original file line number Diff line number Diff line change
@@ -151,6 +151,12 @@ public static class AutoUpdater
/// </summary>
public static bool ReportErrors = false;

///<summary>
/// AutoUpdater.NET will not show the 'No Update Available' dialog if
/// no update is available and this is true.
/// </summary>
public static bool SilentOnNoUpdate = false;

/// <summary>
/// Set this to false if your application doesn't need administrator privileges to replace the old version.
/// </summary>
@@ -258,8 +264,8 @@ public static void Start(string appCast, Assembly myAssembly = null)
{
try
{
ServicePointManager.SecurityProtocol |= (SecurityProtocolType) 192 |
(SecurityProtocolType) 768 | (SecurityProtocolType) 3072;
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)192 |
(SecurityProtocolType)768 | (SecurityProtocolType)3072;
}
catch (NotSupportedException)
{
@@ -331,9 +337,9 @@ public static void Start(string appCast, Assembly myAssembly = null)
return;
}
}

Running = false;
}

Running = false;
};

backgroundWorker.RunWorkerAsync(assembly);
@@ -345,13 +351,13 @@ public static void Start(string appCast, Assembly myAssembly = null)
private static object CheckUpdate(Assembly mainAssembly)
{
var companyAttribute =
(AssemblyCompanyAttribute) GetAttribute(mainAssembly, typeof(AssemblyCompanyAttribute));
(AssemblyCompanyAttribute)GetAttribute(mainAssembly, typeof(AssemblyCompanyAttribute));
string appCompany = companyAttribute != null ? companyAttribute.Company : "";

if (string.IsNullOrEmpty(AppTitle))
{
var titleAttribute =
(AssemblyTitleAttribute) GetAttribute(mainAssembly, typeof(AssemblyTitleAttribute));
(AssemblyTitleAttribute)GetAttribute(mainAssembly, typeof(AssemblyTitleAttribute));
AppTitle = titleAttribute != null ? titleAttribute.Title : mainAssembly.GetName().Name;
}

@@ -362,32 +368,40 @@ private static object CheckUpdate(Assembly mainAssembly)
PersistenceProvider ??= new RegistryPersistenceProvider(registryLocation);

BaseUri = new Uri(AppCastURL);
string xml = string.Empty;

switch (BaseUri.Scheme.ToLower())
{
case "sftp":
xml = GetUpdateXmlBySSHClient();
break;

default:
xml = GetUpdateXmlByWebClient();
break;
}

UpdateInfoEventArgs args;
using (MyWebClient client = GetWebClient(BaseUri, BasicAuthXML))

if (ParseUpdateInfoEvent == null)
{
string xml = client.DownloadString(BaseUri);

if (ParseUpdateInfoEvent == null)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UpdateInfoEventArgs));
XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml)) {XmlResolver = null};
args = (UpdateInfoEventArgs) xmlSerializer.Deserialize(xmlTextReader);
}
else
{
ParseUpdateInfoEventArgs parseArgs = new ParseUpdateInfoEventArgs(xml);
ParseUpdateInfoEvent(parseArgs);
args = parseArgs.UpdateInfo;
}
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UpdateInfoEventArgs));
XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml)) { XmlResolver = null };
args = (UpdateInfoEventArgs)xmlSerializer.Deserialize(xmlTextReader);
}
else
{
ParseUpdateInfoEventArgs parseArgs = new ParseUpdateInfoEventArgs(xml);
ParseUpdateInfoEvent(parseArgs);
args = parseArgs.UpdateInfo;
}

if (string.IsNullOrEmpty(args?.CurrentVersion) || string.IsNullOrEmpty(args.DownloadURL))
{
throw new MissingFieldException();
}

args.InstalledVersion = InstalledVersion ?? mainAssembly.GetName().Version;
args.InstalledVersion = InstalledVersion != null ? InstalledVersion : mainAssembly.GetName().Version;
args.IsUpdateAvailable = new Version(args.CurrentVersion) > args.InstalledVersion;

if (!Mandatory)
@@ -434,10 +448,34 @@ private static object CheckUpdate(Assembly mainAssembly)
}
}
}

return args;
}

private static string GetUpdateXmlBySSHClient()
{
string xml = string.Empty;
string host = BaseUri.Host;

MySSHClient client = new MySSHClient(
host: host, userName: FtpCredentials.UserName,
password: FtpCredentials.Password);

xml = client.GetFileContentAsString(BaseUri.AbsolutePath);

return xml;
}

private static string GetUpdateXmlByWebClient()
{
string xml = string.Empty;

using (MyWebClient client = GetWebClient(BaseUri, BasicAuthXML))
{
xml = client.DownloadString(BaseUri);
}

return xml;
}
private static bool StartUpdate(object result)
{
if (result is DateTime time)
@@ -481,7 +519,7 @@ private static bool StartUpdate(object result)
return true;
}

if (ReportErrors)
if (ReportErrors && !SilentOnNoUpdate)
{
MessageBox.Show(Resources.UpdateUnavailableMessage,
Resources.UpdateUnavailableCaption,
@@ -498,7 +536,7 @@ private static void ShowError(Exception exception)
{
if (CheckForUpdateEvent != null)
{
CheckForUpdateEvent(new UpdateInfoEventArgs {Error = exception});
CheckForUpdateEvent(new UpdateInfoEventArgs { Error = exception });
}
else
{
@@ -518,8 +556,6 @@ private static void ShowError(Exception exception)
}
}
}

Running = false;
}

/// <summary>
@@ -547,7 +583,7 @@ internal static void Exit()
{
if (process.CloseMainWindow())
{
process.WaitForExit((int) TimeSpan.FromSeconds(10)
process.WaitForExit((int)TimeSpan.FromSeconds(10)
.TotalMilliseconds); //give some time to process message
}

@@ -589,7 +625,7 @@ private static Attribute GetAttribute(Assembly assembly, Type attributeType)
return null;
}

return (Attribute) attributes[0];
return (Attribute)attributes[0];
}

internal static string GetUserAgent()
@@ -695,5 +731,15 @@ internal static MyWebClient GetWebClient(Uri uri, IAuthentication basicAuthentic

return webClient;
}

internal static MySSHClient GetSSHClient(Uri uri, IAuthentication basicAuthentication)
{
MySSHClient sshClient = new MySSHClient(
host: uri.Host,
userName: FtpCredentials.UserName,
password: FtpCredentials.Password);

return sshClient;
}
}
}
34 changes: 34 additions & 0 deletions AutoUpdater.NET/DownloadProgressChangedEventArgs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.ComponentModel;

namespace AutoUpdaterDotNET
{
//
// Summary:
// Provides data for the SSH client DownloadProgressChanged event.
public class DownloadProgressChangedEventArgs : ProgressChangedEventArgs
{
public DownloadProgressChangedEventArgs(long bytesReceived, long totalBytesToReceive,
int progressPercentage, object userState)
: base(progressPercentage, userState)
{
BytesReceived = bytesReceived;
TotalBytesToReceive = totalBytesToReceive;
}


//
// Summary:
// Gets the number of bytes received.
//
// Returns:
// An System.Int64 value that indicates the number of bytes received.
public long BytesReceived { get; }
//
// Summary:
// Gets the total number of bytes in a System.Net.WebClient data download operation.
//
// Returns:
// An System.Int64 value that indicates the number of bytes that will be received.
public long TotalBytesToReceive { get; }
}
}
23 changes: 23 additions & 0 deletions AutoUpdater.NET/FileDownloadClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdaterDotNET
{
public abstract class FileDownloadClient : IFileDownloadClient
{
/// <summary>
/// The required constructor for the class.
/// </summary>
/// <param name="type"></param>
public FileDownloadClient(FileDownloadClientType type)
{
this.Type = type;
}


public virtual FileDownloadClientType Type { get; private set; }


}
}
30 changes: 30 additions & 0 deletions AutoUpdater.NET/FileDownloadClientType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdaterDotNET
{
/// <summary>
/// Identifies the type of download client required to retrieve the
/// update file, i.e. WebClient, SFTP, etc.
/// </summary>
public enum FileDownloadClientType
{
/// <summary>
/// The type of client to use is unknown.
/// </summary>
Unspecified = 0,

/// <summary>
/// The update process will use the Web Client for
/// a traditional HTTP(S) file download.
/// </summary>
WebClient = 1,

/// <summary>
/// The update process will use an SSH client to connect
/// to a secure FTP site that is hosting the update file.
/// </summary>
SFTPClient = 2
}
}
13 changes: 13 additions & 0 deletions AutoUpdater.NET/IFileDownloadClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdaterDotNET
{
public interface IFileDownloadClient
{
FileDownloadClientType Type { get; }


}
}
130 changes: 130 additions & 0 deletions AutoUpdater.NET/MySSHClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
using Renci.SshNet;
using Renci.SshNet.Sftp;
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoUpdaterDotNET
{
public class MySSHClient
{
private string _Host;
private int _Port;
private string _UserName;
private string _Password;

public Action<object, DownloadProgressChangedEventArgs> DownloadProgressChanged { get; internal set; }

public AsyncCompletedEventHandler DownloadFileCompleted;

public MySSHClient(string host, string userName, string password, int port = 22)
{
_Host = host;
_Port = port;
_UserName = userName;
_Password = password;
}

public byte[] GetFileContent(string remoteFilePath)
{
var tempFile = Path.GetTempFileName();
using var client = new SftpClient(_Host, _Port <= 0 ? 22 : _Port, _UserName, _Password);

try
{
client.Connect();

using (var stream = File.Create(tempFile))
{
client.DownloadFile(remoteFilePath, stream);
}

if (!File.Exists(tempFile))
{
throw new Exception("The temporary file could not be written.");
}

FileInfo fileInfo = new FileInfo(tempFile);
if (fileInfo.Length == 0)
{
throw new Exception("The file is zero bytes.");
}

return File.ReadAllBytes(tempFile);
}
catch (Exception exception)
{
// _logger.LogError(exception, $"Failed in downloading to file [{tempFile}] from [{remoteFilePath}]");
throw;
}
finally
{
client.Disconnect();

if (File.Exists(tempFile))
File.Delete(tempFile);
}

return null;
}

public string GetFileContentAsString(string remoteFilePath, Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding.UTF8;

var bytes = GetFileContent(remoteFilePath);
return encoding.GetString(bytes);
}

public void DownloadFile(Uri uri, string destination)
{
string remoteFilePath = uri.AbsolutePath;

using (var client = new SftpClient(_Host, _Port <= 0 ? 22 : _Port, _UserName, _Password))
{
try
{
client.Connect();
RemoteFileName = uri.Segments.Last();
RemoteFileInfo = client.GetAttributes(remoteFilePath);

using (var saveFile = File.OpenWrite(destination))
{
client.DownloadFile(remoteFilePath, saveFile, OnDownloadProgressChanged);
}

DownloadFileCompleted.Invoke(null,
new AsyncCompletedEventArgs(null, false, destination));
}
catch (Exception ex)
{
DownloadFileCompleted.Invoke(null, new AsyncCompletedEventArgs(ex, false, null));
}
finally
{
client.Disconnect();
}
}
}

private string RemoteFileName { get; set; }

private SftpFileAttributes RemoteFileInfo { get; set; }

private void OnDownloadProgressChanged(ulong bytesReceived)
{
int percent = (int)bytesReceived / (int)RemoteFileInfo.Size;
var args = new DownloadProgressChangedEventArgs(
(long)bytesReceived,
RemoteFileInfo.Size,
percent,
new { Name = RemoteFileName, Info = RemoteFileInfo });

DownloadProgressChanged.Invoke(null, args);
}
}
}
16 changes: 16 additions & 0 deletions AutoUpdater.NET/MyWebClient.cs
Original file line number Diff line number Diff line change
@@ -6,6 +6,8 @@ namespace AutoUpdaterDotNET
/// <inheritdoc />
public class MyWebClient : WebClient
{
public event EventHandler<DownloadProgressChangedEventArgs> DownloadProgressChanged;

/// <summary>
/// Response Uri after any redirects.
/// </summary>
@@ -18,5 +20,19 @@ protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult r
ResponseUri = webResponse.ResponseUri;
return webResponse;
}

protected override void OnDownloadProgressChanged(System.Net.DownloadProgressChangedEventArgs e)
{
EventHandler<DownloadProgressChangedEventArgs> handler = DownloadProgressChanged;
if (handler != null)
{
handler(this, new DownloadProgressChangedEventArgs(
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage,
e.UserState));
}
// base.OnDownloadProgressChanged(e);
}
}
}
24 changes: 24 additions & 0 deletions AutoUpdater.NET/SFTPFileDownloadClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdaterDotNET
{
public class SFTPFileDownloadClient : FileDownloadClient
{
private MySSHClient sshClient;

public SFTPFileDownloadClient(MySSHClient client) : base(FileDownloadClientType.SFTPClient)
{
this.sshClient = client;
}

public SFTPFileDownloadClient(string host, string userName, string password, int port = 22) : base(FileDownloadClientType.SFTPClient)
{
sshClient = new MySSHClient(host, userName, password, port);
}



}
}
4 changes: 2 additions & 2 deletions AutoUpdaterTest/AutoUpdaterTest.csproj
Original file line number Diff line number Diff line change
@@ -39,8 +39,8 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
44 changes: 30 additions & 14 deletions AutoUpdaterTest/FormMain.Designer.cs
26 changes: 25 additions & 1 deletion AutoUpdaterTest/FormMain.cs
Original file line number Diff line number Diff line change
@@ -233,7 +233,7 @@ private void AutoUpdaterOnCheckForUpdateEvent(UpdateInfoEventArgs args)
}
}

private void ButtonCheckForUpdate_Click(object sender, EventArgs e)
private void ButtonCheckForUpdateViaHttp_Click(object sender, EventArgs e)
{
//Uncomment below lines to select download path where update is saved.

@@ -248,5 +248,29 @@ private void ButtonCheckForUpdate_Click(object sender, EventArgs e)
AutoUpdater.ClearAppDirectory = false;
AutoUpdater.Start("https://rbsoft.org/updates/AutoUpdaterTest.xml");
}

private void buttonCheckForUpdateViaSftp_Click(object sender, EventArgs e)
{
//Uncomment below lines to select download path where update is saved.

//FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
//if (folderBrowserDialog.ShowDialog().Equals(DialogResult.OK))
//{
// AutoUpdater.DownloadPath = folderBrowserDialog.SelectedPath;
// AutoUpdater.Mandatory = true;
// AutoUpdater.Start("https://rbsoft.org/updates/AutoUpdaterTest.xml");
//}

AutoUpdater.Mandatory = true;
//AutoUpdater.Start("https://rbsoft.org/updates/AutoUpdaterTest.xml");

// SFTP test
AutoUpdater.Synchronous = false;
AutoUpdater.Start(
appCast: "sftp://files.mydomain.com/AutoUpdaterTest.xml",
ftpCredentials: new NetworkCredential(
userName: "some-username",
password: "VRF1peB9f^2V6%LCMTToFc"));
}
}
}
2 changes: 1 addition & 1 deletion AutoUpdaterTest/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net462" />
<package id="Newtonsoft.Json" version="13.0.2" targetFramework="net462" />
</packages>
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -115,6 +115,14 @@ AutoUpdater.Start("ftp://rbsoft.org/updates/AutoUpdaterTest.xml", new NetworkCre

If you are using FTP download URL in the XML file then credentials provided here will be used to authenticate the request.

### Download Update file and XML using SFTP (FTP over SSH)

Using an SFTP server for your XML file is also supported. Simply provide the URL to your SFTP server along with the credentials required to access it securely as shown below.

````csharp
AutoUpdater.Start("sftp://securefiles.rbsoft.org/updates/AutoUpdaterTest.xml", new NetworkCredential("SftpUserName", "SftpPassword"));
````

### Check for updates synchronously

If you want to check for updates synchronously then set Synchronous to true before starting the update as shown below.
8 changes: 7 additions & 1 deletion ZipExtractor/ZipExtractor.csproj
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@
<ApplicationVersion>1.3.2.0</ApplicationVersion>
<ApplicationIcon>ZipExtractor.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<SignAssembly>true</SignAssembly>
<SignAssembly>False</SignAssembly>
<AssemblyOriginatorKeyFile>ZipExtractor.snk</AssemblyOriginatorKeyFile>
<NeutralLanguage>en</NeutralLanguage>
<LangVersion>default</LangVersion>
@@ -44,6 +44,12 @@
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Windows.Forms" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Settings.Designer.cs">
<DesignTimeSharedInput>True</DesignTimeSharedInput>