checking in all the old panacean stuff

This commit is contained in:
2016-07-25 15:42:39 -04:00
parent c996cdd81f
commit 8fd9e44ae5
1210 changed files with 220657 additions and 0 deletions

View File

@@ -0,0 +1,930 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2010. IntelliProtector.com
// Web site: http://intelliprotector.com
// Version: v2.5
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace netprotector.api
{
internal delegate void dVoid_NoParams();
internal delegate void dVoid_BoolParam(out bool b1);
internal delegate void dVoid_IntParam(out int i1);
internal delegate void dVoid_2IntParam(out int i1, int i2);
internal delegate void dVoid_5IntParams(out int i1, out int i2, out int i3, out int i4, out int i5);
internal delegate void dVoid_StringBuilderParam([MarshalAs(UnmanagedType.LPWStr)] StringBuilder s1, int iMaxLength);
internal delegate void dBool_StringParam(out bool res, [MarshalAs(UnmanagedType.LPWStr)]String s1, int iMaxLength);
internal delegate void dBool_StringOnlyParam(out bool res, [MarshalAs(UnmanagedType.LPWStr)]String s1);
internal delegate void dBool_StringStringParam(out bool res, [MarshalAs(UnmanagedType.LPWStr)]String s1, [MarshalAs(UnmanagedType.LPWStr)]String s2);
}
namespace IntelliProtectorService.attributes
{
internal class Encrypt : Attribute { }
internal class GetBuyNowLinkAttribute : Attribute { }
internal class IsSoftwareProtectedAttribute : Attribute { }
internal class IsSoftwareRegisteredAttribute : Attribute { }
internal class GetTrialDaysCountAttribute : Attribute { }
internal class GetTrialUnitsCountAttribute : Attribute { }
internal class GetTrialDaysLeftCountAttribute : Attribute { }
internal class GetTrialUnitsLeftCountAttribute : Attribute { }
internal class GetTrialLaunchesCountAttribute : Attribute { }
internal class GetTrialLaunchesLeftCountAttribute : Attribute { }
internal class ShowRegistrationWindowAttribute : Attribute { }
internal class IsTrialElapsedAttribute : Attribute { }
internal class GetRenewalPurchaseLinkAttribute : Attribute { }
internal class GetLicenseTypeAttribute : Attribute { }
internal class GetLicenseExpirationDaysCountAttribute : Attribute { }
internal class GetLicenseExpirationDaysLeftCountAttribute : Attribute { }
internal class GetSupportExpirationDaysCountAttribute : Attribute { }
internal class GetSupportExpirationDaysLeftCountAttribute : Attribute { }
internal class GetCurrentProductVersionAttribute : Attribute { }
internal class GetCustomerNameAttribute : Attribute { }
internal class GetCustomerEMailAttribute : Attribute { }
internal class GetLicenseCodeAttribute : Attribute { }
internal class RegisterSoftwareAttribute : Attribute { }
internal class RenewLicenseCodeAttribute : Attribute { }
internal class GetCurrentActivationDateAttribute : Attribute { }
internal class GetCurrentRegistrationDateAttribute : Attribute { }
internal class GetFirstRegistrationDateAttribute : Attribute { }
internal class GetOrderDateAttribute : Attribute { }
internal class GetLicenseExpirationDateAttribute : Attribute { }
internal class GetProtectionDateAttribute : Attribute { }
internal class GetSupportExpirationDateAttribute : Attribute { }
internal class GetSupportExpirationProductVersionAttribute : Attribute { }
internal class GetIntelliProtectorVersionAttribute : Attribute { }
internal class CreateRegistrationRequestCertificateAttribute : Attribute { }
internal class UseRegistrationResponseCertificateAttribute : Attribute { }
internal class SystemFunction1Attribute : Attribute { }
}
namespace IntelliProtectorService
{
internal class IntelliProtector
{
public static double Version_2_5()
{
return 2.5f;
}
#if DEBUG
public static bool IsInDebugMode()
{
return true;
}
#endif
public enum enUnitDimension
{
eudMinutes,
eudHours,
eudDays,
eudWeeks,
eudMonths
};
private class Init32
{
[DllImport("JitHookCore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Init")]
public static extern void Init();
};
private class Init64
{
[DllImport("JitHookCoreX64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Init")]
public static extern void Init();
};
public static bool Init()
{
try
{
bool tryLoadX64 = false;
try
{
Init32.Init();
}
catch (BadImageFormatException)
{
tryLoadX64 = true;
}
if (tryLoadX64)
{
try
{
Init64.Init();
}
catch (BadImageFormatException)
{
return false;
}
}
return true;
}
catch (System.Exception)
{
return false;
}
}
#region GetBuyNowLink
[attributes.GetBuyNowLinkAttribute]
public static String GetBuyNowLink()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetBuyNowLinkTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetBuyNowLinkTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region IsSoftwareProtected
[attributes.IsSoftwareProtected]
public static bool IsSoftwareProtected()
{
UInt64 address = 0;
object[] obj = new object[] { false };
Type tp = typeof(netprotector.api.dVoid_BoolParam);
IsSoftwareProtectedTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void IsSoftwareProtectedTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(bool))
return;
obj[0] = false;
}
#endregion
#region IsSoftwareRegistered
[attributes.IsSoftwareRegistered]
public static bool IsSoftwareRegistered()
{
UInt64 address = 0;
object[] obj = new object[] { false };
Type tp = typeof(netprotector.api.dVoid_BoolParam);
IsSoftwareRegisteredTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void IsSoftwareRegisteredTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(bool))
return;
obj[0] = false;
}
#endregion
#region GetTrialDaysCount
[attributes.GetTrialDaysCount]
public static int GetTrialDaysCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialDaysCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
protected static void GetTrialDaysCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialUnitsCount
[attributes.GetTrialUnitsCount]
public static int GetTrialUnitsCount(int dimensions)
{
UInt64 address = 0;
object[] obj = new object[] { (int)0, dimensions };
Type tp = typeof(netprotector.api.dVoid_2IntParam);
GetTrialUnitsCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialUnitsCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) && obj[1].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialDaysLeftCount
[attributes.GetTrialDaysLeftCount]
public static int GetTrialDaysLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialDaysLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialDaysLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialUnitsLeftCount
[attributes.GetTrialUnitsLeftCount]
public static int GetTrialUnitsLeftCount(int dimension)
{
UInt64 address = 0;
object[] obj = new object[] { (int)0, dimension };
Type tp = typeof(netprotector.api.dVoid_2IntParam);
GetTrialUnitsLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialUnitsLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) && obj[1].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialLaunchesCount
[attributes.GetTrialLaunchesCount]
public static int GetTrialLaunchesCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialLaunchesCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialLaunchesCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialLaunchesLeftCount
[attributes.GetTrialLaunchesLeftCount]
public static int GetTrialLaunchesLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialLaunchesLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialLaunchesLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region ShowRegistrationWindow
[attributes.ShowRegistrationWindow]
public static void ShowRegistrationWindow()
{
UInt64 address = 0;
Type tp = typeof(netprotector.api.dVoid_NoParams);
ShowRegistrationWindowTest(address, null, tp);
}
[attributes.Encrypt]
public static void ShowRegistrationWindowTest(UInt64 address, object[] obj, Type delegateType)
{
}
#endregion
#region IsTrialElapsed
[attributes.IsTrialElapsed]
public static bool IsTrialElapsed()
{
UInt64 address = 0;
object[] obj = new object[] { false };
Type tp = typeof(netprotector.api.dVoid_BoolParam);
IsTrialElapsedTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void IsTrialElapsedTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(bool))
return;
obj[0] = false;
}
#endregion
#region GetRenewalPurchaseLink
[attributes.GetRenewalPurchaseLink]
public static String GetRenewalPurchaseLink()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetRenewalPurchaseLinkTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetRenewalPurchaseLinkTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetLicenseType
[attributes.GetLicenseType]
public static int GetLicenseType()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetLicenseTypeTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetLicenseTypeTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetLicenseExpirationDaysCount
[attributes.GetLicenseExpirationDaysCount]
public static int GetLicenseExpirationDaysCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetLicenseExpirationDaysCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetLicenseExpirationDaysCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetLicenseExpirationDaysLeftCount
[attributes.GetLicenseExpirationDaysLeftCount]
public static int GetLicenseExpirationDaysLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetLicenseExpirationDaysLeftTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetLicenseExpirationDaysLeftTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetSupportExpirationDaysCount
[attributes.GetSupportExpirationDaysCount]
public static int GetSupportExpirationDaysCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetSupportExpirationDaysCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetSupportExpirationDaysCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetSupportExpirationDaysLeftCount
[attributes.GetSupportExpirationDaysLeftCount]
public static int GetSupportExpirationDaysLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetSupportExpirationDaysLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetSupportExpirationDaysLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetCurrentProductVersion
[attributes.GetCurrentProductVersion]
public static String GetCurrentProductVersion()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetCurrentProductVersionTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetCurrentProductVersionTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetCustomerName
[attributes.GetCustomerName]
public static String GetCustomerName()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetCustomerNameTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetCustomerNameTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetCustomerEMail
[attributes.GetCustomerEMail]
public static String GetCustomerEMail()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetCustomerEMailTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetCustomerEMailTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetLicenseCode
[attributes.GetLicenseCode]
public static String GetLicenseCode()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetLicenseCodeTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetLicenseCodeTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region RegisterSoftware
[attributes.RegisterSoftware]
public static bool RegisterSoftware(string licenseKey)
{
UInt64 address = 0;
bool res = false;
object[] obj = new object[] { res, licenseKey, licenseKey.Length };
Type tp = typeof(netprotector.api.dBool_StringParam);
RegisterSoftwareTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void RegisterSoftwareTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = false;
}
#endregion
#region RenewLicenseCode
[attributes.RenewLicenseCode]
public static bool RenewLicenseCode(string renewalCode)
{
UInt64 address = 0;
object[] obj = new object[] { false, renewalCode, renewalCode.Length };
Type tp = typeof(netprotector.api.dBool_StringParam);
RenewLicenseCodeTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void RenewLicenseCodeTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = false;
}
#endregion
#region GetCurrentActivationDate
[attributes.GetCurrentActivationDate]
public static DateTime GetCurrentActivationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetCurrentActivationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetCurrentActivationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetCurrentRegistrationDate
[attributes.GetCurrentRegistrationDate]
public static DateTime GetCurrentRegistrationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetCurrentRegistrationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetCurrentRegistrationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetFirstRegistrationDate
[attributes.GetFirstRegistrationDate]
public static DateTime GetFirstRegistrationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetFirstRegistrationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetFirstRegistrationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetOrderDate
[attributes.GetOrderDate]
public static DateTime GetOrderDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetOrderDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetOrderDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetLicenseExpirationDate
[attributes.GetLicenseExpirationDate]
public static DateTime GetLicenseExpirationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetLicenseExpirationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetLicenseExpirationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetProtectionDate
[attributes.GetProtectionDate]
public static DateTime GetProtectionDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetProtectionDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetProtectionDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetSupportExpirationDate
[attributes.GetSupportExpirationDate]
public static DateTime GetSupportExpirationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetSupportExpirationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetSupportExpirationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetSupportExpirationProductVersion
[attributes.GetSupportExpirationProductVersion]
public static String GetSupportExpirationProductVersion()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetSupportExpirationProductVersionTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetSupportExpirationProductVersionTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetIntelliProtectorVersion
[attributes.GetIntelliProtectorVersion]
public static String GetIntelliProtectorVersion()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetIntelliProtectorVersionTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetIntelliProtectorVersionTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region CreateRegistrationRequestCertificate
[attributes.CreateRegistrationRequestCertificate]
public static bool CreateRegistrationRequestCertificate(string path, string licenseCode)
{
UInt64 address = 0;
bool res = false;
object[] obj = new object[] { res, path, licenseCode };
Type tp = typeof(netprotector.api.dBool_StringStringParam);
CreateRegistrationRequestCertificateTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void CreateRegistrationRequestCertificateTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = true;
}
#endregion
#region UseRegistrationResponseCertificate
[attributes.UseRegistrationResponseCertificate]
public static bool UseRegistrationResponseCertificate(string path)
{
UInt64 address = 0;
bool res = false;
object[] obj = new object[] { res, path };
Type tp = typeof(netprotector.api.dBool_StringOnlyParam);
UseRegistrationResponseCertificateTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void UseRegistrationResponseCertificateTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = true;
}
#endregion
#region SystemFunction1
[attributes.SystemFunction1]
protected static void SystemFunction1(UInt64 address, object[] parameters, Type delegateType)
{
Delegate delegateFunc = Marshal.GetDelegateForFunctionPointer((IntPtr)address, delegateType);
delegateFunc.DynamicInvoke(parameters);
}
#endregion
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IntelliProtectorService;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
namespace Register
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (!IntelliProtector.Init())
throw new Exception("IntelliProtector Failed to Initialize");
//if (!IntelliProtector.Init())
// Application.Run(new Register());
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Register")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Panacean Technologies, LLC")]
[assembly: AssemblyProduct("Register")]
[assembly: AssemblyCopyright("Copyright © Panacean Technologies 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("51df0402-3102-48e9-a572-4d8d26e50387")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Register.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Register.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Register.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

47
sFTPlugins/Register/Register.Designer.cs generated Normal file
View File

@@ -0,0 +1,47 @@
namespace Register
{
partial class Register
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(455, 291);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Register
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
}
}

View File

@@ -0,0 +1,95 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{A72A61E3-5C00-41EC-9372-148D879945FC}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Register</RootNamespace>
<AssemblyName>Register</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Target\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Target\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IntelliProtector.cs" />
<Compile Include="Register.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Register.Designer.cs">
<DependentUpon>Register.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Register.resx">
<DependentUpon>Register.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

View File

@@ -0,0 +1,10 @@
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\Register.exe
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\Register.pdb
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\ResolveAssemblyReference.cache
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\Register.Register.resources
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\Register.Properties.Resources.resources
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\Register.exe
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\Register.pdb
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\ResGen.read.1.tlog
C:\_ROOT_\PanaceanTech\sFTPlugins\Register\obj\x86\Release\ResGen.write.1.tlog
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\Register.exe.config

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,930 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2010. IntelliProtector.com
// Web site: http://intelliprotector.com
// Version: v2.5
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace netprotector.api
{
internal delegate void dVoid_NoParams();
internal delegate void dVoid_BoolParam(out bool b1);
internal delegate void dVoid_IntParam(out int i1);
internal delegate void dVoid_2IntParam(out int i1, int i2);
internal delegate void dVoid_5IntParams(out int i1, out int i2, out int i3, out int i4, out int i5);
internal delegate void dVoid_StringBuilderParam([MarshalAs(UnmanagedType.LPWStr)] StringBuilder s1, int iMaxLength);
internal delegate void dBool_StringParam(out bool res, [MarshalAs(UnmanagedType.LPWStr)]String s1, int iMaxLength);
internal delegate void dBool_StringOnlyParam(out bool res, [MarshalAs(UnmanagedType.LPWStr)]String s1);
internal delegate void dBool_StringStringParam(out bool res, [MarshalAs(UnmanagedType.LPWStr)]String s1, [MarshalAs(UnmanagedType.LPWStr)]String s2);
}
namespace IntelliProtectorService.attributes
{
internal class Encrypt : Attribute { }
internal class GetBuyNowLinkAttribute : Attribute { }
internal class IsSoftwareProtectedAttribute : Attribute { }
internal class IsSoftwareRegisteredAttribute : Attribute { }
internal class GetTrialDaysCountAttribute : Attribute { }
internal class GetTrialUnitsCountAttribute : Attribute { }
internal class GetTrialDaysLeftCountAttribute : Attribute { }
internal class GetTrialUnitsLeftCountAttribute : Attribute { }
internal class GetTrialLaunchesCountAttribute : Attribute { }
internal class GetTrialLaunchesLeftCountAttribute : Attribute { }
internal class ShowRegistrationWindowAttribute : Attribute { }
internal class IsTrialElapsedAttribute : Attribute { }
internal class GetRenewalPurchaseLinkAttribute : Attribute { }
internal class GetLicenseTypeAttribute : Attribute { }
internal class GetLicenseExpirationDaysCountAttribute : Attribute { }
internal class GetLicenseExpirationDaysLeftCountAttribute : Attribute { }
internal class GetSupportExpirationDaysCountAttribute : Attribute { }
internal class GetSupportExpirationDaysLeftCountAttribute : Attribute { }
internal class GetCurrentProductVersionAttribute : Attribute { }
internal class GetCustomerNameAttribute : Attribute { }
internal class GetCustomerEMailAttribute : Attribute { }
internal class GetLicenseCodeAttribute : Attribute { }
internal class RegisterSoftwareAttribute : Attribute { }
internal class RenewLicenseCodeAttribute : Attribute { }
internal class GetCurrentActivationDateAttribute : Attribute { }
internal class GetCurrentRegistrationDateAttribute : Attribute { }
internal class GetFirstRegistrationDateAttribute : Attribute { }
internal class GetOrderDateAttribute : Attribute { }
internal class GetLicenseExpirationDateAttribute : Attribute { }
internal class GetProtectionDateAttribute : Attribute { }
internal class GetSupportExpirationDateAttribute : Attribute { }
internal class GetSupportExpirationProductVersionAttribute : Attribute { }
internal class GetIntelliProtectorVersionAttribute : Attribute { }
internal class CreateRegistrationRequestCertificateAttribute : Attribute { }
internal class UseRegistrationResponseCertificateAttribute : Attribute { }
internal class SystemFunction1Attribute : Attribute { }
}
namespace IntelliProtectorService
{
internal class IntelliProtector
{
public static double Version_2_5()
{
return 2.5f;
}
#if DEBUG
public static bool IsInDebugMode()
{
return true;
}
#endif
public enum enUnitDimension
{
eudMinutes,
eudHours,
eudDays,
eudWeeks,
eudMonths
};
private class Init32
{
[DllImport("JitHookCore.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Init")]
public static extern void Init();
};
private class Init64
{
[DllImport("JitHookCoreX64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Init")]
public static extern void Init();
};
public static bool Init()
{
try
{
bool tryLoadX64 = false;
try
{
Init32.Init();
}
catch (BadImageFormatException)
{
tryLoadX64 = true;
}
if (tryLoadX64)
{
try
{
Init64.Init();
}
catch (BadImageFormatException)
{
return false;
}
}
return true;
}
catch (System.Exception)
{
return false;
}
}
#region GetBuyNowLink
[attributes.GetBuyNowLinkAttribute]
public static String GetBuyNowLink()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetBuyNowLinkTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetBuyNowLinkTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region IsSoftwareProtected
[attributes.IsSoftwareProtected]
public static bool IsSoftwareProtected()
{
UInt64 address = 0;
object[] obj = new object[] { false };
Type tp = typeof(netprotector.api.dVoid_BoolParam);
IsSoftwareProtectedTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void IsSoftwareProtectedTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(bool))
return;
obj[0] = false;
}
#endregion
#region IsSoftwareRegistered
[attributes.IsSoftwareRegistered]
public static bool IsSoftwareRegistered()
{
UInt64 address = 0;
object[] obj = new object[] { false };
Type tp = typeof(netprotector.api.dVoid_BoolParam);
IsSoftwareRegisteredTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void IsSoftwareRegisteredTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(bool))
return;
obj[0] = false;
}
#endregion
#region GetTrialDaysCount
[attributes.GetTrialDaysCount]
public static int GetTrialDaysCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialDaysCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
protected static void GetTrialDaysCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialUnitsCount
[attributes.GetTrialUnitsCount]
public static int GetTrialUnitsCount(int dimensions)
{
UInt64 address = 0;
object[] obj = new object[] { (int)0, dimensions };
Type tp = typeof(netprotector.api.dVoid_2IntParam);
GetTrialUnitsCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialUnitsCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) && obj[1].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialDaysLeftCount
[attributes.GetTrialDaysLeftCount]
public static int GetTrialDaysLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialDaysLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialDaysLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialUnitsLeftCount
[attributes.GetTrialUnitsLeftCount]
public static int GetTrialUnitsLeftCount(int dimension)
{
UInt64 address = 0;
object[] obj = new object[] { (int)0, dimension };
Type tp = typeof(netprotector.api.dVoid_2IntParam);
GetTrialUnitsLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialUnitsLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) && obj[1].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialLaunchesCount
[attributes.GetTrialLaunchesCount]
public static int GetTrialLaunchesCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialLaunchesCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialLaunchesCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetTrialLaunchesLeftCount
[attributes.GetTrialLaunchesLeftCount]
public static int GetTrialLaunchesLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetTrialLaunchesLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetTrialLaunchesLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region ShowRegistrationWindow
[attributes.ShowRegistrationWindow]
public static void ShowRegistrationWindow()
{
UInt64 address = 0;
Type tp = typeof(netprotector.api.dVoid_NoParams);
ShowRegistrationWindowTest(address, null, tp);
}
[attributes.Encrypt]
public static void ShowRegistrationWindowTest(UInt64 address, object[] obj, Type delegateType)
{
}
#endregion
#region IsTrialElapsed
[attributes.IsTrialElapsed]
public static bool IsTrialElapsed()
{
UInt64 address = 0;
object[] obj = new object[] { false };
Type tp = typeof(netprotector.api.dVoid_BoolParam);
IsTrialElapsedTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void IsTrialElapsedTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(bool))
return;
obj[0] = false;
}
#endregion
#region GetRenewalPurchaseLink
[attributes.GetRenewalPurchaseLink]
public static String GetRenewalPurchaseLink()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetRenewalPurchaseLinkTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetRenewalPurchaseLinkTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetLicenseType
[attributes.GetLicenseType]
public static int GetLicenseType()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetLicenseTypeTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetLicenseTypeTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetLicenseExpirationDaysCount
[attributes.GetLicenseExpirationDaysCount]
public static int GetLicenseExpirationDaysCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetLicenseExpirationDaysCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetLicenseExpirationDaysCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetLicenseExpirationDaysLeftCount
[attributes.GetLicenseExpirationDaysLeftCount]
public static int GetLicenseExpirationDaysLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetLicenseExpirationDaysLeftTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetLicenseExpirationDaysLeftTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetSupportExpirationDaysCount
[attributes.GetSupportExpirationDaysCount]
public static int GetSupportExpirationDaysCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetSupportExpirationDaysCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetSupportExpirationDaysCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetSupportExpirationDaysLeftCount
[attributes.GetSupportExpirationDaysLeftCount]
public static int GetSupportExpirationDaysLeftCount()
{
UInt64 address = 0;
object[] obj = new object[] { (int)0 };
Type tp = typeof(netprotector.api.dVoid_IntParam);
GetSupportExpirationDaysLeftCountTest(address, obj, tp);
return (int)obj[0];
}
[attributes.Encrypt]
public static void GetSupportExpirationDaysLeftCountTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int))
return;
obj[0] = -1;
}
#endregion
#region GetCurrentProductVersion
[attributes.GetCurrentProductVersion]
public static String GetCurrentProductVersion()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetCurrentProductVersionTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetCurrentProductVersionTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetCustomerName
[attributes.GetCustomerName]
public static String GetCustomerName()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetCustomerNameTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetCustomerNameTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetCustomerEMail
[attributes.GetCustomerEMail]
public static String GetCustomerEMail()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetCustomerEMailTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetCustomerEMailTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetLicenseCode
[attributes.GetLicenseCode]
public static String GetLicenseCode()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetLicenseCodeTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetLicenseCodeTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region RegisterSoftware
[attributes.RegisterSoftware]
public static bool RegisterSoftware(string licenseKey)
{
UInt64 address = 0;
bool res = false;
object[] obj = new object[] { res, licenseKey, licenseKey.Length };
Type tp = typeof(netprotector.api.dBool_StringParam);
RegisterSoftwareTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void RegisterSoftwareTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = false;
}
#endregion
#region RenewLicenseCode
[attributes.RenewLicenseCode]
public static bool RenewLicenseCode(string renewalCode)
{
UInt64 address = 0;
object[] obj = new object[] { false, renewalCode, renewalCode.Length };
Type tp = typeof(netprotector.api.dBool_StringParam);
RenewLicenseCodeTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void RenewLicenseCodeTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = false;
}
#endregion
#region GetCurrentActivationDate
[attributes.GetCurrentActivationDate]
public static DateTime GetCurrentActivationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetCurrentActivationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetCurrentActivationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetCurrentRegistrationDate
[attributes.GetCurrentRegistrationDate]
public static DateTime GetCurrentRegistrationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetCurrentRegistrationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetCurrentRegistrationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetFirstRegistrationDate
[attributes.GetFirstRegistrationDate]
public static DateTime GetFirstRegistrationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetFirstRegistrationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetFirstRegistrationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetOrderDate
[attributes.GetOrderDate]
public static DateTime GetOrderDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetOrderDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetOrderDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetLicenseExpirationDate
[attributes.GetLicenseExpirationDate]
public static DateTime GetLicenseExpirationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetLicenseExpirationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetLicenseExpirationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetProtectionDate
[attributes.GetProtectionDate]
public static DateTime GetProtectionDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetProtectionDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetProtectionDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetSupportExpirationDate
[attributes.GetSupportExpirationDate]
public static DateTime GetSupportExpirationDate()
{
UInt64 address = 0;
object[] obj = new object[] { 0, 0, 0, 0, 0 };
Type tp = typeof(netprotector.api.dVoid_5IntParams);
GetSupportExpirationDateTest(address, obj, tp);
if ((int)obj[0] < 0)
return DateTime.MinValue;
return new DateTime((int)obj[0], (int)obj[1], (int)obj[2], (int)obj[3], (int)obj[4], 0);
}
[attributes.Encrypt]
protected static void GetSupportExpirationDateTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(int) ||
obj[1].GetType() != typeof(int) ||
obj[2].GetType() != typeof(int) ||
obj[3].GetType() != typeof(int) ||
obj[4].GetType() != typeof(int))
{
return;
}
obj[0] = -1;
obj[1] = -1;
obj[2] = -1;
obj[3] = -1;
obj[4] = -1;
}
#endregion
#region GetSupportExpirationProductVersion
[attributes.GetSupportExpirationProductVersion]
public static String GetSupportExpirationProductVersion()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetSupportExpirationProductVersionTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetSupportExpirationProductVersionTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region GetIntelliProtectorVersion
[attributes.GetIntelliProtectorVersion]
public static String GetIntelliProtectorVersion()
{
UInt64 address = 0;
int ciMinLength = 0;
int ciMaxLength = 1024;
StringBuilder rValue = new StringBuilder(ciMaxLength);
object[] obj = new object[] { rValue, ciMaxLength - ciMinLength };
Type tp = typeof(netprotector.api.dVoid_StringBuilderParam);
GetIntelliProtectorVersionTest(address, obj, tp);
return rValue.ToString();
}
[attributes.Encrypt]
protected static void GetIntelliProtectorVersionTest(UInt64 address, object[] obj, Type delegateType)
{
if (obj[0].GetType() != typeof(StringBuilder))
return;
string strLink = "";
if ((int)obj[1] >= strLink.Length)
((StringBuilder)obj[0]).Append(strLink);
}
#endregion
#region CreateRegistrationRequestCertificate
[attributes.CreateRegistrationRequestCertificate]
public static bool CreateRegistrationRequestCertificate(string path, string licenseCode)
{
UInt64 address = 0;
bool res = false;
object[] obj = new object[] { res, path, licenseCode };
Type tp = typeof(netprotector.api.dBool_StringStringParam);
CreateRegistrationRequestCertificateTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void CreateRegistrationRequestCertificateTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = true;
}
#endregion
#region UseRegistrationResponseCertificate
[attributes.UseRegistrationResponseCertificate]
public static bool UseRegistrationResponseCertificate(string path)
{
UInt64 address = 0;
bool res = false;
object[] obj = new object[] { res, path };
Type tp = typeof(netprotector.api.dBool_StringOnlyParam);
UseRegistrationResponseCertificateTest(address, obj, tp);
return (bool)obj[0];
}
[attributes.Encrypt]
protected static void UseRegistrationResponseCertificateTest(UInt64 address, object[] obj, Type delegateType)
{
obj[0] = true;
}
#endregion
#region SystemFunction1
[attributes.SystemFunction1]
protected static void SystemFunction1(UInt64 address, object[] parameters, Type delegateType)
{
Delegate delegateFunc = Marshal.GetDelegateForFunctionPointer((IntPtr)address, delegateType);
delegateFunc.DynamicInvoke(parameters);
}
#endregion
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SMFTP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Panacean Technologies, LLC")]
[assembly: AssemblyProduct("SMFTP")]
[assembly: AssemblyCopyright("Copyright © Panacean Technologies 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2ec998f7-55c3-4904-a9d1-e4d9d125af39")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,397 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using IntelliProtectorService;
namespace SMFTP
{
/// <remarks>
/// Wrapper Managed Class around putty sftp.
/// <example>
/// <code>
/// SFTPClient client = new SFTPClient();
/// if(client.Connect("sftp.somedomain.com","user","password","22"))
/// bool bFetchedFile = client.CmdExec_Any("get somefile.txt");
/// </code>
/// </example>
/// </remarks>
public class SFTPClient : IDisposable
{
#region Private Statics
/// <summary>
/// Used in the all to LoadLibrary * Names here
/// * if you change it here * also change DllImports (below)
/// </summary>
private const string PSFTP_FILENAME = "psftp.dll";
/// <summary>
/// We only want to load the Psftp dll once per process
/// </summary>
private static bool s_PSFTPDLL_IsLoaded = false;
/// <summary>
/// Responsible for creating an active connection
/// </summary>
[DllImport("psftp.dll")]
private static extern int dllmain(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] String[] argv);
/// <summary>
/// Responsible for running a command on an active connection
/// </summary>
[DllImport("psftp.dll")]
private static extern int do_sftp2([MarshalAs(UnmanagedType.LPStr)] string cmdLine);
/// <summary>
/// Responsible for Putty Cleanup
/// </summary>
[DllImport("psftp.dll")]
private static extern void dllmain_cleanup();
/// <summary>
/// Loads the Putty Dll
/// </summary>
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(String dllname);
#endregion
#region Construction / Destruction
/// <summary>
/// Create a SFTClient Object
/// </summary>
public SFTPClient()
{
bool bForceFileWrite = true;
#if !DEBUG
// Initialize IntelliProtect
if (!IntelliProtector.Init())
throw new Exception("Cannot load protector SFTPClient");
bForceFileWrite = false;
#endif
// Extract the Native Dll to the Temp Directory,
// if it is not already there...
if (bForceFileWrite || !File.Exists(_pstfpTempFileNameNPath))
{
using (BinaryReader br = new BinaryReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(("SMFTP.Components." + PSFTP_FILENAME))))
using (BinaryWriter bw = new BinaryWriter(new FileStream(_pstfpTempFileNameNPath, FileMode.Create)))
{
byte[] buffer = new byte[64 * 1024];
int numread = br.Read(buffer, 0, buffer.Length);
while (numread > 0)
{
bw.Write(buffer, 0, numread);
numread = br.Read(buffer, 0, buffer.Length);
}
bw.Flush();
}
}
// Load the dll, if it isn't already
if (!s_PSFTPDLL_IsLoaded)
{
IntPtr hDll = LoadLibrary(_pstfpTempFileNameNPath);
s_PSFTPDLL_IsLoaded = (hDll != IntPtr.Zero);
}
if (!s_PSFTPDLL_IsLoaded)
throw new Exception(("Failed to load " + _pstfpTempFileNameNPath + ". Something terrible is wrong"));
}
/// <summary>
/// Finalizer
/// </summary>
~SFTPClient()
{
Dispose(false);
}
#endregion
#region Private Members
private bool _IsConnected = false;
private bool _disposed = false;
private readonly string _pstfpTempFileNameNPath = Path.GetTempPath() + PSFTP_FILENAME;
#endregion
#region Main Putty Functions
/// <summary>
/// Start a Connection to the specified Host with the specified credentials
/// </summary>
/// <param name="hostname">url to sftp host</param>
/// <param name="username">user credential</param>
/// <param name="password">password credential</param>
/// <param name="port">port to connect to (default 22)</param>
/// <returns>true if connection occured successfully, false otherwise</returns>
public bool Connect(string hostname, string username, string password, string port = "22")
{
if (String.IsNullOrEmpty(hostname) || String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password) || String.IsNullOrEmpty(port))
throw new ArgumentException("Empty String not valid for any of the arguments");
Disconnect();
int nResult = dllmain(10, new String[] { Assembly.GetExecutingAssembly().Location, "-l", username, "-pw", password, "-P", port, "-batch", "-y", hostname });
if (nResult != 0) // Error occured connecting to host with specified prms
return false;
_IsConnected = true;
return true;
}
/// <summary>
/// End the active Connection
/// </summary>
public bool Disconnect()
{
if (_IsConnected)
{
dllmain_cleanup();
_IsConnected = false;
}
return !_IsConnected;
}
/// <summary>
/// Performs the specified Command on the Active Connection
/// </summary>
/// <param name="Command">a Command including optional parameters like "dir *.*" that can be understood by psftp</param>
/// <returns>true, if command run successfully, falser otherwise</returns>
public bool CmdExec_Any(string Command)
{
// Perform the Action
if (_IsConnected)
{
bool bPerformedAction = (do_sftp2(Command) == 1);
return bPerformedAction;
}
return false;
}
#endregion
#region Command Helpers (Assumes Active Connection)
/// <summary>
/// Set the Working Directory Locally
/// </summary>
/// <param name="path">path to a local directory</param>
/// <param name="bCreateIfNotExists">true to create the local directory, if it doesn't exist, false otherwise</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExec_LocalDirSet(string path, bool bCreateIfNotExists = false)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if(String.IsNullOrEmpty(path))
throw new ArgumentException("path can not be empty");
bool bSuccess = CmdExec_Any("lcd " + path);
if (!bSuccess && bCreateIfNotExists)
{
Directory.CreateDirectory(path);
if(Directory.Exists(path))
bSuccess = CmdExec_Any("lcd " + path);
}
return bSuccess;
}
/// <summary>
/// Set the Working Directory on the Remote sftp connection
/// </summary>
/// <param name="path">path to a remote directory</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExec_RemoteDirSet(string path)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(path))
throw new ArgumentException("path can not be empty");
// Always make paths absolute * safer *
if (path[0] != '/' && path[0] != '\\')
path = '/' + path;
bool bSuccess = CmdExec_Any("cd " + path);
return bSuccess;
}
/// <summary>
/// Checks for existence of the Directory on the Server
/// </summary>
/// <param name="path">path to a remote directory</param>
/// <returns>true, if remote directory exists, false otherwise</returns>
public bool CmdExec_RemoteDirExists(string path)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(path))
throw new ArgumentException("path can not be empty");
// Always make paths absolute * safer *
if (path[0] != '/' && path[0] != '\\')
path = '/' + path;
bool bSuccess = CmdExec_Any("cd /"); // make sure we are at the root dir
if (bSuccess)
bSuccess = CmdExec_Any("cd " + path);
if (bSuccess)
bSuccess = CmdExec_Any("cd /"); // back to root dir
return bSuccess;
}
/// <summary>
/// Download a Directory at once including all it's files. if bRecursive is set,
/// Download all child directories and files
/// </summary>
/// <param name="bRecursive">If bRecursive is true, recursively fetch files and directories</param>
/// <param name="path">path to a remote directory</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExe_MGetDir(bool bRecursive, string path)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(path))
throw new ArgumentException("path can not be empty");
// Always make paths absolute * safer *
if (path[0] != '/' && path[0] != '\\')
path = '/' + path;
string mgetCmd = bRecursive ? "mget -r " : "mget ";
bool bSuccess = CmdExec_Any(mgetCmd + path);
return bSuccess;
}
/// <summary>
/// Download multiple files at once
/// <example>
/// "*.c" "filename1.txt" "*.sln"
/// </example>
/// </summary>
/// <param name="filenames_or_wildcards">space seperated list of multiple filenames or wildcards</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExe_MGetFiles(string filenames_or_wildcards)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(filenames_or_wildcards))
throw new ArgumentException("filenames_or_wildcards can not be empty");
bool bSuccess = CmdExec_Any("mget " + filenames_or_wildcards);
return bSuccess;
}
/// <summary>
/// Upload a Directory at once including all it's files. if bRecursive is set,
/// Upload all child directories and files
/// </summary>
/// <param name="bRecursive">If bRecursive is true, recursively put files and directories</param>
/// <param name="path">path to a local directory</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExe_MPutDir(bool bRecursive, string path)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(path))
throw new ArgumentException("path can not be empty");
string mgetCmd = bRecursive ? "mput -r " : "mget ";
bool bSuccess = CmdExec_Any(mgetCmd + path);
return bSuccess;
}
/// <summary>
/// Upload multiple files at once
/// <example>
/// "*.c" "filename1.txt" "*.sln"
/// </example>
/// </summary>
/// <param name="filenames_or_wildcards">space seperated list of multiple filenames or wildcards</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExe_MPutFiles(string filenames_or_wildcards)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(filenames_or_wildcards))
throw new ArgumentException("filenames_or_wildcards can not be empty");
bool bSuccess = CmdExec_Any("mput " + filenames_or_wildcards);
return bSuccess;
}
/// <summary>
/// Delete multiple files at once from the server
/// <example>
/// "*.c" "filename1.txt" "*.sln"
/// </example>
/// </summary>
/// <param name="filenames_or_wildcards">space seperated list of multiple filenames or wildcards</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExe_MDelFiles(string filenames_or_wildcards)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(filenames_or_wildcards))
throw new ArgumentException("filenames_or_wildcards can not be empty");
bool bSuccess = CmdExec_Any("del " + filenames_or_wildcards);
return bSuccess;
}
/// <summary>
/// Removes a Directory from the server. Directory must be empty in order
/// to be removed.
/// </summary>
/// <param name="path">path to a remote directory</param>
/// <returns>true, if successful, false otherwise</returns>
public bool CmdExe_MDelDir(string path)
{
if (!_IsConnected)
throw new Exception("Not Connected");
if (String.IsNullOrEmpty(path))
throw new ArgumentException("path can not be empty");
// Always make paths absolute * safer *
if (path[0] != '/' && path[0] != '\\')
path = '/' + path;
bool bSuccess = CmdExec_Any("" + path);
return bSuccess;
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Free Managed Resources
}
// Free Unmanaged Resources
Disconnect();
_disposed = true;
}
}
#endregion
}
}

View File

@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6C463FB5-D25B-4CD4-A493-7B91615E8467}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SMFTP</RootNamespace>
<AssemblyName>SMFTP</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Target\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Target\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IntelliProtector.cs" />
<Compile Include="SFTPClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Components\psftp.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>copy "$(SolutionDir)psftp\WINDOWS\MSVC\PSFTP\$(ConfigurationName)\psftp.dll" "$(ProjectDir)Components" /y
</PreBuildEvent>
</PropertyGroup>
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View File

@@ -0,0 +1,5 @@
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP.dll
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP.pdb
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP\obj\Release\ResolveAssemblyReference.cache
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP\obj\Release\SMFTP.dll
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP\obj\Release\SMFTP.pdb

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace SMFTP_CallTestCS
{
class Program
{
private static Assembly _sftpasm = null;
static void Main(string[] args)
{
#if DEBUG
_sftpasm = Assembly.LoadFile(@"C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Debug\SMFTP.dll");
if (_sftpasm != null)
DebugModeTest();
#else
_sftpasm = Assembly.LoadFile(@"C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP.dll");
if (_sftpasm != null)
ReleaseModeTest();
#endif
}
/// <summary>
/// Test SMFTP using Dynamic Invokes on a release dll
/// </summary>
public static void ReleaseModeTest()
{
Type t = _sftpasm.GetType("SMFTP.SFTPClient");
object o = Activator.CreateInstance(t);
BindingFlags bindings = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance;
object[] prms = null;
prms = new object[] { "secureftp.navicure.com", "5S3F054P", "LPM2055", "22" };
bool bSuccess = (bool)t.InvokeMember("Connect", bindings, null, o, prms);
if (bSuccess)
{
prms = new object[] { "in" };
bSuccess = (bool)t.InvokeMember("CmdExec_RemoteDirSet", bindings, null, o, prms);
}
//if (bSuccess)
//{
// prms = new object[] { "c:\\out", true };
// bSuccess = (bool)t.InvokeMember("CmdExec_LocalDirSet", bindings, null, o, prms);
//}
//if (bSuccess)
//{
// prms = new object[] { true, "out/997" };
// bSuccess = (bool)t.InvokeMember("CmdExe_MGetDir", bindings, null, o, prms);
//}
//if (bSuccess)
//{
// prms = new object[] { "in" };
// bSuccess = (bool)t.InvokeMember("CmdExec_RemoteDirSet", bindings, null, o, prms);
//}
//if (bSuccess)
//{
// prms = new object[] { "c:\\out\\997", true };
// bSuccess = (bool)t.InvokeMember("CmdExec_LocalDirSet", bindings, null, o, prms);
//}
if (bSuccess)
{
prms = new object[] { "C:\\out\\Doris day\\EmptyDummy File.txt" };
bSuccess = (bool)t.InvokeMember("CmdExe_MPutFiles", bindings, null, o, prms);
}
//if (bSuccess)
//{
// prms = new object[] { "*.997" };
// bSuccess = (bool)t.InvokeMember("CmdExe_MDelFiles", bindings, null, o, prms);
//}
}
/// <summary>
/// Test SMTP using direct invokes on debug dll
/// </summary>
public static void DebugModeTest()
{
using (SMFTP.SFTPClient client = new SMFTP.SFTPClient())
{
bool bConnected = client.Connect("secureftp.navicure.com", "5S3F054P", "LPM2055");
if (bConnected)
{
bool bSuccess = true;
//if (bSuccess)
// bSuccess = client.CmdExec_RemoteDirExists("out/997");
//if (bSuccess)
// bSuccess = client.CmdExec_LocalDirSet("c:\\out", true);
//if (bSuccess)
// bSuccess = client.CmdExe_MGetDir(true, "out/997");
if (bSuccess)
bSuccess = client.CmdExec_RemoteDirSet("in");
//if (bSuccess)
// bSuccess = client.CmdExec_LocalDirSet("c:\\out\\997", true);
if (bSuccess)
bSuccess = client.CmdExe_MPutFiles("\"C:\\out\\Doris day\\EmptyDummy File.txt\"");
//if (bSuccess)
// bSuccess = client.CmdExe_MDelFiles("*.997");
}
}
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SMFTP_CallTestCS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("SMFTP_CallTestCS")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("18baf6fa-bd5c-4dc3-8492-a11394b109ff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F0A4D6FB-0864-478C-A91D-E916B71FDF5C}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SMFTP_CallTestCS</RootNamespace>
<AssemblyName>SMFTP_CallTestCS</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Target\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Target\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SMFTP\SMFTP.csproj">
<Project>{6C463FB5-D25B-4CD4-A493-7B91615E8467}</Project>
<Name>SMFTP</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View File

@@ -0,0 +1,5 @@
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP_CallTestCS.exe
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP_CallTestCS.pdb
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestCS\obj\x86\Release\ResolveAssemblyReference.cache
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestCS\obj\x86\Release\SMFTP_CallTestCS.exe
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestCS\obj\x86\Release\SMFTP_CallTestCS.pdb

View File

@@ -0,0 +1,73 @@
Imports System.Reflection
Module Module1
Sub Main()
Dim sftpasm As Assembly = Assembly.LoadFile("C:\Users\Administrator\Documents\Visual Studio 2010\Projects\puttysrc\SMFTP\bin\Debug\SMFTP.dll")
If sftpasm IsNot Nothing Then
Dim t As Type = sftpasm.[GetType]("SMFTP.SFTPClient")
Dim o As Object = Activator.CreateInstance(t)
Dim bindings As BindingFlags = BindingFlags.InvokeMethod Or BindingFlags.[Public] Or BindingFlags.Instance
Dim prms As Object() = Nothing
prms = New Object() {"secureftp.navicure.com", "5S3F054P", "LPM2055", "22"}
Dim bSuccess As Boolean = CBool(t.InvokeMember("Connect", bindings, Nothing, o, prms))
If bSuccess Then
prms = New Object() {"out/997"}
bSuccess = CBool(t.InvokeMember("CmdExec_RemoteDirExists", bindings, Nothing, o, prms))
End If
If bSuccess Then
prms = New Object() {"c:\out", True}
bSuccess = CBool(t.InvokeMember("CmdExec_LocalDirSet", bindings, Nothing, o, prms))
End If
If bSuccess Then
prms = New Object() {True, "out/997"}
bSuccess = CBool(t.InvokeMember("CmdExe_MGetDir", bindings, Nothing, o, prms))
End If
If bSuccess Then
prms = New Object() {"in"}
bSuccess = CBool(t.InvokeMember("CmdExec_RemoteDirSet", bindings, Nothing, o, prms))
End If
If bSuccess Then
prms = New Object() {"c:\out\997", True}
bSuccess = CBool(t.InvokeMember("CmdExec_LocalDirSet", bindings, Nothing, o, prms))
End If
If bSuccess Then
prms = New Object() {"*.997"}
bSuccess = CBool(t.InvokeMember("CmdExe_MPutFiles", bindings, Nothing, o, prms))
End If
If bSuccess Then
prms = New Object() {"*.997"}
bSuccess = CBool(t.InvokeMember("CmdExe_MDelFiles", bindings, Nothing, o, prms))
End If
End If
' Using client As New SMFTP.SFTPClient()
' Dim bConnected As Boolean = client.Connect("secureftp.navicure.com", "5S3F054P", "LPM2055")
' If bConnected Then
' Dim bSuccess As Boolean = client.CmdExec_RemoteDirExists("out/997")
' If bSuccess Then
' bSuccess = client.CmdExec_LocalDirSet("c:\out", True)
' End If
' If bSuccess Then
' bSuccess = client.CmdExe_MGetDir(True, "out/997")
' End If
' If bSuccess Then
' bSuccess = client.CmdExec_RemoteDirSet("in")
' End If
' If bSuccess Then
' bSuccess = client.CmdExec_LocalDirSet("c:\out\997", True)
' End If
' If bSuccess Then
' bSuccess = client.CmdExe_MPutFiles("*.997")
' End If
' If bSuccess Then
' bSuccess = client.CmdExe_MDelFiles("*.997")
' End If
' End If
'End Using
End Sub
End Module

View File

@@ -0,0 +1,13 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.225
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MySubMain>false</MySubMain>
<SingleInstance>false</SingleInstance>
<ShutdownMode>0</ShutdownMode>
<EnableVisualStyles>true</EnableVisualStyles>
<AuthenticationMode>0</AuthenticationMode>
<ApplicationType>2</ApplicationType>
<SaveMySettingsOnExit>true</SaveMySettingsOnExit>
</MyApplicationData>

View File

@@ -0,0 +1,35 @@
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("SMFTP_CallTestVB")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("SMFTP_CallTestVB")>
<Assembly: AssemblyCopyright("Copyright © Microsoft 2011")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("8576e025-880b-4979-a9f6-649dc879cf7e")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>

View File

@@ -0,0 +1,62 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.225
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("SMFTP_CallTestVB.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,73 @@
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.225
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Partial Friend NotInheritable Class MySettings
Inherits Global.System.Configuration.ApplicationSettingsBase
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
#Region "My.Settings Auto-Save Functionality"
#If _MyType = "WindowsForms" Then
Private Shared addedHandler As Boolean
Private Shared addedHandlerLockObject As New Object
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
If My.Application.SaveMySettingsOnExit Then
My.Settings.Save()
End If
End Sub
#End If
#End Region
Public Shared ReadOnly Property [Default]() As MySettings
Get
#If _MyType = "WindowsForms" Then
If Not addedHandler Then
SyncLock addedHandlerLockObject
If Not addedHandler Then
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
addedHandler = True
End If
End SyncLock
End If
#End If
Return defaultInstance
End Get
End Property
End Class
End Namespace
Namespace My
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
Friend Module MySettingsProperty
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
Friend ReadOnly Property Settings() As Global.SMFTP_CallTestVB.My.MySettings
Get
Return Global.SMFTP_CallTestVB.My.MySettings.Default
End Get
End Property
End Module
End Namespace

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>
</SchemaVersion>
<ProjectGuid>{70D1820D-B49C-4FEB-9B3D-18A0D64837D6}</ProjectGuid>
<OutputType>Exe</OutputType>
<StartupObject>SMFTP_CallTestVB.Module1</StartupObject>
<RootNamespace>SMFTP_CallTestVB</RootNamespace>
<AssemblyName>SMFTP_CallTestVB</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Console</MyType>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Target\Debug\</OutputPath>
<DocumentationFile>SMFTP_CallTestVB.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>..\Target\Release\</OutputPath>
<DocumentationFile>SMFTP_CallTestVB.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Xml" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="Module1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SMFTP\SMFTP.csproj">
<Project>{6C463FB5-D25B-4CD4-A493-7B91615E8467}</Project>
<Name>SMFTP</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View File

@@ -0,0 +1,10 @@
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP_CallTestVB.exe
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP_CallTestVB.pdb
C:\_ROOT_\PanaceanTech\sFTPlugins\Target\Release\SMFTP_CallTestVB.xml
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\ResolveAssemblyReference.cache
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\SMFTP_CallTestVB.Resources.resources
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\GenerateResource.read.1.tlog
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\GenerateResource.write.1.tlog
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\SMFTP_CallTestVB.exe
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\SMFTP_CallTestVB.xml
C:\_ROOT_\PanaceanTech\sFTPlugins\SMFTP_CallTestVB\obj\x86\Release\SMFTP_CallTestVB.pdb

View File

@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>
SMFTP_CallTestVB
</name>
</assembly>
<members>
<member name="P:SMFTP_CallTestVB.My.Resources.Resources.ResourceManager">
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
</member><member name="P:SMFTP_CallTestVB.My.Resources.Resources.Culture">
<summary>
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
</summary>
</member><member name="T:SMFTP_CallTestVB.My.Resources.Resources">
<summary>
A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
</members>
</doc>

Binary file not shown.

View File

@@ -0,0 +1,3 @@
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>
SMFTP_CallTestVB
</name>
</assembly>
<members>
<member name="P:SMFTP_CallTestVB.My.Resources.Resources.ResourceManager">
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
</member><member name="P:SMFTP_CallTestVB.My.Resources.Resources.Culture">
<summary>
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
</summary>
</member><member name="T:SMFTP_CallTestVB.My.Resources.Resources">
<summary>
A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
</members>
</doc>

View File

@@ -0,0 +1,16 @@
/*
* Linking module for PSCP: list the available backends, but
* without accompanying function suites. Used only for name
* lookups.
*/
#include <stdio.h>
#include "putty.h"
struct backend_list backends[] = {
{PROT_SSH, "ssh", NULL},
{PROT_TELNET, "telnet", NULL},
{PROT_RLOGIN, "rlogin", NULL},
{PROT_RAW, "raw", NULL},
{0, NULL}
};

View File

@@ -0,0 +1,154 @@
/*
* charset.h - header file for general character set conversion
* routines.
*/
#ifndef charset_charset_h
#define charset_charset_h
#include <stddef.h>
/*
* Enumeration that lists all the multibyte or single-byte
* character sets known to this library.
*/
typedef enum {
CS_NONE, /* used for reporting errors, etc */
CS_ISO8859_1,
CS_ISO8859_1_X11, /* X font encoding with VT100 glyphs */
CS_ISO8859_2,
CS_ISO8859_3,
CS_ISO8859_4,
CS_ISO8859_5,
CS_ISO8859_6,
CS_ISO8859_7,
CS_ISO8859_8,
CS_ISO8859_9,
CS_ISO8859_10,
CS_ISO8859_11,
CS_ISO8859_13,
CS_ISO8859_14,
CS_ISO8859_15,
CS_ISO8859_16,
CS_CP437,
CS_CP850,
CS_CP866,
CS_CP1250,
CS_CP1251,
CS_CP1252,
CS_CP1253,
CS_CP1254,
CS_CP1255,
CS_CP1256,
CS_CP1257,
CS_CP1258,
CS_KOI8_R,
CS_KOI8_U,
CS_MAC_ROMAN,
CS_MAC_TURKISH,
CS_MAC_CROATIAN,
CS_MAC_ICELAND,
CS_MAC_ROMANIAN,
CS_MAC_GREEK,
CS_MAC_CYRILLIC,
CS_MAC_THAI,
CS_MAC_CENTEURO,
CS_MAC_SYMBOL,
CS_MAC_DINGBATS,
CS_MAC_ROMAN_OLD,
CS_MAC_CROATIAN_OLD,
CS_MAC_ICELAND_OLD,
CS_MAC_ROMANIAN_OLD,
CS_MAC_GREEK_OLD,
CS_MAC_CYRILLIC_OLD,
CS_MAC_UKRAINE,
CS_MAC_VT100,
CS_MAC_VT100_OLD,
CS_VISCII,
CS_HP_ROMAN8,
CS_DEC_MCS,
CS_UTF8
} charset_t;
typedef struct {
unsigned long s0;
} charset_state;
/*
* Routine to convert a MB/SB character set to Unicode.
*
* This routine accepts some number of bytes, updates a state
* variable, and outputs some number of Unicode characters. There
* are no guarantees. You can't even guarantee that at most one
* Unicode character will be output per byte you feed in; for
* example, suppose you're reading UTF-8, you've seen E1 80, and
* then you suddenly see FE. Now you need to output _two_ error
* characters - one for the incomplete sequence E1 80, and one for
* the completely invalid UTF-8 byte FE.
*
* Returns the number of wide characters output; will never output
* more than the size of the buffer (as specified on input).
* Advances the `input' pointer and decrements `inlen', to indicate
* how far along the input string it got.
*
* The sequence of `errlen' wide characters pointed to by `errstr'
* will be used to indicate a conversion error. If `errstr' is
* NULL, `errlen' will be ignored, and the library will choose
* something sensible to do on its own. For Unicode, this will be
* U+FFFD (REPLACEMENT CHARACTER).
*/
int charset_to_unicode(char **input, int *inlen, wchar_t *output, int outlen,
int charset, charset_state *state,
const wchar_t *errstr, int errlen);
/*
* Routine to convert Unicode to an MB/SB character set.
*
* This routine accepts some number of Unicode characters, updates
* a state variable, and outputs some number of bytes.
*
* Returns the number of bytes characters output; will never output
* more than the size of the buffer (as specified on input), and
* will never output a partial MB character. Advances the `input'
* pointer and decrements `inlen', to indicate how far along the
* input string it got.
*
* The sequence of `errlen' characters pointed to by `errstr' will
* be used to indicate a conversion error. If `errstr' is NULL,
* `errlen' will be ignored, and the library will choose something
* sensible to do on its own (which will vary depending on the
* output charset).
*/
int charset_from_unicode(wchar_t **input, int *inlen, char *output, int outlen,
int charset, charset_state *state,
const char *errstr, int errlen);
/*
* Convert X11 encoding names to and from our charset identifiers.
*/
const char *charset_to_xenc(int charset);
int charset_from_xenc(const char *name);
/*
* Convert MIME encoding names to and from our charset identifiers.
*/
const char *charset_to_mimeenc(int charset);
int charset_from_mimeenc(const char *name);
/*
* Convert our own encoding names to and from our charset
* identifiers.
*/
const char *charset_to_localenc(int charset);
int charset_from_localenc(const char *name);
int charset_localenc_nth(int n);
/*
* Convert Mac OS script/region/font to our charset identifiers.
*/
int charset_from_macenc(int script, int region, int sysvers,
const char *fontname);
#endif /* charset_charset_h */

442
sFTPlugins/psftp/CMDLINE.C Normal file
View File

@@ -0,0 +1,442 @@
/*
* cmdline.c - command-line parsing shared between many of the
* PuTTY applications
*/
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "putty.h"
/*
* Some command-line parameters need to be saved up until after
* we've loaded the saved session which will form the basis of our
* eventual running configuration. For this we use the macro
* SAVEABLE, which notices if the `need_save' parameter is set and
* saves the parameter and value on a list.
*
* We also assign priorities to saved parameters, just to slightly
* ameliorate silly ordering problems. For example, if you specify
* a saved session to load, it will be loaded _before_ all your
* local modifications such as -L are evaluated; and if you specify
* a protocol and a port, the protocol is set up first so that the
* port can override its choice of port number.
*
* (In fact -load is not saved at all, since in at least Plink the
* processing of further command-line options depends on whether or
* not the loaded session contained a hostname. So it must be
* executed immediately.)
*/
#define NPRIORITIES 2
struct cmdline_saved_param {
char *p, *value;
};
struct cmdline_saved_param_set {
struct cmdline_saved_param *params;
int nsaved, savesize;
};
/*
* C guarantees this structure will be initialised to all zero at
* program start, which is exactly what we want.
*/
static struct cmdline_saved_param_set saves[NPRIORITIES];
static void cmdline_save_param(char *p, char *value, int pri)
{
if (saves[pri].nsaved >= saves[pri].savesize) {
saves[pri].savesize = saves[pri].nsaved + 32;
saves[pri].params = sresize(saves[pri].params, saves[pri].savesize,
struct cmdline_saved_param);
}
saves[pri].params[saves[pri].nsaved].p = p;
saves[pri].params[saves[pri].nsaved].value = value;
saves[pri].nsaved++;
}
void cmdline_cleanup(void)
{
int pri;
for (pri = 0; pri < NPRIORITIES; pri++)
sfree(saves[pri].params);
}
#define SAVEABLE(pri) do { \
if (need_save) { cmdline_save_param(p, value, pri); return ret; } \
} while (0)
static char *cmdline_password = NULL;
/*
* Similar interface to get_userpass_input(), except that here a -1
* return means that we aren't capable of processing the prompt and
* someone else should do it.
*/
int cmdline_get_passwd_input(prompts_t *p, unsigned char *in, int inlen) {
static int tried_once = 0;
/*
* We only handle prompts which don't echo (which we assume to be
* passwords), and (currently) we only cope with a password prompt
* that comes in a prompt-set on its own.
*/
if (!cmdline_password || in || p->n_prompts != 1 || p->prompts[0]->echo) {
return -1;
}
/*
* If we've tried once, return utter failure (no more passwords left
* to try).
*/
if (tried_once)
return 0;
strncpy(p->prompts[0]->result, cmdline_password,
p->prompts[0]->result_len);
p->prompts[0]->result[p->prompts[0]->result_len-1] = '\0';
memset(cmdline_password, 0, strlen(cmdline_password));
tried_once = 1;
return 1;
}
/*
* Here we have a flags word which describes the capabilities of
* the particular tool on whose behalf we're running. We will
* refuse certain command-line options if a particular tool
* inherently can't do anything sensible. For example, the file
* transfer tools (psftp, pscp) can't do a great deal with protocol
* selections (ever tried running scp over telnet?) or with port
* forwarding (even if it wasn't a hideously bad idea, they don't
* have the select() infrastructure to make them work).
*/
int cmdline_tooltype = 0;
static int cmdline_check_unavailable(int flag, char *p)
{
if (cmdline_tooltype & flag) {
cmdline_error("option \"%s\" not available in this tool", p);
return 1;
}
return 0;
}
#define UNAVAILABLE_IN(flag) do { \
if (cmdline_check_unavailable(flag, p)) return ret; \
} while (0)
/*
* Process a standard command-line parameter. `p' is the parameter
* in question; `value' is the subsequent element of argv, which
* may or may not be required as an operand to the parameter.
* If `need_save' is 1, arguments which need to be saved as
* described at this top of this file are, for later execution;
* if 0, they are processed normally. (-1 is a special value used
* by pterm to count arguments for a preliminary pass through the
* argument list; it causes immediate return with an appropriate
* value with no action taken.)
* Return value is 2 if both arguments were used; 1 if only p was
* used; 0 if the parameter wasn't one we recognised; -2 if it
* should have been 2 but value was NULL.
*/
#define RETURN(x) do { \
if ((x) == 2 && !value) return -2; \
ret = x; \
if (need_save < 0) return x; \
} while (0)
int cmdline_process_param(char *p, char *value, int need_save, Config *cfg)
{
int ret = 0;
if (!strcmp(p, "-load")) {
RETURN(2);
/* This parameter must be processed immediately rather than being
* saved. */
do_defaults(value, cfg);
loaded_session = TRUE;
return 2;
}
if (!strcmp(p, "-ssh")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
default_protocol = cfg->protocol = PROT_SSH;
default_port = cfg->port = 22;
return 1;
}
if (!strcmp(p, "-telnet")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
default_protocol = cfg->protocol = PROT_TELNET;
default_port = cfg->port = 23;
return 1;
}
if (!strcmp(p, "-rlogin")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
default_protocol = cfg->protocol = PROT_RLOGIN;
default_port = cfg->port = 513;
return 1;
}
if (!strcmp(p, "-raw")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
default_protocol = cfg->protocol = PROT_RAW;
}
if (!strcmp(p, "-v")) {
RETURN(1);
flags |= FLAG_VERBOSE;
}
if (!strcmp(p, "-l")) {
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
strncpy(cfg->username, value, sizeof(cfg->username));
cfg->username[sizeof(cfg->username) - 1] = '\0';
}
if ((!strcmp(p, "-L") || !strcmp(p, "-R") || !strcmp(p, "-D"))) {
char *fwd, *ptr, *q, *qq;
int dynamic, i=0;
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
dynamic = !strcmp(p, "-D");
fwd = value;
ptr = cfg->portfwd;
/* if existing forwards, find end of list */
while (*ptr) {
while (*ptr)
ptr++;
ptr++;
}
i = ptr - cfg->portfwd;
ptr[0] = p[1]; /* insert a 'L', 'R' or 'D' at the start */
ptr++;
if (1 + strlen(fwd) + 2 > sizeof(cfg->portfwd) - i) {
cmdline_error("out of space for port forwardings");
return ret;
}
strncpy(ptr, fwd, sizeof(cfg->portfwd) - i - 2);
if (!dynamic) {
/*
* We expect _at least_ two colons in this string. The
* possible formats are `sourceport:desthost:destport',
* or `sourceip:sourceport:desthost:destport' if you're
* specifying a particular loopback address. We need to
* replace the one between source and dest with a \t;
* this means we must find the second-to-last colon in
* the string.
*/
q = qq = strchr(ptr, ':');
while (qq) {
char *qqq = strchr(qq+1, ':');
if (qqq)
q = qq;
qq = qqq;
}
if (q) *q = '\t'; /* replace second-last colon with \t */
}
cfg->portfwd[sizeof(cfg->portfwd) - 1] = '\0';
cfg->portfwd[sizeof(cfg->portfwd) - 2] = '\0';
ptr[strlen(ptr)+1] = '\000'; /* append 2nd '\000' */
}
if ((!strcmp(p, "-nc"))) {
char *host, *portp;
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
host = portp = value;
while (*portp && *portp != ':')
portp++;
if (*portp) {
unsigned len = portp - host;
if (len >= sizeof(cfg->ssh_nc_host))
len = sizeof(cfg->ssh_nc_host) - 1;
strncpy(cfg->ssh_nc_host, value, len);
cfg->ssh_nc_host[sizeof(cfg->ssh_nc_host) - 1] = '\0';
cfg->ssh_nc_port = atoi(portp+1);
} else {
cmdline_error("-nc expects argument of form 'host:port'");
return ret;
}
}
if (!strcmp(p, "-m")) {
char *filename, *command;
int cmdlen, cmdsize;
FILE *fp;
int c, d;
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
filename = value;
cmdlen = cmdsize = 0;
command = NULL;
fp = fopen(filename, "r");
if (!fp) {
cmdline_error("unable to open command "
"file \"%s\"", filename);
return ret;
}
do {
c = fgetc(fp);
d = c;
if (c == EOF)
d = 0;
if (cmdlen >= cmdsize) {
cmdsize = cmdlen + 512;
command = sresize(command, cmdsize, char);
}
command[cmdlen++] = d;
} while (c != EOF);
cfg->remote_cmd_ptr = command;
cfg->remote_cmd_ptr2 = NULL;
cfg->nopty = TRUE; /* command => no terminal */
}
if (!strcmp(p, "-P")) {
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(1); /* lower priority than -ssh,-telnet */
cfg->port = atoi(value);
}
if (!strcmp(p, "-pw")) {
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(1);
/* We delay evaluating this until after the protocol is decided,
* so that we can warn if it's of no use with the selected protocol */
if (cfg->protocol != PROT_SSH)
cmdline_error("the -pw option can only be used with the "
"SSH protocol");
else {
cmdline_password = dupstr(value);
/* Assuming that `value' is directly from argv, make a good faith
* attempt to trample it, to stop it showing up in `ps' output
* on Unix-like systems. Not guaranteed, of course. */
memset(value, 0, strlen(value));
}
}
if (!strcmp(p, "-agent") || !strcmp(p, "-pagent") ||
!strcmp(p, "-pageant")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->tryagent = TRUE;
}
if (!strcmp(p, "-noagent") || !strcmp(p, "-nopagent") ||
!strcmp(p, "-nopageant")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->tryagent = FALSE;
}
if (!strcmp(p, "-A")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->agentfwd = 1;
}
if (!strcmp(p, "-a")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->agentfwd = 0;
}
if (!strcmp(p, "-X")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->x11_forward = 1;
}
if (!strcmp(p, "-x")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->x11_forward = 0;
}
if (!strcmp(p, "-t")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(1); /* lower priority than -m */
cfg->nopty = 0;
}
if (!strcmp(p, "-T")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(1);
cfg->nopty = 1;
}
if (!strcmp(p, "-N")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_FILETRANSFER | TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->ssh_no_shell = 1;
}
if (!strcmp(p, "-C")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->compression = 1;
}
if (!strcmp(p, "-1")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->sshprot = 0; /* ssh protocol 1 only */
}
if (!strcmp(p, "-2")) {
RETURN(1);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->sshprot = 3; /* ssh protocol 2 only */
}
if (!strcmp(p, "-i")) {
RETURN(2);
UNAVAILABLE_IN(TOOLTYPE_NONNETWORK);
SAVEABLE(0);
cfg->keyfile = filename_from_str(value);
}
if (!strcmp(p, "-4") || !strcmp(p, "-ipv4")) {
RETURN(1);
SAVEABLE(1);
cfg->addressfamily = ADDRTYPE_IPV4;
}
if (!strcmp(p, "-6") || !strcmp(p, "-ipv6")) {
RETURN(1);
SAVEABLE(1);
cfg->addressfamily = ADDRTYPE_IPV6;
}
return ret; /* unrecognised */
}
void cmdline_run_saved(Config *cfg)
{
int pri, i;
for (pri = 0; pri < NPRIORITIES; pri++)
for (i = 0; i < saves[pri].nsaved; i++)
cmdline_process_param(saves[pri].params[i].p,
saves[pri].params[i].value, 0, cfg);
}

190
sFTPlugins/psftp/CPROXY.C Normal file
View File

@@ -0,0 +1,190 @@
/*
* Routines to do cryptographic interaction with proxies in PuTTY.
* This is in a separate module from proxy.c, so that it can be
* conveniently removed in PuTTYtel by replacing this module with
* the stub version nocproxy.c.
*/
#include <assert.h>
#include <ctype.h>
#include <string.h>
#define DEFINE_PLUG_METHOD_MACROS
#include "putty.h"
#include "ssh.h" /* For MD5 support */
#include "network.h"
#include "proxy.h"
static void hmacmd5_chap(const unsigned char *challenge, int challen,
const char *passwd, unsigned char *response)
{
void *hmacmd5_ctx;
int pwlen;
hmacmd5_ctx = hmacmd5_make_context();
pwlen = strlen(passwd);
if (pwlen>64) {
unsigned char md5buf[16];
MD5Simple(passwd, pwlen, md5buf);
hmacmd5_key(hmacmd5_ctx, md5buf, 16);
} else {
hmacmd5_key(hmacmd5_ctx, passwd, pwlen);
}
hmacmd5_do_hmac(hmacmd5_ctx, challenge, challen, response);
hmacmd5_free_context(hmacmd5_ctx);
}
void proxy_socks5_offerencryptedauth(char *command, int *len)
{
command[*len] = 0x03; /* CHAP */
(*len)++;
}
int proxy_socks5_handlechap (Proxy_Socket p)
{
/* CHAP authentication reply format:
* version number (1 bytes) = 1
* number of commands (1 byte)
*
* For each command:
* command identifier (1 byte)
* data length (1 byte)
*/
unsigned char data[260];
unsigned char outbuf[20];
while(p->chap_num_attributes == 0 ||
p->chap_num_attributes_processed < p->chap_num_attributes) {
if (p->chap_num_attributes == 0 ||
p->chap_current_attribute == -1) {
/* CHAP normally reads in two bytes, either at the
* beginning or for each attribute/value pair. But if
* we're waiting for the value's data, we might not want
* to read 2 bytes.
*/
if (bufchain_size(&p->pending_input_data) < 2)
return 1; /* not got anything yet */
/* get the response */
bufchain_fetch(&p->pending_input_data, data, 2);
bufchain_consume(&p->pending_input_data, 2);
}
if (p->chap_num_attributes == 0) {
/* If there are no attributes, this is our first msg
* with the server, where we negotiate version and
* number of attributes
*/
if (data[0] != 0x01) {
plug_closing(p->plug, "Proxy error: SOCKS proxy wants"
" a different CHAP version",
PROXY_ERROR_GENERAL, 0);
return 1;
}
if (data[1] == 0x00) {
plug_closing(p->plug, "Proxy error: SOCKS proxy won't"
" negotiate CHAP with us",
PROXY_ERROR_GENERAL, 0);
return 1;
}
p->chap_num_attributes = data[1];
} else {
if (p->chap_current_attribute == -1) {
/* We have to read in each attribute/value pair -
* those we don't understand can be ignored, but
* there are a few we'll need to handle.
*/
p->chap_current_attribute = data[0];
p->chap_current_datalen = data[1];
}
if (bufchain_size(&p->pending_input_data) <
p->chap_current_datalen)
return 1; /* not got everything yet */
/* get the response */
bufchain_fetch(&p->pending_input_data, data,
p->chap_current_datalen);
bufchain_consume(&p->pending_input_data,
p->chap_current_datalen);
switch (p->chap_current_attribute) {
case 0x00:
/* Successful authentication */
if (data[0] == 0x00)
p->state = 2;
else {
plug_closing(p->plug, "Proxy error: SOCKS proxy"
" refused CHAP authentication",
PROXY_ERROR_GENERAL, 0);
return 1;
}
break;
case 0x03:
outbuf[0] = 0x01; /* Version */
outbuf[1] = 0x01; /* One attribute */
outbuf[2] = 0x04; /* Response */
outbuf[3] = 0x10; /* Length */
hmacmd5_chap(data, p->chap_current_datalen,
p->cfg.proxy_password, &outbuf[4]);
sk_write(p->sub_socket, (char *)outbuf, 20);
break;
case 0x11:
/* Chose a protocol */
if (data[0] != 0x85) {
plug_closing(p->plug, "Proxy error: Server chose "
"CHAP of other than HMAC-MD5 but we "
"didn't offer it!",
PROXY_ERROR_GENERAL, 0);
return 1;
}
break;
}
p->chap_current_attribute = -1;
p->chap_num_attributes_processed++;
}
if (p->state == 8 &&
p->chap_num_attributes_processed >= p->chap_num_attributes) {
p->chap_num_attributes = 0;
p->chap_num_attributes_processed = 0;
p->chap_current_datalen = 0;
}
}
return 0;
}
int proxy_socks5_selectchap(Proxy_Socket p)
{
if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
char chapbuf[514];
int ulen;
chapbuf[0] = '\x01'; /* Version */
chapbuf[1] = '\x02'; /* Number of attributes sent */
chapbuf[2] = '\x11'; /* First attribute - algorithms list */
chapbuf[3] = '\x01'; /* Only one CHAP algorithm */
chapbuf[4] = '\x85'; /* ...and it's HMAC-MD5, the core one */
chapbuf[5] = '\x02'; /* Second attribute - username */
ulen = strlen(p->cfg.proxy_username);
if (ulen > 255) ulen = 255; if (ulen < 1) ulen = 1;
chapbuf[6] = ulen;
memcpy(chapbuf+7, p->cfg.proxy_username, ulen);
sk_write(p->sub_socket, chapbuf, ulen + 7);
p->chap_num_attributes = 0;
p->chap_num_attributes_processed = 0;
p->chap_current_attribute = -1;
p->chap_current_datalen = 0;
p->state = 8;
} else
plug_closing(p->plug, "Proxy error: Server chose "
"CHAP authentication but we didn't offer it!",
PROXY_ERROR_GENERAL, 0);
return 1;
}

130
sFTPlugins/psftp/INT64.C Normal file
View File

@@ -0,0 +1,130 @@
/*
* Handling of the int64 and uint64 types. Done in 32-bit integers,
* for (pre-C99) portability. Hopefully once C99 becomes widespread
* we can kiss this lot goodbye...
*/
#include <assert.h>
#include <string.h>
#include "int64.h"
uint64 uint64_div10(uint64 x, int *remainder)
{
uint64 y;
int rem, r2;
y.hi = x.hi / 10;
y.lo = x.lo / 10;
rem = x.lo % 10;
/*
* Now we have to add in the remainder left over from x.hi.
*/
r2 = x.hi % 10;
y.lo += r2 * 2 * (0x80000000 / 10);
rem += r2 * 2 * (0x80000000 % 10);
y.lo += rem / 10;
rem %= 10;
if (remainder)
*remainder = rem;
return y;
}
void uint64_decimal(uint64 x, char *buffer)
{
char buf[20];
int start = 20;
int d;
do {
x = uint64_div10(x, &d);
assert(start > 0);
buf[--start] = d + '0';
} while (x.hi || x.lo);
memcpy(buffer, buf + start, sizeof(buf) - start);
buffer[sizeof(buf) - start] = '\0';
}
uint64 uint64_make(unsigned long hi, unsigned long lo)
{
uint64 y;
y.hi = hi;
y.lo = lo;
return y;
}
uint64 uint64_add(uint64 x, uint64 y)
{
x.lo += y.lo;
x.hi += y.hi + (x.lo < y.lo ? 1 : 0);
return x;
}
uint64 uint64_add32(uint64 x, unsigned long y)
{
uint64 yy;
yy.hi = 0;
yy.lo = y;
return uint64_add(x, yy);
}
int uint64_compare(uint64 x, uint64 y)
{
if (x.hi != y.hi)
return x.hi < y.hi ? -1 : +1;
if (x.lo != y.lo)
return x.lo < y.lo ? -1 : +1;
return 0;
}
uint64 uint64_subtract(uint64 x, uint64 y)
{
x.lo -= y.lo;
x.hi -= y.hi + (x.lo > ~y.lo ? 1 : 0);
return x;
}
double uint64_to_double(uint64 x)
{
return (4294967296.0 * x.hi) + (double)x.lo;
}
uint64 uint64_shift_right(uint64 x, int shift)
{
if (shift < 32) {
x.lo >>= shift;
x.lo |= (x.hi << (32-shift));
x.hi >>= shift;
} else {
x.lo = x.hi >> (shift-32);
x.hi = 0;
}
return x;
}
uint64 uint64_shift_left(uint64 x, int shift)
{
if (shift < 32) {
x.hi <<= shift;
x.hi |= (x.lo >> (32-shift));
x.lo <<= shift;
} else {
x.hi = x.lo << (shift-32);
x.lo = 0;
}
return x;
}
uint64 uint64_from_decimal(char *str)
{
uint64 ret;
ret.hi = ret.lo = 0;
while (*str >= '0' && *str <= '9') {
ret = uint64_add(uint64_shift_left(ret, 3),
uint64_shift_left(ret, 1));
ret = uint64_add32(ret, *str - '0');
str++;
}
return ret;
}

24
sFTPlugins/psftp/INT64.H Normal file
View File

@@ -0,0 +1,24 @@
/*
* Header for int64.c.
*/
#ifndef PUTTY_INT64_H
#define PUTTY_INT64_H
typedef struct {
unsigned long hi, lo;
} uint64;
uint64 uint64_div10(uint64 x, int *remainder);
void uint64_decimal(uint64 x, char *buffer);
uint64 uint64_make(unsigned long hi, unsigned long lo);
uint64 uint64_add(uint64 x, uint64 y);
uint64 uint64_add32(uint64 x, unsigned long y);
int uint64_compare(uint64 x, uint64 y);
uint64 uint64_subtract(uint64 x, uint64 y);
double uint64_to_double(uint64 x);
uint64 uint64_shift_right(uint64 x, int shift);
uint64 uint64_shift_left(uint64 x, int shift);
uint64 uint64_from_decimal(char *str);
#endif

415
sFTPlugins/psftp/LOGGING.C Normal file
View File

@@ -0,0 +1,415 @@
/*
* Session logging.
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include <assert.h>
#include "putty.h"
/* log session to file stuff ... */
struct LogContext {
FILE *lgfp;
enum { L_CLOSED, L_OPENING, L_OPEN, L_ERROR } state;
bufchain queue;
Filename currlogfilename;
void *frontend;
Config cfg;
};
static void xlatlognam(Filename *d, Filename s, char *hostname, struct tm *tm);
/*
* Internal wrapper function which must be called for _all_ output
* to the log file. It takes care of opening the log file if it
* isn't open, buffering data if it's in the process of being
* opened asynchronously, etc.
*/
static void logwrite(struct LogContext *ctx, void *data, int len)
{
/*
* In state L_CLOSED, we call logfopen, which will set the state
* to one of L_OPENING, L_OPEN or L_ERROR. Hence we process all of
* those three _after_ processing L_CLOSED.
*/
if (ctx->state == L_CLOSED)
logfopen(ctx);
if (ctx->state == L_OPENING) {
bufchain_add(&ctx->queue, data, len);
} else if (ctx->state == L_OPEN) {
assert(ctx->lgfp);
fwrite(data, 1, len, ctx->lgfp);
} /* else L_ERROR, so ignore the write */
}
/*
* Convenience wrapper on logwrite() which printf-formats the
* string.
*/
static void logprintf(struct LogContext *ctx, const char *fmt, ...)
{
va_list ap;
char *data;
va_start(ap, fmt);
data = dupvprintf(fmt, ap);
va_end(ap);
logwrite(ctx, data, strlen(data));
sfree(data);
}
/*
* Flush any open log file.
*/
void logflush(void *handle) {
struct LogContext *ctx = (struct LogContext *)handle;
if (ctx->cfg.logtype > 0)
if (ctx->state == L_OPEN)
fflush(ctx->lgfp);
}
static void logfopen_callback(void *handle, int mode)
{
struct LogContext *ctx = (struct LogContext *)handle;
char buf[256], *event;
struct tm tm;
const char *fmode;
if (mode == 0) {
ctx->state = L_ERROR; /* disable logging */
} else {
fmode = (mode == 1 ? "ab" : "wb");
ctx->lgfp = f_open(ctx->currlogfilename, fmode, TRUE);
if (ctx->lgfp)
ctx->state = L_OPEN;
else
ctx->state = L_ERROR;
}
if (ctx->state == L_OPEN) {
/* Write header line into log file. */
tm = ltime();
strftime(buf, 24, "%Y.%m.%d %H:%M:%S", &tm);
logprintf(ctx, "=~=~=~=~=~=~=~=~=~=~=~= PuTTY log %s"
" =~=~=~=~=~=~=~=~=~=~=~=\r\n", buf);
}
event = dupprintf("%s session log (%s mode) to file: %s",
(mode == 0 ? "Disabled writing" :
mode == 1 ? "Appending" : "Writing new"),
(ctx->cfg.logtype == LGTYP_ASCII ? "ASCII" :
ctx->cfg.logtype == LGTYP_DEBUG ? "raw" :
ctx->cfg.logtype == LGTYP_PACKETS ? "SSH packets" :
ctx->cfg.logtype == LGTYP_SSHRAW ? "SSH raw data" :
"unknown"),
filename_to_str(&ctx->currlogfilename));
logevent(ctx->frontend, event);
sfree(event);
/*
* Having either succeeded or failed in opening the log file,
* we should write any queued data out.
*/
assert(ctx->state != L_OPENING); /* make _sure_ it won't be requeued */
while (bufchain_size(&ctx->queue)) {
void *data;
int len;
bufchain_prefix(&ctx->queue, &data, &len);
logwrite(ctx, data, len);
bufchain_consume(&ctx->queue, len);
}
}
/*
* Open the log file. Takes care of detecting an already-existing
* file and asking the user whether they want to append, overwrite
* or cancel logging.
*/
void logfopen(void *handle)
{
struct LogContext *ctx = (struct LogContext *)handle;
struct tm tm;
int mode;
/* Prevent repeat calls */
if (ctx->state != L_CLOSED)
return;
if (!ctx->cfg.logtype)
return;
tm = ltime();
/* substitute special codes in file name */
xlatlognam(&ctx->currlogfilename, ctx->cfg.logfilename,ctx->cfg.host, &tm);
ctx->lgfp = f_open(ctx->currlogfilename, "r", FALSE); /* file already present? */
if (ctx->lgfp) {
fclose(ctx->lgfp);
if (ctx->cfg.logxfovr != LGXF_ASK) {
mode = ((ctx->cfg.logxfovr == LGXF_OVR) ? 2 : 1);
} else
mode = askappend(ctx->frontend, ctx->currlogfilename,
logfopen_callback, ctx);
} else
mode = 2; /* create == overwrite */
if (mode < 0)
ctx->state = L_OPENING;
else
logfopen_callback(ctx, mode); /* open the file */
}
void logfclose(void *handle)
{
struct LogContext *ctx = (struct LogContext *)handle;
if (ctx->lgfp) {
fclose(ctx->lgfp);
ctx->lgfp = NULL;
}
ctx->state = L_CLOSED;
}
/*
* Log session traffic.
*/
void logtraffic(void *handle, unsigned char c, int logmode)
{
struct LogContext *ctx = (struct LogContext *)handle;
if (ctx->cfg.logtype > 0) {
if (ctx->cfg.logtype == logmode)
logwrite(ctx, &c, 1);
}
}
/*
* Log an Event Log entry. Used in SSH packet logging mode; this is
* also as convenient a place as any to put the output of Event Log
* entries to stderr when a command-line tool is in verbose mode.
* (In particular, this is a better place to put it than in the
* front ends, because it only has to be done once for all
* platforms. Platforms which don't have a meaningful stderr can
* just avoid defining FLAG_STDERR.
*/
void log_eventlog(void *handle, const char *event)
{
struct LogContext *ctx = (struct LogContext *)handle;
if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) {
fprintf(stderr, "%s\n", event);
fflush(stderr);
}
/* If we don't have a context yet (eg winnet.c init) then skip entirely */
if (!ctx)
return;
if (ctx->cfg.logtype != LGTYP_PACKETS &&
ctx->cfg.logtype != LGTYP_SSHRAW)
return;
logprintf(ctx, "Event Log: %s\r\n", event);
logflush(ctx);
}
/*
* Log an SSH packet.
* If n_blanks != 0, blank or omit some parts.
* Set of blanking areas must be in increasing order.
*/
void log_packet(void *handle, int direction, int type,
char *texttype, void *data, int len,
int n_blanks, const struct logblank_t *blanks)
{
struct LogContext *ctx = (struct LogContext *)handle;
char dumpdata[80], smalldata[5];
int p = 0, b = 0, omitted = 0;
int output_pos = 0; /* NZ if pending output in dumpdata */
if (!(ctx->cfg.logtype == LGTYP_SSHRAW ||
(ctx->cfg.logtype == LGTYP_PACKETS && texttype)))
return;
/* Packet header. */
if (texttype)
logprintf(ctx, "%s packet type %d / 0x%02x (%s)\r\n",
direction == PKT_INCOMING ? "Incoming" : "Outgoing",
type, type, texttype);
else
logprintf(ctx, "%s raw data\r\n",
direction == PKT_INCOMING ? "Incoming" : "Outgoing");
/*
* Output a hex/ASCII dump of the packet body, blanking/omitting
* parts as specified.
*/
while (p < len) {
int blktype;
/* Move to a current entry in the blanking array. */
while ((b < n_blanks) &&
(p >= blanks[b].offset + blanks[b].len))
b++;
/* Work out what type of blanking to apply to
* this byte. */
blktype = PKTLOG_EMIT; /* default */
if ((b < n_blanks) &&
(p >= blanks[b].offset) &&
(p < blanks[b].offset + blanks[b].len))
blktype = blanks[b].type;
/* If we're about to stop omitting, it's time to say how
* much we omitted. */
if ((blktype != PKTLOG_OMIT) && omitted) {
logprintf(ctx, " (%d byte%s omitted)\r\n",
omitted, (omitted==1?"":"s"));
omitted = 0;
}
/* (Re-)initialise dumpdata as necessary
* (start of row, or if we've just stopped omitting) */
if (!output_pos && !omitted)
sprintf(dumpdata, " %08x%*s\r\n", p-(p%16), 1+3*16+2+16, "");
/* Deal with the current byte. */
if (blktype == PKTLOG_OMIT) {
omitted++;
} else {
int c;
if (blktype == PKTLOG_BLANK) {
c = 'X';
sprintf(smalldata, "XX");
} else { /* PKTLOG_EMIT */
c = ((unsigned char *)data)[p];
sprintf(smalldata, "%02x", c);
}
dumpdata[10+2+3*(p%16)] = smalldata[0];
dumpdata[10+2+3*(p%16)+1] = smalldata[1];
dumpdata[10+1+3*16+2+(p%16)] = (isprint(c) ? c : '.');
output_pos = (p%16) + 1;
}
p++;
/* Flush row if necessary */
if (((p % 16) == 0) || (p == len) || omitted) {
if (output_pos) {
strcpy(dumpdata + 10+1+3*16+2+output_pos, "\r\n");
logwrite(ctx, dumpdata, strlen(dumpdata));
output_pos = 0;
}
}
}
/* Tidy up */
if (omitted)
logprintf(ctx, " (%d byte%s omitted)\r\n",
omitted, (omitted==1?"":"s"));
logflush(ctx);
}
void *log_init(void *frontend, Config *cfg)
{
struct LogContext *ctx = snew(struct LogContext);
ctx->lgfp = NULL;
ctx->state = L_CLOSED;
ctx->frontend = frontend;
ctx->cfg = *cfg; /* STRUCTURE COPY */
bufchain_init(&ctx->queue);
return ctx;
}
void log_free(void *handle)
{
struct LogContext *ctx = (struct LogContext *)handle;
logfclose(ctx);
bufchain_clear(&ctx->queue);
sfree(ctx);
}
void log_reconfig(void *handle, Config *cfg)
{
struct LogContext *ctx = (struct LogContext *)handle;
int reset_logging;
if (!filename_equal(ctx->cfg.logfilename, cfg->logfilename) ||
ctx->cfg.logtype != cfg->logtype)
reset_logging = TRUE;
else
reset_logging = FALSE;
if (reset_logging)
logfclose(ctx);
ctx->cfg = *cfg; /* STRUCTURE COPY */
if (reset_logging)
logfopen(ctx);
}
/*
* translate format codes into time/date strings
* and insert them into log file name
*
* "&Y":YYYY "&m":MM "&d":DD "&T":hhmmss "&h":<hostname> "&&":&
*/
static void xlatlognam(Filename *dest, Filename src,
char *hostname, struct tm *tm) {
char buf[10], *bufp;
int size;
char buffer[FILENAME_MAX];
int len = sizeof(buffer)-1;
char *d;
const char *s;
d = buffer;
s = filename_to_str(&src);
while (*s) {
/* Let (bufp, len) be the string to append. */
bufp = buf; /* don't usually override this */
if (*s == '&') {
char c;
s++;
size = 0;
if (*s) switch (c = *s++, tolower(c)) {
case 'y':
size = strftime(buf, sizeof(buf), "%Y", tm);
break;
case 'm':
size = strftime(buf, sizeof(buf), "%m", tm);
break;
case 'd':
size = strftime(buf, sizeof(buf), "%d", tm);
break;
case 't':
size = strftime(buf, sizeof(buf), "%H%M%S", tm);
break;
case 'h':
bufp = hostname;
size = strlen(bufp);
break;
default:
buf[0] = '&';
size = 1;
if (c != '&')
buf[size++] = c;
}
} else {
buf[0] = *s++;
size = 1;
}
if (size > len)
size = len;
memcpy(d, bufp, size);
d += size;
len -= size;
}
*d = '\0';
*dest = filename_from_str(buffer);
}

View File

@@ -0,0 +1,69 @@
/*
* macstuff.h -- Mac-specific definitions visible to the rest of PuTTY.
*/
typedef void *Context; /* FIXME */
#include <MacTypes.h>
#include <Files.h>
#include <stdio.h>
#include "charset.h"
struct Filename {
FSSpec fss;
};
extern FILE * f_open(struct Filename, char const *, int);
/* Suspiciously similar to an ICFontRecord */
struct FontSpec {
short size;
Style face;
char pad;
Str255 name;
};
/*
* On the Mac, Unicode text copied to the clipboard has U+2028 line separators.
* Non-Unicode text will have these converted to CR along with the rest of the
* content.
*/
#define SEL_NL { 0x2028 }
#include <MacTypes.h>
#include <Events.h> /* Timing related goo */
#define GETTICKCOUNT TickCount
#define CURSORBLINK GetCaretTime()
#define TICKSPERSEC 60
#define DEFAULT_CODEPAGE 0 /* FIXME: no idea how to do this */
#define WCHAR wchar_t
#define BYTE UInt8
#define DWORD UInt32
#define OPTIMISE_SCROLL
/*
* sk_getxdmdata() does not exist under the Mac (SGT: I have no
* idea whatsoever how to write it, and furthermore I'm unconvinced
* it's necessary), so it's a macro which always returns NULL.
*/
#define sk_getxdmdata(socket, lenp) (NULL)
/* To make it compile */
#include <stdarg.h>
extern int vsnprintf(char *, size_t, char const *, va_list);
extern int stricmp(char const *, char const *);
extern int strnicmp(char const *, char const *, size_t);
#define HELPCTX(foo) I(0)
#define FILTER_KEY_FILES "pAgt.PPK"
#define CP_UTF8 CS_UTF8 /* from libcharset */

View File

@@ -0,0 +1,34 @@
#ifndef PUTTY_OSX_H
#define PUTTY_OSX_H
/*
* Cocoa defines `FontSpec' itself, so we must change its name.
* (Arrgh.)
*/
#define FontSpec FontSpec_OSX_Proof
/*
* Define the various compatibility symbols to make uxpty.c compile
* correctly on OS X.
*/
#define BSD_PTYS
#define OMIT_UTMP
#define HAVE_NO_SETRESUID
#define NOT_X_WINDOWS
/*
* OS X is largely just Unix, so we can include most of this
* unchanged.
*/
#include "unix.h"
/*
* Functions exported by osxsel.m. (Both of these functions are
* expected to be called in the _main_ thread: the select subthread
* is an implementation detail of osxsel.m and ideally should not
* be visible at all outside it.)
*/
void osxsel_init(void); /* call this to kick things off */
void osxsel_process_results(void); /* call this on receipt of a netevent */
#endif

655
sFTPlugins/psftp/MISC.C Normal file
View File

@@ -0,0 +1,655 @@
/*
* Platform-independent routines shared between all PuTTY programs.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <limits.h>
#include <ctype.h>
#include <assert.h>
#include "putty.h"
/*
* Parse a string block size specification. This is approximately a
* subset of the block size specs supported by GNU fileutils:
* "nk" = n kilobytes
* "nM" = n megabytes
* "nG" = n gigabytes
* All numbers are decimal, and suffixes refer to powers of two.
* Case-insensitive.
*/
unsigned long parse_blocksize(const char *bs)
{
char *suf;
unsigned long r = strtoul(bs, &suf, 10);
if (*suf != '\0') {
while (*suf && isspace((unsigned char)*suf)) suf++;
switch (*suf) {
case 'k': case 'K':
r *= 1024ul;
break;
case 'm': case 'M':
r *= 1024ul * 1024ul;
break;
case 'g': case 'G':
r *= 1024ul * 1024ul * 1024ul;
break;
case '\0':
default:
break;
}
}
return r;
}
/*
* Parse a ^C style character specification.
* Returns NULL in `next' if we didn't recognise it as a control character,
* in which case `c' should be ignored.
* The precise current parsing is an oddity inherited from the terminal
* answerback-string parsing code. All sequences start with ^; all except
* ^<123> are two characters. The ones that are worth keeping are probably:
* ^? 127
* ^@A-Z[\]^_ 0-31
* a-z 1-26
* <num> specified by number (decimal, 0octal, 0xHEX)
* ~ ^ escape
*/
char ctrlparse(char *s, char **next)
{
char c = 0;
if (*s != '^') {
*next = NULL;
} else {
s++;
if (*s == '\0') {
*next = NULL;
} else if (*s == '<') {
s++;
c = (char)strtol(s, next, 0);
if ((*next == s) || (**next != '>')) {
c = 0;
*next = NULL;
} else
(*next)++;
} else if (*s >= 'a' && *s <= 'z') {
c = (*s - ('a' - 1));
*next = s+1;
} else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
c = ('@' ^ *s);
*next = s+1;
} else if (*s == '~') {
c = '^';
*next = s+1;
}
}
return c;
}
prompts_t *new_prompts(void *frontend)
{
prompts_t *p = snew(prompts_t);
p->prompts = NULL;
p->n_prompts = 0;
p->frontend = frontend;
p->data = NULL;
p->to_server = TRUE; /* to be on the safe side */
p->name = p->instruction = NULL;
p->name_reqd = p->instr_reqd = FALSE;
return p;
}
void add_prompt(prompts_t *p, char *promptstr, int echo, size_t len)
{
prompt_t *pr = snew(prompt_t);
char *result = snewn(len, char);
pr->prompt = promptstr;
pr->echo = echo;
pr->result = result;
pr->result_len = len;
p->n_prompts++;
p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
p->prompts[p->n_prompts-1] = pr;
}
void free_prompts(prompts_t *p)
{
size_t i;
for (i=0; i < p->n_prompts; i++) {
prompt_t *pr = p->prompts[i];
memset(pr->result, 0, pr->result_len); /* burn the evidence */
sfree(pr->result);
sfree(pr->prompt);
sfree(pr);
}
sfree(p->prompts);
sfree(p->name);
sfree(p->instruction);
sfree(p);
}
/* ----------------------------------------------------------------------
* String handling routines.
*/
char *dupstr(const char *s)
{
char *p = NULL;
if (s) {
int len = strlen(s);
p = snewn(len + 1, char);
strcpy(p, s);
}
return p;
}
/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
char *dupcat(const char *s1, ...)
{
int len;
char *p, *q, *sn;
va_list ap;
len = strlen(s1);
va_start(ap, s1);
while (1) {
sn = va_arg(ap, char *);
if (!sn)
break;
len += strlen(sn);
}
va_end(ap);
p = snewn(len + 1, char);
strcpy(p, s1);
q = p + strlen(p);
va_start(ap, s1);
while (1) {
sn = va_arg(ap, char *);
if (!sn)
break;
strcpy(q, sn);
q += strlen(q);
}
va_end(ap);
return p;
}
/*
* Do an sprintf(), but into a custom-allocated buffer.
*
* Currently I'm doing this via vsnprintf. This has worked so far,
* but it's not good, because vsnprintf is not available on all
* platforms. There's an ifdef to use `_vsnprintf', which seems
* to be the local name for it on Windows. Other platforms may
* lack it completely, in which case it'll be time to rewrite
* this function in a totally different way.
*
* The only `properly' portable solution I can think of is to
* implement my own format string scanner, which figures out an
* upper bound for the length of each formatting directive,
* allocates the buffer as it goes along, and calls sprintf() to
* actually process each directive. If I ever need to actually do
* this, some caveats:
*
* - It's very hard to find a reliable upper bound for
* floating-point values. %f, in particular, when supplied with
* a number near to the upper or lower limit of representable
* numbers, could easily take several hundred characters. It's
* probably feasible to predict this statically using the
* constants in <float.h>, or even to predict it dynamically by
* looking at the exponent of the specific float provided, but
* it won't be fun.
*
* - Don't forget to _check_, after calling sprintf, that it's
* used at most the amount of space we had available.
*
* - Fault any formatting directive we don't fully understand. The
* aim here is to _guarantee_ that we never overflow the buffer,
* because this is a security-critical function. If we see a
* directive we don't know about, we should panic and die rather
* than run any risk.
*/
char *dupprintf(const char *fmt, ...)
{
char *ret;
va_list ap;
va_start(ap, fmt);
ret = dupvprintf(fmt, ap);
va_end(ap);
return ret;
}
char *dupvprintf(const char *fmt, va_list ap)
{
char *buf;
int len, size;
buf = snewn(512, char);
size = 512;
while (1) {
#ifdef _WINDOWS
#define vsnprintf _vsnprintf
#endif
#ifdef va_copy
/* Use the `va_copy' macro mandated by C99, if present.
* XXX some environments may have this as __va_copy() */
va_list aq;
va_copy(aq, ap);
len = vsnprintf(buf, size, fmt, aq);
va_end(aq);
#else
/* Ugh. No va_copy macro, so do something nasty.
* Technically, you can't reuse a va_list like this: it is left
* unspecified whether advancing a va_list pointer modifies its
* value or something it points to, so on some platforms calling
* vsnprintf twice on the same va_list might fail hideously
* (indeed, it has been observed to).
* XXX the autoconf manual suggests that using memcpy() will give
* "maximum portability". */
len = vsnprintf(buf, size, fmt, ap);
#endif
if (len >= 0 && len < size) {
/* This is the C99-specified criterion for snprintf to have
* been completely successful. */
return buf;
} else if (len > 0) {
/* This is the C99 error condition: the returned length is
* the required buffer size not counting the NUL. */
size = len + 1;
} else {
/* This is the pre-C99 glibc error condition: <0 means the
* buffer wasn't big enough, so we enlarge it a bit and hope. */
size += 512;
}
buf = sresize(buf, size, char);
}
}
/*
* Read an entire line of text from a file. Return a buffer
* malloced to be as big as necessary (caller must free).
*/
char *fgetline(FILE *fp)
{
char *ret = snewn(512, char);
int size = 512, len = 0;
while (fgets(ret + len, size - len, fp)) {
len += strlen(ret + len);
if (ret[len-1] == '\n')
break; /* got a newline, we're done */
size = len + 512;
ret = sresize(ret, size, char);
}
if (len == 0) { /* first fgets returned NULL */
sfree(ret);
return NULL;
}
ret[len] = '\0';
return ret;
}
/* ----------------------------------------------------------------------
* Base64 encoding routine. This is required in public-key writing
* but also in HTTP proxy handling, so it's centralised here.
*/
void base64_encode_atom(unsigned char *data, int n, char *out)
{
static const char base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned word;
word = data[0] << 16;
if (n > 1)
word |= data[1] << 8;
if (n > 2)
word |= data[2];
out[0] = base64_chars[(word >> 18) & 0x3F];
out[1] = base64_chars[(word >> 12) & 0x3F];
if (n > 1)
out[2] = base64_chars[(word >> 6) & 0x3F];
else
out[2] = '=';
if (n > 2)
out[3] = base64_chars[word & 0x3F];
else
out[3] = '=';
}
/* ----------------------------------------------------------------------
* Generic routines to deal with send buffers: a linked list of
* smallish blocks, with the operations
*
* - add an arbitrary amount of data to the end of the list
* - remove the first N bytes from the list
* - return a (pointer,length) pair giving some initial data in
* the list, suitable for passing to a send or write system
* call
* - retrieve a larger amount of initial data from the list
* - return the current size of the buffer chain in bytes
*/
#define BUFFER_GRANULE 512
struct bufchain_granule {
struct bufchain_granule *next;
int buflen, bufpos;
char buf[BUFFER_GRANULE];
};
void bufchain_init(bufchain *ch)
{
ch->head = ch->tail = NULL;
ch->buffersize = 0;
}
void bufchain_clear(bufchain *ch)
{
struct bufchain_granule *b;
while (ch->head) {
b = ch->head;
ch->head = ch->head->next;
sfree(b);
}
ch->tail = NULL;
ch->buffersize = 0;
}
int bufchain_size(bufchain *ch)
{
return ch->buffersize;
}
void bufchain_add(bufchain *ch, const void *data, int len)
{
const char *buf = (const char *)data;
if (len == 0) return;
ch->buffersize += len;
if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
buf += copylen;
len -= copylen;
ch->tail->buflen += copylen;
}
while (len > 0) {
int grainlen = min(len, BUFFER_GRANULE);
struct bufchain_granule *newbuf;
newbuf = snew(struct bufchain_granule);
newbuf->bufpos = 0;
newbuf->buflen = grainlen;
memcpy(newbuf->buf, buf, grainlen);
buf += grainlen;
len -= grainlen;
if (ch->tail)
ch->tail->next = newbuf;
else
ch->head = ch->tail = newbuf;
newbuf->next = NULL;
ch->tail = newbuf;
}
}
void bufchain_consume(bufchain *ch, int len)
{
struct bufchain_granule *tmp;
assert(ch->buffersize >= len);
while (len > 0) {
int remlen = len;
assert(ch->head != NULL);
if (remlen >= ch->head->buflen - ch->head->bufpos) {
remlen = ch->head->buflen - ch->head->bufpos;
tmp = ch->head;
ch->head = tmp->next;
sfree(tmp);
if (!ch->head)
ch->tail = NULL;
} else
ch->head->bufpos += remlen;
ch->buffersize -= remlen;
len -= remlen;
}
}
void bufchain_prefix(bufchain *ch, void **data, int *len)
{
*len = ch->head->buflen - ch->head->bufpos;
*data = ch->head->buf + ch->head->bufpos;
}
void bufchain_fetch(bufchain *ch, void *data, int len)
{
struct bufchain_granule *tmp;
char *data_c = (char *)data;
tmp = ch->head;
assert(ch->buffersize >= len);
while (len > 0) {
int remlen = len;
assert(tmp != NULL);
if (remlen >= tmp->buflen - tmp->bufpos)
remlen = tmp->buflen - tmp->bufpos;
memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
tmp = tmp->next;
len -= remlen;
data_c += remlen;
}
}
/* ----------------------------------------------------------------------
* My own versions of malloc, realloc and free. Because I want
* malloc and realloc to bomb out and exit the program if they run
* out of memory, realloc to reliably call malloc if passed a NULL
* pointer, and free to reliably do nothing if passed a NULL
* pointer. We can also put trace printouts in, if we need to; and
* we can also replace the allocator with an ElectricFence-like
* one.
*/
#ifdef MINEFIELD
void *minefield_c_malloc(size_t size);
void minefield_c_free(void *p);
void *minefield_c_realloc(void *p, size_t size);
#endif
#ifdef MALLOC_LOG
static FILE *fp = NULL;
static char *mlog_file = NULL;
static int mlog_line = 0;
void mlog(char *file, int line)
{
mlog_file = file;
mlog_line = line;
if (!fp) {
fp = fopen("putty_mem.log", "w");
setvbuf(fp, NULL, _IONBF, BUFSIZ);
}
if (fp)
fprintf(fp, "%s:%d: ", file, line);
}
#endif
void *safemalloc(size_t n, size_t size)
{
void *p;
if (n > INT_MAX / size) {
p = NULL;
} else {
size *= n;
if (size == 0) size = 1;
#ifdef MINEFIELD
p = minefield_c_malloc(size);
#else
p = malloc(size);
#endif
}
if (!p) {
char str[200];
#ifdef MALLOC_LOG
sprintf(str, "Out of memory! (%s:%d, size=%d)",
mlog_file, mlog_line, size);
fprintf(fp, "*** %s\n", str);
fclose(fp);
#else
strcpy(str, "Out of memory!");
#endif
modalfatalbox(str);
}
#ifdef MALLOC_LOG
if (fp)
fprintf(fp, "malloc(%d) returns %p\n", size, p);
#endif
return p;
}
void *saferealloc(void *ptr, size_t n, size_t size)
{
void *p;
if (n > INT_MAX / size) {
p = NULL;
} else {
size *= n;
if (!ptr) {
#ifdef MINEFIELD
p = minefield_c_malloc(size);
#else
p = malloc(size);
#endif
} else {
#ifdef MINEFIELD
p = minefield_c_realloc(ptr, size);
#else
p = realloc(ptr, size);
#endif
}
}
if (!p) {
char str[200];
#ifdef MALLOC_LOG
sprintf(str, "Out of memory! (%s:%d, size=%d)",
mlog_file, mlog_line, size);
fprintf(fp, "*** %s\n", str);
fclose(fp);
#else
strcpy(str, "Out of memory!");
#endif
modalfatalbox(str);
}
#ifdef MALLOC_LOG
if (fp)
fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
#endif
return p;
}
void safefree(void *ptr)
{
if (ptr) {
#ifdef MALLOC_LOG
if (fp)
fprintf(fp, "free(%p)\n", ptr);
#endif
#ifdef MINEFIELD
minefield_c_free(ptr);
#else
free(ptr);
#endif
}
#ifdef MALLOC_LOG
else if (fp)
fprintf(fp, "freeing null pointer - no action taken\n");
#endif
}
/* ----------------------------------------------------------------------
* Debugging routines.
*/
#ifdef DEBUG
extern void dputs(char *); /* defined in per-platform *misc.c */
void debug_printf(char *fmt, ...)
{
char *buf;
va_list ap;
va_start(ap, fmt);
buf = dupvprintf(fmt, ap);
dputs(buf);
sfree(buf);
va_end(ap);
}
void debug_memdump(void *buf, int len, int L)
{
int i;
unsigned char *p = buf;
char foo[17];
if (L) {
int delta;
debug_printf("\t%d (0x%x) bytes:\n", len, len);
delta = 15 & (int) p;
p -= delta;
len += delta;
}
for (; 0 < len; p += 16, len -= 16) {
dputs(" ");
if (L)
debug_printf("%p: ", p);
strcpy(foo, "................"); /* sixteen dots */
for (i = 0; i < 16 && i < len; ++i) {
if (&p[i] < (unsigned char *) buf) {
dputs(" "); /* 3 spaces */
foo[i] = ' ';
} else {
debug_printf("%c%02.2x",
&p[i] != (unsigned char *) buf
&& i % 4 ? '.' : ' ', p[i]
);
if (p[i] >= ' ' && p[i] <= '~')
foo[i] = (char) p[i];
}
}
foo[i] = '\0';
debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
}
}
#endif /* def DEBUG */
/*
* Determine whether or not a Config structure represents a session
* which can sensibly be launched right now.
*/
int cfg_launchable(const Config *cfg)
{
if (cfg->protocol == PROT_SERIAL)
return cfg->serline[0] != 0;
else
return cfg->host[0] != 0;
}
char const *cfg_dest(const Config *cfg)
{
if (cfg->protocol == PROT_SERIAL)
return cfg->serline;
else
return cfg->host;
}

132
sFTPlugins/psftp/MISC.H Normal file
View File

@@ -0,0 +1,132 @@
/*
* Header for misc.c.
*/
#ifndef PUTTY_MISC_H
#define PUTTY_MISC_H
#include "puttymem.h"
#include <stdio.h> /* for FILE * */
#include <stdarg.h> /* for va_list */
#include <time.h> /* for struct tm */
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
typedef struct Filename Filename;
typedef struct FontSpec FontSpec;
unsigned long parse_blocksize(const char *bs);
char ctrlparse(char *s, char **next);
char *dupstr(const char *s);
char *dupcat(const char *s1, ...);
char *dupprintf(const char *fmt, ...);
char *dupvprintf(const char *fmt, va_list ap);
char *fgetline(FILE *fp);
void base64_encode_atom(unsigned char *data, int n, char *out);
struct bufchain_granule;
typedef struct bufchain_tag {
struct bufchain_granule *head, *tail;
int buffersize; /* current amount of buffered data */
} bufchain;
void bufchain_init(bufchain *ch);
void bufchain_clear(bufchain *ch);
int bufchain_size(bufchain *ch);
void bufchain_add(bufchain *ch, const void *data, int len);
void bufchain_prefix(bufchain *ch, void **data, int *len);
void bufchain_consume(bufchain *ch, int len);
void bufchain_fetch(bufchain *ch, void *data, int len);
struct tm ltime(void);
/*
* Debugging functions.
*
* Output goes to debug.log
*
* debug(()) (note the double brackets) is like printf().
*
* dmemdump() and dmemdumpl() both do memory dumps. The difference
* is that dmemdumpl() is more suited for when the memory address is
* important (say because you'll be recording pointer values later
* on). dmemdump() is more concise.
*/
#ifdef DEBUG
void debug_printf(char *fmt, ...);
void debug_memdump(void *buf, int len, int L);
#define debug(x) (debug_printf x)
#define dmemdump(buf,len) debug_memdump (buf, len, 0);
#define dmemdumpl(buf,len) debug_memdump (buf, len, 1);
#else
#define debug(x)
#define dmemdump(buf,len)
#define dmemdumpl(buf,len)
#endif
#ifndef lenof
#define lenof(x) ( (sizeof((x))) / (sizeof(*(x))))
#endif
#ifndef min
#define min(x,y) ( (x) < (y) ? (x) : (y) )
#endif
#ifndef max
#define max(x,y) ( (x) > (y) ? (x) : (y) )
#endif
#define GET_32BIT_LSB_FIRST(cp) \
(((unsigned long)(unsigned char)(cp)[0]) | \
((unsigned long)(unsigned char)(cp)[1] << 8) | \
((unsigned long)(unsigned char)(cp)[2] << 16) | \
((unsigned long)(unsigned char)(cp)[3] << 24))
#define PUT_32BIT_LSB_FIRST(cp, value) ( \
(cp)[0] = (unsigned char)(value), \
(cp)[1] = (unsigned char)((value) >> 8), \
(cp)[2] = (unsigned char)((value) >> 16), \
(cp)[3] = (unsigned char)((value) >> 24) )
#define GET_16BIT_LSB_FIRST(cp) \
(((unsigned long)(unsigned char)(cp)[0]) | \
((unsigned long)(unsigned char)(cp)[1] << 8))
#define PUT_16BIT_LSB_FIRST(cp, value) ( \
(cp)[0] = (unsigned char)(value), \
(cp)[1] = (unsigned char)((value) >> 8) )
#define GET_32BIT_MSB_FIRST(cp) \
(((unsigned long)(unsigned char)(cp)[0] << 24) | \
((unsigned long)(unsigned char)(cp)[1] << 16) | \
((unsigned long)(unsigned char)(cp)[2] << 8) | \
((unsigned long)(unsigned char)(cp)[3]))
#define GET_32BIT(cp) GET_32BIT_MSB_FIRST(cp)
#define PUT_32BIT_MSB_FIRST(cp, value) ( \
(cp)[0] = (unsigned char)((value) >> 24), \
(cp)[1] = (unsigned char)((value) >> 16), \
(cp)[2] = (unsigned char)((value) >> 8), \
(cp)[3] = (unsigned char)(value) )
#define PUT_32BIT(cp, value) PUT_32BIT_MSB_FIRST(cp, value)
#define GET_16BIT_MSB_FIRST(cp) \
(((unsigned long)(unsigned char)(cp)[0] << 8) | \
((unsigned long)(unsigned char)(cp)[1]))
#define PUT_16BIT_MSB_FIRST(cp, value) ( \
(cp)[0] = (unsigned char)((value) >> 8), \
(cp)[1] = (unsigned char)(value) )
#endif

235
sFTPlugins/psftp/NETWORK.H Normal file
View File

@@ -0,0 +1,235 @@
/*
* Networking abstraction in PuTTY.
*
* The way this works is: a back end can choose to open any number
* of sockets - including zero, which might be necessary in some.
* It can register a bunch of callbacks (most notably for when
* data is received) for each socket, and it can call the networking
* abstraction to send data without having to worry about blocking.
* The stuff behind the abstraction takes care of selects and
* nonblocking writes and all that sort of painful gubbins.
*/
#ifndef PUTTY_NETWORK_H
#define PUTTY_NETWORK_H
#ifndef DONE_TYPEDEFS
#define DONE_TYPEDEFS
typedef struct config_tag Config;
typedef struct backend_tag Backend;
typedef struct terminal_tag Terminal;
#endif
typedef struct SockAddr_tag *SockAddr;
/* pay attention to levels of indirection */
typedef struct socket_function_table **Socket;
typedef struct plug_function_table **Plug;
#ifndef OSSOCKET_DEFINED
typedef void *OSSocket;
#endif
struct socket_function_table {
Plug(*plug) (Socket s, Plug p);
/* use a different plug (return the old one) */
/* if p is NULL, it doesn't change the plug */
/* but it does return the one it's using */
void (*close) (Socket s);
int (*write) (Socket s, const char *data, int len);
int (*write_oob) (Socket s, const char *data, int len);
void (*flush) (Socket s);
void (*set_private_ptr) (Socket s, void *ptr);
void *(*get_private_ptr) (Socket s);
void (*set_frozen) (Socket s, int is_frozen);
/* ignored by tcp, but vital for ssl */
const char *(*socket_error) (Socket s);
};
struct plug_function_table {
void (*log)(Plug p, int type, SockAddr addr, int port,
const char *error_msg, int error_code);
/*
* Passes the client progress reports on the process of setting
* up the connection.
*
* - type==0 means we are about to try to connect to address
* `addr' (error_msg and error_code are ignored)
* - type==1 means we have failed to connect to address `addr'
* (error_msg and error_code are supplied). This is not a
* fatal error - we may well have other candidate addresses
* to fall back to. When it _is_ fatal, the closing()
* function will be called.
*/
int (*closing)
(Plug p, const char *error_msg, int error_code, int calling_back);
/* error_msg is NULL iff it is not an error (ie it closed normally) */
/* calling_back != 0 iff there is a Plug function */
/* currently running (would cure the fixme in try_send()) */
int (*receive) (Plug p, int urgent, char *data, int len);
/*
* - urgent==0. `data' points to `len' bytes of perfectly
* ordinary data.
*
* - urgent==1. `data' points to `len' bytes of data,
* which were read from before an Urgent pointer.
*
* - urgent==2. `data' points to `len' bytes of data,
* the first of which was the one at the Urgent mark.
*/
void (*sent) (Plug p, int bufsize);
/*
* The `sent' function is called when the pending send backlog
* on a socket is cleared or partially cleared. The new backlog
* size is passed in the `bufsize' parameter.
*/
int (*accepting)(Plug p, OSSocket sock);
/*
* returns 0 if the host at address addr is a valid host for connecting or error
*/
};
/* proxy indirection layer */
/* NB, control of 'addr' is passed via new_connection, which takes
* responsibility for freeing it */
Socket new_connection(SockAddr addr, char *hostname,
int port, int privport,
int oobinline, int nodelay, int keepalive,
Plug plug, const Config *cfg);
Socket new_listener(char *srcaddr, int port, Plug plug, int local_host_only,
const Config *cfg, int addressfamily);
SockAddr name_lookup(char *host, int port, char **canonicalname,
const Config *cfg, int addressfamily);
/* platform-dependent callback from new_connection() */
/* (same caveat about addr as new_connection()) */
Socket platform_new_connection(SockAddr addr, char *hostname,
int port, int privport,
int oobinline, int nodelay, int keepalive,
Plug plug, const Config *cfg);
/* socket functions */
void sk_init(void); /* called once at program startup */
void sk_cleanup(void); /* called just before program exit */
SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family);
SockAddr sk_nonamelookup(const char *host);
void sk_getaddr(SockAddr addr, char *buf, int buflen);
int sk_hostname_is_local(char *name);
int sk_address_is_local(SockAddr addr);
int sk_addrtype(SockAddr addr);
void sk_addrcopy(SockAddr addr, char *buf);
void sk_addr_free(SockAddr addr);
/* NB, control of 'addr' is passed via sk_new, which takes responsibility
* for freeing it, as for new_connection() */
Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
int nodelay, int keepalive, Plug p);
Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int address_family);
Socket sk_register(OSSocket sock, Plug plug);
#define sk_plug(s,p) (((*s)->plug) (s, p))
#define sk_close(s) (((*s)->close) (s))
#define sk_write(s,buf,len) (((*s)->write) (s, buf, len))
#define sk_write_oob(s,buf,len) (((*s)->write_oob) (s, buf, len))
#define sk_flush(s) (((*s)->flush) (s))
#ifdef DEFINE_PLUG_METHOD_MACROS
#define plug_log(p,type,addr,port,msg,code) (((*p)->log) (p, type, addr, port, msg, code))
#define plug_closing(p,msg,code,callback) (((*p)->closing) (p, msg, code, callback))
#define plug_receive(p,urgent,buf,len) (((*p)->receive) (p, urgent, buf, len))
#define plug_sent(p,bufsize) (((*p)->sent) (p, bufsize))
#define plug_accepting(p, sock) (((*p)->accepting)(p, sock))
#endif
/*
* Each socket abstraction contains a `void *' private field in
* which the client can keep state.
*
* This is perhaps unnecessary now that we have the notion of a plug,
* but there is some existing code that uses it, so it stays.
*/
#define sk_set_private_ptr(s, ptr) (((*s)->set_private_ptr) (s, ptr))
#define sk_get_private_ptr(s) (((*s)->get_private_ptr) (s))
/*
* Special error values are returned from sk_namelookup and sk_new
* if there's a problem. These functions extract an error message,
* or return NULL if there's no problem.
*/
const char *sk_addr_error(SockAddr addr);
#define sk_socket_error(s) (((*s)->socket_error) (s))
/*
* Set the `frozen' flag on a socket. A frozen socket is one in
* which all READABLE notifications are ignored, so that data is
* not accepted from the peer until the socket is unfrozen. This
* exists for two purposes:
*
* - Port forwarding: when a local listening port receives a
* connection, we do not want to receive data from the new
* socket until we have somewhere to send it. Hence, we freeze
* the socket until its associated SSH channel is ready; then we
* unfreeze it and pending data is delivered.
*
* - Socket buffering: if an SSH channel (or the whole connection)
* backs up or presents a zero window, we must freeze the
* associated local socket in order to avoid unbounded buffer
* growth.
*/
#define sk_set_frozen(s, is_frozen) (((*s)->set_frozen) (s, is_frozen))
/*
* Call this after an operation that might have tried to send on a
* socket, to clean up any pending network errors.
*/
void net_pending_errors(void);
/*
* Simple wrapper on getservbyname(), needed by ssh.c. Returns the
* port number, in host byte order (suitable for printf and so on).
* Returns 0 on failure. Any platform not supporting getservbyname
* can just return 0 - this function is not required to handle
* numeric port specifications.
*/
int net_service_lookup(char *service);
/********** SSL stuff **********/
/*
* This section is subject to change, but you get the general idea
* of what it will eventually look like.
*/
typedef struct certificate *Certificate;
typedef struct our_certificate *Our_Certificate;
/* to be defined somewhere else, somehow */
typedef struct ssl_client_socket_function_table **SSL_Client_Socket;
typedef struct ssl_client_plug_function_table **SSL_Client_Plug;
struct ssl_client_socket_function_table {
struct socket_function_table base;
void (*renegotiate) (SSL_Client_Socket s);
/* renegotiate the cipher spec */
};
struct ssl_client_plug_function_table {
struct plug_function_table base;
int (*refuse_cert) (SSL_Client_Plug p, Certificate cert[]);
/* do we accept this certificate chain? If not, why not? */
/* cert[0] is the server's certificate, cert[] is NULL-terminated */
/* the last certificate may or may not be the root certificate */
Our_Certificate(*client_cert) (SSL_Client_Plug p);
/* the server wants us to identify ourselves */
/* may return NULL if we want anonymity */
};
SSL_Client_Socket sk_ssl_client_over(Socket s, /* pre-existing (tcp) connection */
SSL_Client_Plug p);
#define sk_renegotiate(s) (((*s)->renegotiate) (s))
#endif

71
sFTPlugins/psftp/PINGER.C Normal file
View File

@@ -0,0 +1,71 @@
/*
* pinger.c: centralised module that deals with sending TS_PING
* keepalives, to avoid replicating this code in multiple backends.
*/
#include "putty.h"
struct pinger_tag {
int interval;
int pending;
long next;
Backend *back;
void *backhandle;
};
static void pinger_schedule(Pinger pinger);
static void pinger_timer(void *ctx, long now)
{
Pinger pinger = (Pinger)ctx;
if (pinger->pending && now - pinger->next >= 0) {
pinger->back->special(pinger->backhandle, TS_PING);
pinger->pending = FALSE;
pinger_schedule(pinger);
}
}
static void pinger_schedule(Pinger pinger)
{
int next;
if (!pinger->interval) {
pinger->pending = FALSE; /* cancel any pending ping */
return;
}
next = schedule_timer(pinger->interval * TICKSPERSEC,
pinger_timer, pinger);
if (!pinger->pending || next < pinger->next) {
pinger->next = next;
pinger->pending = TRUE;
}
}
Pinger pinger_new(Config *cfg, Backend *back, void *backhandle)
{
Pinger pinger = snew(struct pinger_tag);
pinger->interval = cfg->ping_interval;
pinger->pending = FALSE;
pinger->back = back;
pinger->backhandle = backhandle;
pinger_schedule(pinger);
return pinger;
}
void pinger_reconfig(Pinger pinger, Config *oldcfg, Config *newcfg)
{
if (oldcfg->ping_interval != newcfg->ping_interval) {
pinger->interval = newcfg->ping_interval;
pinger_schedule(pinger);
}
}
void pinger_free(Pinger pinger)
{
expire_timer_context(pinger);
sfree(pinger);
}

555
sFTPlugins/psftp/PORTFWD.C Normal file
View File

@@ -0,0 +1,555 @@
/*
* SSH port forwarding.
*/
#include <stdio.h>
#include <stdlib.h>
#include "putty.h"
#include "ssh.h"
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
struct PFwdPrivate {
const struct plug_function_table *fn;
/* the above variable absolutely *must* be the first in this structure */
void *c; /* (channel) data used by ssh.c */
void *backhandle; /* instance of SSH backend itself */
/* Note that backhandle need not be filled in if c is non-NULL */
Socket s;
int throttled, throttle_override;
int ready;
/*
* `dynamic' does double duty. It's set to 0 for an ordinary
* forwarded port, and nonzero for SOCKS-style dynamic port
* forwarding; but it also represents the state of the SOCKS
* exchange.
*/
int dynamic;
/*
* `hostname' and `port' are the real hostname and port, once
* we know what we're connecting to; they're unused for this
* purpose while conducting a local SOCKS exchange, which means
* we can also use them as a buffer and pointer for reading
* data from the SOCKS client.
*/
char hostname[256+8];
int port;
/*
* When doing dynamic port forwarding, we can receive
* connection data before we are actually able to send it; so
* we may have to temporarily hold some in a dynamically
* allocated buffer here.
*/
void *buffer;
int buflen;
};
static void pfd_log(Plug plug, int type, SockAddr addr, int port,
const char *error_msg, int error_code)
{
/* we have to dump these since we have no interface to logging.c */
}
static int pfd_closing(Plug plug, const char *error_msg, int error_code,
int calling_back)
{
struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
/*
* We have no way to communicate down the forwarded connection,
* so if an error occurred on the socket, we just ignore it
* and treat it like a proper close.
*/
if (pr->c)
sshfwd_close(pr->c);
pfd_close(pr->s);
return 1;
}
static int pfd_receive(Plug plug, int urgent, char *data, int len)
{
struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
if (pr->dynamic) {
while (len--) {
/*
* Throughout SOCKS negotiation, "hostname" is re-used as a
* random protocol buffer with "port" storing the length.
*/
if (pr->port >= lenof(pr->hostname)) {
/* Request too long. */
if ((pr->dynamic >> 12) == 4) {
/* Send back a SOCKS 4 error before closing. */
char data[8];
memset(data, 0, sizeof(data));
data[1] = 91; /* generic `request rejected' */
sk_write(pr->s, data, 8);
}
pfd_close(pr->s);
return 1;
}
pr->hostname[pr->port++] = *data++;
/*
* Now check what's in the buffer to see if it's a
* valid and complete message in the SOCKS exchange.
*/
if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 4) &&
pr->hostname[0] == 4) {
/*
* SOCKS 4.
*/
if (pr->dynamic == 1)
pr->dynamic = 0x4000;
if (pr->port < 2) continue;/* don't have command code yet */
if (pr->hostname[1] != 1) {
/* Not CONNECT. */
/* Send back a SOCKS 4 error before closing. */
char data[8];
memset(data, 0, sizeof(data));
data[1] = 91; /* generic `request rejected' */
sk_write(pr->s, data, 8);
pfd_close(pr->s);
return 1;
}
if (pr->port <= 8) continue; /* haven't started user/hostname */
if (pr->hostname[pr->port-1] != 0)
continue; /* haven't _finished_ user/hostname */
/*
* Now we have a full SOCKS 4 request. Check it to
* see if it's a SOCKS 4A request.
*/
if (pr->hostname[4] == 0 && pr->hostname[5] == 0 &&
pr->hostname[6] == 0 && pr->hostname[7] != 0) {
/*
* It's SOCKS 4A. So if we haven't yet
* collected the host name, we should continue
* waiting for data in order to do so; if we
* have, we can go ahead.
*/
int len;
if (pr->dynamic == 0x4000) {
pr->dynamic = 0x4001;
pr->port = 8; /* reset buffer to overwrite name */
continue;
}
pr->hostname[0] = 0; /* reply version code */
pr->hostname[1] = 90; /* request granted */
sk_write(pr->s, pr->hostname, 8);
len= pr->port - 8;
pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
memmove(pr->hostname, pr->hostname + 8, len);
goto connect;
} else {
/*
* It's SOCKS 4, which means we should format
* the IP address into the hostname string and
* then just go.
*/
pr->hostname[0] = 0; /* reply version code */
pr->hostname[1] = 90; /* request granted */
sk_write(pr->s, pr->hostname, 8);
pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
sprintf(pr->hostname, "%d.%d.%d.%d",
(unsigned char)pr->hostname[4],
(unsigned char)pr->hostname[5],
(unsigned char)pr->hostname[6],
(unsigned char)pr->hostname[7]);
goto connect;
}
}
if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 5) &&
pr->hostname[0] == 5) {
/*
* SOCKS 5.
*/
if (pr->dynamic == 1)
pr->dynamic = 0x5000;
if (pr->dynamic == 0x5000) {
int i, method;
char data[2];
/*
* We're receiving a set of method identifiers.
*/
if (pr->port < 2) continue;/* no method count yet */
if (pr->port < 2 + (unsigned char)pr->hostname[1])
continue; /* no methods yet */
method = 0xFF; /* invalid */
for (i = 0; i < (unsigned char)pr->hostname[1]; i++)
if (pr->hostname[2+i] == 0) {
method = 0;/* no auth */
break;
}
data[0] = 5;
data[1] = method;
sk_write(pr->s, data, 2);
pr->dynamic = 0x5001;
pr->port = 0; /* re-empty the buffer */
continue;
}
if (pr->dynamic == 0x5001) {
/*
* We're receiving a SOCKS request.
*/
unsigned char reply[10]; /* SOCKS5 atyp=1 reply */
int atype, alen = 0;
/*
* Pre-fill reply packet.
* In all cases, we set BND.{HOST,ADDR} to 0.0.0.0:0
* (atyp=1) in the reply; if we succeed, we don't know
* the right answers, and if we fail, they should be
* ignored.
*/
memset(reply, 0, lenof(reply));
reply[0] = 5; /* VER */
reply[3] = 1; /* ATYP = 1 (IPv4, 0.0.0.0:0) */
if (pr->port < 6) continue;
atype = (unsigned char)pr->hostname[3];
if (atype == 1) /* IPv4 address */
alen = 4;
if (atype == 4) /* IPv6 address */
alen = 16;
if (atype == 3) /* domain name has leading length */
alen = 1 + (unsigned char)pr->hostname[4];
if (pr->port < 6 + alen) continue;
if (pr->hostname[1] != 1 || pr->hostname[2] != 0) {
/* Not CONNECT or reserved field nonzero - error */
reply[1] = 1; /* generic failure */
sk_write(pr->s, (char *) reply, lenof(reply));
pfd_close(pr->s);
return 1;
}
/*
* Now we have a viable connect request. Switch
* on atype.
*/
pr->port = GET_16BIT_MSB_FIRST(pr->hostname+4+alen);
if (atype == 1) {
/* REP=0 (success) already */
sk_write(pr->s, (char *) reply, lenof(reply));
sprintf(pr->hostname, "%d.%d.%d.%d",
(unsigned char)pr->hostname[4],
(unsigned char)pr->hostname[5],
(unsigned char)pr->hostname[6],
(unsigned char)pr->hostname[7]);
goto connect;
} else if (atype == 3) {
/* REP=0 (success) already */
sk_write(pr->s, (char *) reply, lenof(reply));
memmove(pr->hostname, pr->hostname + 5, alen-1);
pr->hostname[alen-1] = '\0';
goto connect;
} else {
/*
* Unknown address type. (FIXME: support IPv6!)
*/
reply[1] = 8; /* atype not supported */
sk_write(pr->s, (char *) reply, lenof(reply));
pfd_close(pr->s);
return 1;
}
}
}
/*
* If we get here without either having done `continue'
* or `goto connect', it must be because there is no
* sensible interpretation of what's in our buffer. So
* close the connection rudely.
*/
pfd_close(pr->s);
return 1;
}
return 1;
/*
* We come here when we're ready to make an actual
* connection.
*/
connect:
pr->c = new_sock_channel(pr->backhandle, pr->s);
if (pr->c == NULL) {
pfd_close(pr->s);
return 1;
} else {
/* asks to forward to the specified host/port for this */
ssh_send_port_open(pr->c, pr->hostname, pr->port, "forwarding");
}
pr->dynamic = 0;
/*
* Now freeze the socket until the SSH server confirms the
* connection.
*/
sk_set_frozen(pr->s, 1);
/*
* If there's any data remaining in our current buffer,
* save it to be sent on pfd_confirm().
*/
if (len > 0) {
pr->buffer = snewn(len, char);
memcpy(pr->buffer, data, len);
pr->buflen = len;
}
}
if (pr->ready) {
if (sshfwd_write(pr->c, data, len) > 0) {
pr->throttled = 1;
sk_set_frozen(pr->s, 1);
}
}
return 1;
}
static void pfd_sent(Plug plug, int bufsize)
{
struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
if (pr->c)
sshfwd_unthrottle(pr->c, bufsize);
}
/*
* Called when receiving a PORT OPEN from the server
*/
const char *pfd_newconnect(Socket *s, char *hostname, int port,
void *c, const Config *cfg, int addressfamily)
{
static const struct plug_function_table fn_table = {
pfd_log,
pfd_closing,
pfd_receive,
pfd_sent,
NULL
};
SockAddr addr;
const char *err;
char *dummy_realhost;
struct PFwdPrivate *pr;
/*
* Try to find host.
*/
addr = name_lookup(hostname, port, &dummy_realhost, cfg, addressfamily);
if ((err = sk_addr_error(addr)) != NULL) {
sk_addr_free(addr);
return err;
}
/*
* Open socket.
*/
pr = snew(struct PFwdPrivate);
pr->buffer = NULL;
pr->fn = &fn_table;
pr->throttled = pr->throttle_override = 0;
pr->ready = 1;
pr->c = c;
pr->backhandle = NULL; /* we shouldn't need this */
pr->dynamic = 0;
pr->s = *s = new_connection(addr, dummy_realhost, port,
0, 1, 0, 0, (Plug) pr, cfg);
if ((err = sk_socket_error(*s)) != NULL) {
sfree(pr);
return err;
}
sk_set_private_ptr(*s, pr);
return NULL;
}
/*
called when someone connects to the local port
*/
static int pfd_accepting(Plug p, OSSocket sock)
{
static const struct plug_function_table fn_table = {
pfd_log,
pfd_closing,
pfd_receive,
pfd_sent,
NULL
};
struct PFwdPrivate *pr, *org;
Socket s;
const char *err;
org = (struct PFwdPrivate *)p;
pr = snew(struct PFwdPrivate);
pr->buffer = NULL;
pr->fn = &fn_table;
pr->c = NULL;
pr->backhandle = org->backhandle;
pr->s = s = sk_register(sock, (Plug) pr);
if ((err = sk_socket_error(s)) != NULL) {
sfree(pr);
return err != NULL;
}
sk_set_private_ptr(s, pr);
pr->throttled = pr->throttle_override = 0;
pr->ready = 0;
if (org->dynamic) {
pr->dynamic = 1;
pr->port = 0; /* "hostname" buffer is so far empty */
sk_set_frozen(s, 0); /* we want to receive SOCKS _now_! */
} else {
pr->dynamic = 0;
strcpy(pr->hostname, org->hostname);
pr->port = org->port;
pr->c = new_sock_channel(org->backhandle, s);
if (pr->c == NULL) {
sfree(pr);
return 1;
} else {
/* asks to forward to the specified host/port for this */
ssh_send_port_open(pr->c, pr->hostname, pr->port, "forwarding");
}
}
return 0;
}
/* Add a new forwarding from port -> desthost:destport
sets up a listener on the local machine on (srcaddr:)port
*/
const char *pfd_addforward(char *desthost, int destport, char *srcaddr,
int port, void *backhandle, const Config *cfg,
void **sockdata, int address_family)
{
static const struct plug_function_table fn_table = {
pfd_log,
pfd_closing,
pfd_receive, /* should not happen... */
pfd_sent, /* also should not happen */
pfd_accepting
};
const char *err;
struct PFwdPrivate *pr;
Socket s;
/*
* Open socket.
*/
pr = snew(struct PFwdPrivate);
pr->buffer = NULL;
pr->fn = &fn_table;
pr->c = NULL;
if (desthost) {
strcpy(pr->hostname, desthost);
pr->port = destport;
pr->dynamic = 0;
} else
pr->dynamic = 1;
pr->throttled = pr->throttle_override = 0;
pr->ready = 0;
pr->backhandle = backhandle;
pr->s = s = new_listener(srcaddr, port, (Plug) pr,
!cfg->lport_acceptall, cfg, address_family);
if ((err = sk_socket_error(s)) != NULL) {
sfree(pr);
return err;
}
sk_set_private_ptr(s, pr);
*sockdata = (void *)s;
return NULL;
}
void pfd_close(Socket s)
{
struct PFwdPrivate *pr;
if (!s)
return;
pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
sfree(pr->buffer);
sfree(pr);
sk_close(s);
}
/*
* Terminate a listener.
*/
void pfd_terminate(void *sv)
{
pfd_close((Socket)sv);
}
void pfd_unthrottle(Socket s)
{
struct PFwdPrivate *pr;
if (!s)
return;
pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
pr->throttled = 0;
sk_set_frozen(s, pr->throttled || pr->throttle_override);
}
void pfd_override_throttle(Socket s, int enable)
{
struct PFwdPrivate *pr;
if (!s)
return;
pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
pr->throttle_override = enable;
sk_set_frozen(s, pr->throttled || pr->throttle_override);
}
/*
* Called to send data down the raw connection.
*/
int pfd_send(Socket s, char *data, int len)
{
if (s == NULL)
return 0;
return sk_write(s, data, len);
}
void pfd_confirm(Socket s)
{
struct PFwdPrivate *pr;
if (s == NULL)
return;
pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
pr->ready = 1;
sk_set_frozen(s, 0);
sk_write(s, NULL, 0);
if (pr->buffer) {
sshfwd_write(pr->c, pr->buffer, pr->buflen);
sfree(pr->buffer);
pr->buffer = NULL;
}
}

1478
sFTPlugins/psftp/PROXY.C Normal file

File diff suppressed because it is too large Load Diff

123
sFTPlugins/psftp/PROXY.H Normal file
View File

@@ -0,0 +1,123 @@
/*
* Network proxy abstraction in PuTTY
*
* A proxy layer, if necessary, wedges itself between the
* network code and the higher level backend.
*
* Supported proxies: HTTP CONNECT, generic telnet, SOCKS 4 & 5
*/
#ifndef PUTTY_PROXY_H
#define PUTTY_PROXY_H
#define PROXY_ERROR_GENERAL 8000
#define PROXY_ERROR_UNEXPECTED 8001
typedef struct Socket_proxy_tag * Proxy_Socket;
struct Socket_proxy_tag {
const struct socket_function_table *fn;
/* the above variable absolutely *must* be the first in this structure */
char * error;
Socket sub_socket;
Plug plug;
SockAddr remote_addr;
int remote_port;
bufchain pending_output_data;
bufchain pending_oob_output_data;
int pending_flush;
bufchain pending_input_data;
#define PROXY_STATE_NEW -1
#define PROXY_STATE_ACTIVE 0
int state; /* proxy states greater than 0 are implementation
* dependent, but represent various stages/states
* of the initialization/setup/negotiation with the
* proxy server.
*/
int freeze; /* should we freeze the underlying socket when
* we are done with the proxy negotiation? this
* simply caches the value of sk_set_frozen calls.
*/
#define PROXY_CHANGE_NEW -1
#define PROXY_CHANGE_CLOSING 0
#define PROXY_CHANGE_SENT 1
#define PROXY_CHANGE_RECEIVE 2
#define PROXY_CHANGE_ACCEPTING 3
/* something has changed (a call from the sub socket
* layer into our Proxy Plug layer, or we were just
* created, etc), so the proxy layer needs to handle
* this change (the type of which is the second argument)
* and further the proxy negotiation process.
*/
int (*negotiate) (Proxy_Socket /* this */, int /* change type */);
/* current arguments of plug handlers
* (for use by proxy's negotiate function)
*/
/* closing */
const char *closing_error_msg;
int closing_error_code;
int closing_calling_back;
/* receive */
int receive_urgent;
char *receive_data;
int receive_len;
/* sent */
int sent_bufsize;
/* accepting */
OSSocket accepting_sock;
/* configuration, used to look up proxy settings */
Config cfg;
/* CHAP transient data */
int chap_num_attributes;
int chap_num_attributes_processed;
int chap_current_attribute;
int chap_current_datalen;
};
typedef struct Plug_proxy_tag * Proxy_Plug;
struct Plug_proxy_tag {
const struct plug_function_table *fn;
/* the above variable absolutely *must* be the first in this structure */
Proxy_Socket proxy_socket;
};
extern void proxy_activate (Proxy_Socket);
extern int proxy_http_negotiate (Proxy_Socket, int);
extern int proxy_telnet_negotiate (Proxy_Socket, int);
extern int proxy_socks4_negotiate (Proxy_Socket, int);
extern int proxy_socks5_negotiate (Proxy_Socket, int);
/*
* This may be reused by local-command proxies on individual
* platforms.
*/
char *format_telnet_command(SockAddr addr, int port, const Config *cfg);
/*
* These are implemented in cproxy.c or nocproxy.c, depending on
* whether encrypted proxy authentication is available.
*/
extern void proxy_socks5_offerencryptedauth(char *command, int *len);
extern int proxy_socks5_handlechap (Proxy_Socket p);
extern int proxy_socks5_selectchap(Proxy_Socket p);
#endif

3002
sFTPlugins/psftp/PSFTP.C Normal file

File diff suppressed because it is too large Load Diff

178
sFTPlugins/psftp/PSFTP.H Normal file
View File

@@ -0,0 +1,178 @@
/*
* psftp.h: interface between psftp.c / scp.c and each
* platform-specific SFTP module.
*/
#include "int64.h"
#ifndef PUTTY_PSFTP_H
#define PUTTY_PSFTP_H
/*
* psftp_getcwd returns the local current directory. The returned
* string must be freed by the caller.
*/
char *psftp_getcwd(void);
/*
* psftp_lcd changes the local current directory. The return value
* is NULL on success, or else an error message which must be freed
* by the caller.
*/
char *psftp_lcd(char *newdir);
/*
* Retrieve file times on a local file. Must return two unsigned
* longs in POSIX time_t format.
*/
void get_file_times(char *filename, unsigned long *mtime,
unsigned long *atime);
/*
* One iteration of the PSFTP event loop: wait for network data and
* process it, once.
*/
int ssh_sftp_loop_iteration(void);
/*
* Read a command line for PSFTP from standard input. Caller must
* free.
*
* If `backend_required' is TRUE, should also listen for activity
* at the backend (rekeys, clientalives, unexpected closures etc)
* and respond as necessary, and if the backend closes it should
* treat this as a failure condition. If `backend_required' is
* FALSE, a back end is not (intentionally) active at all (e.g.
* psftp before an `open' command).
*/
char *ssh_sftp_get_cmdline(char *prompt, int backend_required);
/*
* The main program in psftp.c. Called from main() in the platform-
* specific code, after doing any platform-specific initialisation.
*/
int psftp_main(int argc, char *argv[]);
/*
* These functions are used by PSCP to transmit progress updates
* and error information to a GUI window managing it. This will
* probably only ever be supported on Windows, so these functions
* can safely be stubs on all other platforms.
*/
void gui_update_stats(char *name, unsigned long size,
int percentage, unsigned long elapsed,
unsigned long done, unsigned long eta,
unsigned long ratebs);
void gui_send_errcount(int list, int errs);
void gui_send_char(int is_stderr, int c);
void gui_enable(char *arg);
/*
* It's likely that a given platform's implementation of file
* transfer utilities is going to want to do things with them that
* aren't present in stdio. Hence we supply an alternative
* abstraction for file access functions.
*
* This abstraction tells you the size and access times when you
* open an existing file (platforms may choose the meaning of the
* file times if it's not clear; whatever they choose will be what
* PSCP sends to the server as mtime and atime), and lets you set
* the times when saving a new file.
*
* On the other hand, the abstraction is pretty simple: it supports
* only opening a file and reading it, or creating a file and writing
* it. None of this read-and-write, seeking-back-and-forth stuff.
*/
typedef struct RFile RFile;
typedef struct WFile WFile;
/* Output params size, mtime and atime can all be NULL if desired */
RFile *open_existing_file(char *name, uint64 *size,
unsigned long *mtime, unsigned long *atime);
WFile *open_existing_wfile(char *name, uint64 *size);
/* Returns <0 on error, 0 on eof, or number of bytes read, as usual */
int read_from_file(RFile *f, void *buffer, int length);
/* Closes and frees the RFile */
void close_rfile(RFile *f);
WFile *open_new_file(char *name);
/* Returns <0 on error, 0 on eof, or number of bytes written, as usual */
int write_to_file(WFile *f, void *buffer, int length);
void set_file_times(WFile *f, unsigned long mtime, unsigned long atime);
/* Closes and frees the WFile */
void close_wfile(WFile *f);
/* Seek offset bytes through file */
enum { FROM_START, FROM_CURRENT, FROM_END };
int seek_file(WFile *f, uint64 offset, int whence);
/* Get file position */
uint64 get_file_posn(WFile *f);
/*
* Determine the type of a file: nonexistent, file, directory or
* weird. `weird' covers anything else - named pipes, Unix sockets,
* device files, fish, badgers, you name it. Things marked `weird'
* will be skipped over in recursive file transfers, so the only
* real reason for not lumping them in with `nonexistent' is that
* it allows a slightly more sane error message.
*/
enum {
FILE_TYPE_NONEXISTENT, FILE_TYPE_FILE, FILE_TYPE_DIRECTORY, FILE_TYPE_WEIRD
};
int file_type(char *name);
/*
* Read all the file names out of a directory.
*/
typedef struct DirHandle DirHandle;
DirHandle *open_directory(char *name);
/* The string returned from this will need freeing if not NULL */
char *read_filename(DirHandle *dir);
void close_directory(DirHandle *dir);
/*
* Test a filespec to see whether it's a local wildcard or not.
* Return values:
*
* - WCTYPE_WILDCARD (this is a wildcard).
* - WCTYPE_FILENAME (this is a single file name).
* - WCTYPE_NONEXISTENT (whichever it was, nothing of that name exists).
*
* Some platforms may choose not to support local wildcards when
* they come from the command line; in this case they simply never
* return WCTYPE_WILDCARD, but still test the file's existence.
* (However, all platforms will probably want to support wildcards
* inside the PSFTP CLI.)
*/
enum {
WCTYPE_NONEXISTENT, WCTYPE_FILENAME, WCTYPE_WILDCARD
};
int test_wildcard(char *name, int cmdline);
/*
* Actually return matching file names for a local wildcard.
*/
typedef struct WildcardMatcher WildcardMatcher;
WildcardMatcher *begin_wildcard_matching(char *name);
/* The string returned from this will need freeing if not NULL */
char *wildcard_get_filename(WildcardMatcher *dir);
void finish_wildcard_matching(WildcardMatcher *dir);
/*
* Vet a filename returned from the remote host, to ensure it isn't
* in some way malicious. The idea is that this function is applied
* to filenames returned from FXP_READDIR, which means we can panic
* if we see _anything_ resembling a directory separator.
*
* Returns TRUE if the filename is kosher, FALSE if dangerous.
*/
int vet_filename(char *name);
/*
* Create a directory. Returns 0 on error, !=0 on success.
*/
int create_directory(char *name);
/*
* Concatenate a directory name and a file name. The way this is
* done will depend on the OS.
*/
char *dir_file_cat(char *dir, char *file);
#endif /* PUTTY_PSFTP_H */

1214
sFTPlugins/psftp/PUTTY.H Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,42 @@
/*
* PuTTY memory-handling header.
*/
#ifndef PUTTY_PUTTYMEM_H
#define PUTTY_PUTTYMEM_H
#include <stddef.h> /* for size_t */
#include <string.h> /* for memcpy() */
/* #define MALLOC_LOG do this if you suspect putty of leaking memory */
#ifdef MALLOC_LOG
#define smalloc(z) (mlog(__FILE__,__LINE__), safemalloc(z,1))
#define snmalloc(z,s) (mlog(__FILE__,__LINE__), safemalloc(z,s))
#define srealloc(y,z) (mlog(__FILE__,__LINE__), saferealloc(y,z,1))
#define snrealloc(y,z,s) (mlog(__FILE__,__LINE__), saferealloc(y,z,s))
#define sfree(z) (mlog(__FILE__,__LINE__), safefree(z))
void mlog(char *, int);
#else
#define smalloc(z) safemalloc(z,1)
#define snmalloc safemalloc
#define srealloc(y,z) saferealloc(y,z,1)
#define snrealloc saferealloc
#define sfree safefree
#endif
void *safemalloc(size_t, size_t);
void *saferealloc(void *, size_t, size_t);
void safefree(void *);
/*
* Direct use of smalloc within the code should be avoided where
* possible, in favour of these type-casting macros which ensure
* you don't mistakenly allocate enough space for one sort of
* structure and assign it to a different sort of pointer.
*/
#define snew(type) ((type *)snmalloc(1, sizeof(type)))
#define snewn(n, type) ((type *)snmalloc((n), sizeof(type)))
#define sresize(ptr, n, type) ((type *)snrealloc((ptr), (n), sizeof(type)))
#endif

View File

@@ -0,0 +1,26 @@
/*
* Find the platform-specific header for this platform.
*/
#ifndef PUTTY_PUTTYPS_H
#define PUTTY_PUTTYPS_H
#ifdef _WINDOWS
#include "winstuff.h"
#elif defined(macintosh)
#include "macstuff.h"
#elif defined(MACOSX)
#include "osx.h"
#else
#include "unix.h"
#endif
#endif

869
sFTPlugins/psftp/SETTINGS.C Normal file
View File

@@ -0,0 +1,869 @@
/*
* settings.c: read and write saved sessions. (platform-independent)
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "putty.h"
#include "storage.h"
/*
* Tables of string <-> enum value mappings
*/
struct keyval { char *s; int v; };
/* The cipher order given here is the default order. */
static const struct keyval ciphernames[] = {
{ "aes", CIPHER_AES },
{ "blowfish", CIPHER_BLOWFISH },
{ "3des", CIPHER_3DES },
{ "WARN", CIPHER_WARN },
{ "arcfour", CIPHER_ARCFOUR },
{ "des", CIPHER_DES }
};
static const struct keyval kexnames[] = {
{ "dh-gex-sha1", KEX_DHGEX },
{ "dh-group14-sha1", KEX_DHGROUP14 },
{ "dh-group1-sha1", KEX_DHGROUP1 },
{ "WARN", KEX_WARN }
};
/*
* All the terminal modes that we know about for the "TerminalModes"
* setting. (Also used by config.c for the drop-down list.)
* This is currently precisely the same as the set in ssh.c, but could
* in principle differ if other backends started to support tty modes
* (e.g., the pty backend).
*/
const char *const ttymodes[] = {
"INTR", "QUIT", "ERASE", "KILL", "EOF",
"EOL", "EOL2", "START", "STOP", "SUSP",
"DSUSP", "REPRINT", "WERASE", "LNEXT", "FLUSH",
"SWTCH", "STATUS", "DISCARD", "IGNPAR", "PARMRK",
"INPCK", "ISTRIP", "INLCR", "IGNCR", "ICRNL",
"IUCLC", "IXON", "IXANY", "IXOFF", "IMAXBEL",
"ISIG", "ICANON", "XCASE", "ECHO", "ECHOE",
"ECHOK", "ECHONL", "NOFLSH", "TOSTOP", "IEXTEN",
"ECHOCTL", "ECHOKE", "PENDIN", "OPOST", "OLCUC",
"ONLCR", "OCRNL", "ONOCR", "ONLRET", "CS7",
"CS8", "PARENB", "PARODD", NULL
};
static void gpps(void *handle, const char *name, const char *def,
char *val, int len)
{
if (!read_setting_s(handle, name, val, len)) {
char *pdef;
pdef = platform_default_s(name);
if (pdef) {
strncpy(val, pdef, len);
sfree(pdef);
} else {
strncpy(val, def, len);
}
val[len - 1] = '\0';
}
}
/*
* gppfont and gppfile cannot have local defaults, since the very
* format of a Filename or Font is platform-dependent. So the
* platform-dependent functions MUST return some sort of value.
*/
static void gppfont(void *handle, const char *name, FontSpec *result)
{
if (!read_setting_fontspec(handle, name, result))
*result = platform_default_fontspec(name);
}
static void gppfile(void *handle, const char *name, Filename *result)
{
if (!read_setting_filename(handle, name, result))
*result = platform_default_filename(name);
}
static void gppi(void *handle, char *name, int def, int *i)
{
def = platform_default_i(name, def);
*i = read_setting_i(handle, name, def);
}
/*
* Read a set of name-value pairs in the format we occasionally use:
* NAME\tVALUE\0NAME\tVALUE\0\0 in memory
* NAME=VALUE,NAME=VALUE, in storage
* `def' is in the storage format.
*/
static void gppmap(void *handle, char *name, char *def, char *val, int len)
{
char *buf = snewn(2*len, char), *p, *q;
gpps(handle, name, def, buf, 2*len);
p = buf;
q = val;
while (*p) {
while (*p && *p != ',') {
int c = *p++;
if (c == '=')
c = '\t';
if (c == '\\')
c = *p++;
*q++ = c;
}
if (*p == ',')
p++;
*q++ = '\0';
}
*q = '\0';
sfree(buf);
}
/*
* Write a set of name/value pairs in the above format.
*/
static void wmap(void *handle, char const *key, char const *value, int len)
{
char *buf = snewn(2*len, char), *p;
const char *q;
p = buf;
q = value;
while (*q) {
while (*q) {
int c = *q++;
if (c == '=' || c == ',' || c == '\\')
*p++ = '\\';
if (c == '\t')
c = '=';
*p++ = c;
}
*p++ = ',';
q++;
}
*p = '\0';
write_setting_s(handle, key, buf);
sfree(buf);
}
static int key2val(const struct keyval *mapping, int nmaps, char *key)
{
int i;
for (i = 0; i < nmaps; i++)
if (!strcmp(mapping[i].s, key)) return mapping[i].v;
return -1;
}
static const char *val2key(const struct keyval *mapping, int nmaps, int val)
{
int i;
for (i = 0; i < nmaps; i++)
if (mapping[i].v == val) return mapping[i].s;
return NULL;
}
/*
* Helper function to parse a comma-separated list of strings into
* a preference list array of values. Any missing values are added
* to the end and duplicates are weeded.
* XXX: assumes vals in 'mapping' are small +ve integers
*/
static void gprefs(void *sesskey, char *name, char *def,
const struct keyval *mapping, int nvals,
int *array)
{
char commalist[80];
char *tokarg = commalist;
int n;
unsigned long seen = 0; /* bitmap for weeding dups etc */
gpps(sesskey, name, def, commalist, sizeof(commalist));
/* Grotty parsing of commalist. */
n = 0;
do {
int v;
char *key;
key = strtok(tokarg, ","); /* sorry */
tokarg = NULL;
if (!key) break;
if (((v = key2val(mapping, nvals, key)) != -1) &&
!(seen & 1<<v)) {
array[n] = v;
n++;
seen |= 1<<v;
}
} while (n < nvals);
/* Add any missing values (backward compatibility ect). */
{
int i;
for (i = 0; i < nvals; i++) {
assert(mapping[i].v < 32);
if (!(seen & 1<<mapping[i].v)) {
array[n] = mapping[i].v;
n++;
}
}
}
}
/*
* Write out a preference list.
*/
static void wprefs(void *sesskey, char *name,
const struct keyval *mapping, int nvals,
int *array)
{
char buf[80] = ""; /* XXX assumed big enough */
int l = sizeof(buf)-1, i;
buf[l] = '\0';
for (i = 0; l > 0 && i < nvals; i++) {
const char *s = val2key(mapping, nvals, array[i]);
if (s) {
int sl = strlen(s);
if (i > 0) {
strncat(buf, ",", l);
l--;
}
strncat(buf, s, l);
l -= sl;
}
}
write_setting_s(sesskey, name, buf);
}
char *save_settings(char *section, Config * cfg)
{
void *sesskey;
char *errmsg;
sesskey = open_settings_w(section, &errmsg);
if (!sesskey)
return errmsg;
save_open_settings(sesskey, cfg);
close_settings_w(sesskey);
return NULL;
}
void save_open_settings(void *sesskey, Config *cfg)
{
int i;
char *p;
write_setting_i(sesskey, "Present", 1);
write_setting_s(sesskey, "HostName", cfg->host);
write_setting_filename(sesskey, "LogFileName", cfg->logfilename);
write_setting_i(sesskey, "LogType", cfg->logtype);
write_setting_i(sesskey, "LogFileClash", cfg->logxfovr);
write_setting_i(sesskey, "LogFlush", cfg->logflush);
write_setting_i(sesskey, "SSHLogOmitPasswords", cfg->logomitpass);
write_setting_i(sesskey, "SSHLogOmitData", cfg->logomitdata);
p = "raw";
for (i = 0; backends[i].name != NULL; i++)
if (backends[i].protocol == cfg->protocol) {
p = backends[i].name;
break;
}
write_setting_s(sesskey, "Protocol", p);
write_setting_i(sesskey, "PortNumber", cfg->port);
/* The CloseOnExit numbers are arranged in a different order from
* the standard FORCE_ON / FORCE_OFF / AUTO. */
write_setting_i(sesskey, "CloseOnExit", (cfg->close_on_exit+2)%3);
write_setting_i(sesskey, "WarnOnClose", !!cfg->warn_on_close);
write_setting_i(sesskey, "PingInterval", cfg->ping_interval / 60); /* minutes */
write_setting_i(sesskey, "PingIntervalSecs", cfg->ping_interval % 60); /* seconds */
write_setting_i(sesskey, "TCPNoDelay", cfg->tcp_nodelay);
write_setting_i(sesskey, "TCPKeepalives", cfg->tcp_keepalives);
write_setting_s(sesskey, "TerminalType", cfg->termtype);
write_setting_s(sesskey, "TerminalSpeed", cfg->termspeed);
wmap(sesskey, "TerminalModes", cfg->ttymodes, lenof(cfg->ttymodes));
/* Address family selection */
write_setting_i(sesskey, "AddressFamily", cfg->addressfamily);
/* proxy settings */
write_setting_s(sesskey, "ProxyExcludeList", cfg->proxy_exclude_list);
write_setting_i(sesskey, "ProxyDNS", (cfg->proxy_dns+2)%3);
write_setting_i(sesskey, "ProxyLocalhost", cfg->even_proxy_localhost);
write_setting_i(sesskey, "ProxyMethod", cfg->proxy_type);
write_setting_s(sesskey, "ProxyHost", cfg->proxy_host);
write_setting_i(sesskey, "ProxyPort", cfg->proxy_port);
write_setting_s(sesskey, "ProxyUsername", cfg->proxy_username);
write_setting_s(sesskey, "ProxyPassword", cfg->proxy_password);
write_setting_s(sesskey, "ProxyTelnetCommand", cfg->proxy_telnet_command);
wmap(sesskey, "Environment", cfg->environmt, lenof(cfg->environmt));
write_setting_s(sesskey, "UserName", cfg->username);
write_setting_s(sesskey, "LocalUserName", cfg->localusername);
write_setting_i(sesskey, "NoPTY", cfg->nopty);
write_setting_i(sesskey, "Compression", cfg->compression);
write_setting_i(sesskey, "TryAgent", cfg->tryagent);
write_setting_i(sesskey, "AgentFwd", cfg->agentfwd);
write_setting_i(sesskey, "ChangeUsername", cfg->change_username);
wprefs(sesskey, "Cipher", ciphernames, CIPHER_MAX,
cfg->ssh_cipherlist);
wprefs(sesskey, "KEX", kexnames, KEX_MAX, cfg->ssh_kexlist);
write_setting_i(sesskey, "RekeyTime", cfg->ssh_rekey_time);
write_setting_s(sesskey, "RekeyBytes", cfg->ssh_rekey_data);
write_setting_i(sesskey, "SshNoAuth", cfg->ssh_no_userauth);
write_setting_i(sesskey, "AuthTIS", cfg->try_tis_auth);
write_setting_i(sesskey, "AuthKI", cfg->try_ki_auth);
write_setting_i(sesskey, "SshNoShell", cfg->ssh_no_shell);
write_setting_i(sesskey, "SshProt", cfg->sshprot);
write_setting_i(sesskey, "SSH2DES", cfg->ssh2_des_cbc);
write_setting_filename(sesskey, "PublicKeyFile", cfg->keyfile);
write_setting_s(sesskey, "RemoteCommand", cfg->remote_cmd);
write_setting_i(sesskey, "RFCEnviron", cfg->rfc_environ);
write_setting_i(sesskey, "PassiveTelnet", cfg->passive_telnet);
write_setting_i(sesskey, "BackspaceIsDelete", cfg->bksp_is_delete);
write_setting_i(sesskey, "RXVTHomeEnd", cfg->rxvt_homeend);
write_setting_i(sesskey, "LinuxFunctionKeys", cfg->funky_type);
write_setting_i(sesskey, "NoApplicationKeys", cfg->no_applic_k);
write_setting_i(sesskey, "NoApplicationCursors", cfg->no_applic_c);
write_setting_i(sesskey, "NoMouseReporting", cfg->no_mouse_rep);
write_setting_i(sesskey, "NoRemoteResize", cfg->no_remote_resize);
write_setting_i(sesskey, "NoAltScreen", cfg->no_alt_screen);
write_setting_i(sesskey, "NoRemoteWinTitle", cfg->no_remote_wintitle);
write_setting_i(sesskey, "RemoteQTitleAction", cfg->remote_qtitle_action);
write_setting_i(sesskey, "NoDBackspace", cfg->no_dbackspace);
write_setting_i(sesskey, "NoRemoteCharset", cfg->no_remote_charset);
write_setting_i(sesskey, "ApplicationCursorKeys", cfg->app_cursor);
write_setting_i(sesskey, "ApplicationKeypad", cfg->app_keypad);
write_setting_i(sesskey, "NetHackKeypad", cfg->nethack_keypad);
write_setting_i(sesskey, "AltF4", cfg->alt_f4);
write_setting_i(sesskey, "AltSpace", cfg->alt_space);
write_setting_i(sesskey, "AltOnly", cfg->alt_only);
write_setting_i(sesskey, "ComposeKey", cfg->compose_key);
write_setting_i(sesskey, "CtrlAltKeys", cfg->ctrlaltkeys);
write_setting_i(sesskey, "TelnetKey", cfg->telnet_keyboard);
write_setting_i(sesskey, "TelnetRet", cfg->telnet_newline);
write_setting_i(sesskey, "LocalEcho", cfg->localecho);
write_setting_i(sesskey, "LocalEdit", cfg->localedit);
write_setting_s(sesskey, "Answerback", cfg->answerback);
write_setting_i(sesskey, "AlwaysOnTop", cfg->alwaysontop);
write_setting_i(sesskey, "FullScreenOnAltEnter", cfg->fullscreenonaltenter);
write_setting_i(sesskey, "HideMousePtr", cfg->hide_mouseptr);
write_setting_i(sesskey, "SunkenEdge", cfg->sunken_edge);
write_setting_i(sesskey, "WindowBorder", cfg->window_border);
write_setting_i(sesskey, "CurType", cfg->cursor_type);
write_setting_i(sesskey, "BlinkCur", cfg->blink_cur);
write_setting_i(sesskey, "Beep", cfg->beep);
write_setting_i(sesskey, "BeepInd", cfg->beep_ind);
write_setting_filename(sesskey, "BellWaveFile", cfg->bell_wavefile);
write_setting_i(sesskey, "BellOverload", cfg->bellovl);
write_setting_i(sesskey, "BellOverloadN", cfg->bellovl_n);
write_setting_i(sesskey, "BellOverloadT", cfg->bellovl_t
#ifdef PUTTY_UNIX_H
* 1000
#endif
);
write_setting_i(sesskey, "BellOverloadS", cfg->bellovl_s
#ifdef PUTTY_UNIX_H
* 1000
#endif
);
write_setting_i(sesskey, "ScrollbackLines", cfg->savelines);
write_setting_i(sesskey, "DECOriginMode", cfg->dec_om);
write_setting_i(sesskey, "AutoWrapMode", cfg->wrap_mode);
write_setting_i(sesskey, "LFImpliesCR", cfg->lfhascr);
write_setting_i(sesskey, "DisableArabicShaping", cfg->arabicshaping);
write_setting_i(sesskey, "DisableBidi", cfg->bidi);
write_setting_i(sesskey, "WinNameAlways", cfg->win_name_always);
write_setting_s(sesskey, "WinTitle", cfg->wintitle);
write_setting_i(sesskey, "TermWidth", cfg->width);
write_setting_i(sesskey, "TermHeight", cfg->height);
write_setting_fontspec(sesskey, "Font", cfg->font);
write_setting_i(sesskey, "FontQuality", cfg->font_quality);
write_setting_i(sesskey, "FontVTMode", cfg->vtmode);
write_setting_i(sesskey, "UseSystemColours", cfg->system_colour);
write_setting_i(sesskey, "TryPalette", cfg->try_palette);
write_setting_i(sesskey, "ANSIColour", cfg->ansi_colour);
write_setting_i(sesskey, "Xterm256Colour", cfg->xterm_256_colour);
write_setting_i(sesskey, "BoldAsColour", cfg->bold_colour);
for (i = 0; i < 22; i++) {
char buf[20], buf2[30];
sprintf(buf, "Colour%d", i);
sprintf(buf2, "%d,%d,%d", cfg->colours[i][0],
cfg->colours[i][1], cfg->colours[i][2]);
write_setting_s(sesskey, buf, buf2);
}
write_setting_i(sesskey, "RawCNP", cfg->rawcnp);
write_setting_i(sesskey, "PasteRTF", cfg->rtf_paste);
write_setting_i(sesskey, "MouseIsXterm", cfg->mouse_is_xterm);
write_setting_i(sesskey, "RectSelect", cfg->rect_select);
write_setting_i(sesskey, "MouseOverride", cfg->mouse_override);
for (i = 0; i < 256; i += 32) {
char buf[20], buf2[256];
int j;
sprintf(buf, "Wordness%d", i);
*buf2 = '\0';
for (j = i; j < i + 32; j++) {
sprintf(buf2 + strlen(buf2), "%s%d",
(*buf2 ? "," : ""), cfg->wordness[j]);
}
write_setting_s(sesskey, buf, buf2);
}
write_setting_s(sesskey, "LineCodePage", cfg->line_codepage);
write_setting_i(sesskey, "CJKAmbigWide", cfg->cjk_ambig_wide);
write_setting_i(sesskey, "UTF8Override", cfg->utf8_override);
write_setting_s(sesskey, "Printer", cfg->printer);
write_setting_i(sesskey, "CapsLockCyr", cfg->xlat_capslockcyr);
write_setting_i(sesskey, "ScrollBar", cfg->scrollbar);
write_setting_i(sesskey, "ScrollBarFullScreen", cfg->scrollbar_in_fullscreen);
write_setting_i(sesskey, "ScrollOnKey", cfg->scroll_on_key);
write_setting_i(sesskey, "ScrollOnDisp", cfg->scroll_on_disp);
write_setting_i(sesskey, "EraseToScrollback", cfg->erase_to_scrollback);
write_setting_i(sesskey, "LockSize", cfg->resize_action);
write_setting_i(sesskey, "BCE", cfg->bce);
write_setting_i(sesskey, "BlinkText", cfg->blinktext);
write_setting_i(sesskey, "X11Forward", cfg->x11_forward);
write_setting_s(sesskey, "X11Display", cfg->x11_display);
write_setting_i(sesskey, "X11AuthType", cfg->x11_auth);
write_setting_i(sesskey, "LocalPortAcceptAll", cfg->lport_acceptall);
write_setting_i(sesskey, "RemotePortAcceptAll", cfg->rport_acceptall);
wmap(sesskey, "PortForwardings", cfg->portfwd, lenof(cfg->portfwd));
write_setting_i(sesskey, "BugIgnore1", 2-cfg->sshbug_ignore1);
write_setting_i(sesskey, "BugPlainPW1", 2-cfg->sshbug_plainpw1);
write_setting_i(sesskey, "BugRSA1", 2-cfg->sshbug_rsa1);
write_setting_i(sesskey, "BugHMAC2", 2-cfg->sshbug_hmac2);
write_setting_i(sesskey, "BugDeriveKey2", 2-cfg->sshbug_derivekey2);
write_setting_i(sesskey, "BugRSAPad2", 2-cfg->sshbug_rsapad2);
write_setting_i(sesskey, "BugPKSessID2", 2-cfg->sshbug_pksessid2);
write_setting_i(sesskey, "BugRekey2", 2-cfg->sshbug_rekey2);
write_setting_i(sesskey, "StampUtmp", cfg->stamp_utmp);
write_setting_i(sesskey, "LoginShell", cfg->login_shell);
write_setting_i(sesskey, "ScrollbarOnLeft", cfg->scrollbar_on_left);
write_setting_fontspec(sesskey, "BoldFont", cfg->boldfont);
write_setting_fontspec(sesskey, "WideFont", cfg->widefont);
write_setting_fontspec(sesskey, "WideBoldFont", cfg->wideboldfont);
write_setting_i(sesskey, "ShadowBold", cfg->shadowbold);
write_setting_i(sesskey, "ShadowBoldOffset", cfg->shadowboldoffset);
write_setting_s(sesskey, "SerialLine", cfg->serline);
write_setting_i(sesskey, "SerialSpeed", cfg->serspeed);
write_setting_i(sesskey, "SerialDataBits", cfg->serdatabits);
write_setting_i(sesskey, "SerialStopHalfbits", cfg->serstopbits);
write_setting_i(sesskey, "SerialParity", cfg->serparity);
write_setting_i(sesskey, "SerialFlowControl", cfg->serflow);
}
void load_settings(char *section, Config * cfg)
{
void *sesskey;
sesskey = open_settings_r(section);
load_open_settings(sesskey, cfg);
close_settings_r(sesskey);
}
void load_open_settings(void *sesskey, Config *cfg)
{
int i;
char prot[10];
cfg->ssh_subsys = 0; /* FIXME: load this properly */
cfg->remote_cmd_ptr = NULL;
cfg->remote_cmd_ptr2 = NULL;
cfg->ssh_nc_host[0] = '\0';
gpps(sesskey, "HostName", "", cfg->host, sizeof(cfg->host));
gppfile(sesskey, "LogFileName", &cfg->logfilename);
gppi(sesskey, "LogType", 0, &cfg->logtype);
gppi(sesskey, "LogFileClash", LGXF_ASK, &cfg->logxfovr);
gppi(sesskey, "LogFlush", 1, &cfg->logflush);
gppi(sesskey, "SSHLogOmitPasswords", 1, &cfg->logomitpass);
gppi(sesskey, "SSHLogOmitData", 0, &cfg->logomitdata);
gpps(sesskey, "Protocol", "default", prot, 10);
cfg->protocol = default_protocol;
cfg->port = default_port;
for (i = 0; backends[i].name != NULL; i++)
if (!strcmp(prot, backends[i].name)) {
cfg->protocol = backends[i].protocol;
gppi(sesskey, "PortNumber", default_port, &cfg->port);
break;
}
/* Address family selection */
gppi(sesskey, "AddressFamily", ADDRTYPE_UNSPEC, &cfg->addressfamily);
/* The CloseOnExit numbers are arranged in a different order from
* the standard FORCE_ON / FORCE_OFF / AUTO. */
gppi(sesskey, "CloseOnExit", 1, &i); cfg->close_on_exit = (i+1)%3;
gppi(sesskey, "WarnOnClose", 1, &cfg->warn_on_close);
{
/* This is two values for backward compatibility with 0.50/0.51 */
int pingmin, pingsec;
gppi(sesskey, "PingInterval", 0, &pingmin);
gppi(sesskey, "PingIntervalSecs", 0, &pingsec);
cfg->ping_interval = pingmin * 60 + pingsec;
}
gppi(sesskey, "TCPNoDelay", 1, &cfg->tcp_nodelay);
gppi(sesskey, "TCPKeepalives", 0, &cfg->tcp_keepalives);
gpps(sesskey, "TerminalType", "xterm", cfg->termtype,
sizeof(cfg->termtype));
gpps(sesskey, "TerminalSpeed", "38400,38400", cfg->termspeed,
sizeof(cfg->termspeed));
{
/* This hardcodes a big set of defaults in any new saved
* sessions. Let's hope we don't change our mind. */
int i;
char *def = dupstr("");
/* Default: all set to "auto" */
for (i = 0; ttymodes[i]; i++) {
char *def2 = dupprintf("%s%s=A,", def, ttymodes[i]);
sfree(def);
def = def2;
}
gppmap(sesskey, "TerminalModes", def,
cfg->ttymodes, lenof(cfg->ttymodes));
sfree(def);
}
/* proxy settings */
gpps(sesskey, "ProxyExcludeList", "", cfg->proxy_exclude_list,
sizeof(cfg->proxy_exclude_list));
gppi(sesskey, "ProxyDNS", 1, &i); cfg->proxy_dns = (i+1)%3;
gppi(sesskey, "ProxyLocalhost", 0, &cfg->even_proxy_localhost);
gppi(sesskey, "ProxyMethod", -1, &cfg->proxy_type);
if (cfg->proxy_type == -1) {
int i;
gppi(sesskey, "ProxyType", 0, &i);
if (i == 0)
cfg->proxy_type = PROXY_NONE;
else if (i == 1)
cfg->proxy_type = PROXY_HTTP;
else if (i == 3)
cfg->proxy_type = PROXY_TELNET;
else if (i == 4)
cfg->proxy_type = PROXY_CMD;
else {
gppi(sesskey, "ProxySOCKSVersion", 5, &i);
if (i == 5)
cfg->proxy_type = PROXY_SOCKS5;
else
cfg->proxy_type = PROXY_SOCKS4;
}
}
gpps(sesskey, "ProxyHost", "proxy", cfg->proxy_host,
sizeof(cfg->proxy_host));
gppi(sesskey, "ProxyPort", 80, &cfg->proxy_port);
gpps(sesskey, "ProxyUsername", "", cfg->proxy_username,
sizeof(cfg->proxy_username));
gpps(sesskey, "ProxyPassword", "", cfg->proxy_password,
sizeof(cfg->proxy_password));
gpps(sesskey, "ProxyTelnetCommand", "connect %host %port\\n",
cfg->proxy_telnet_command, sizeof(cfg->proxy_telnet_command));
gppmap(sesskey, "Environment", "", cfg->environmt, lenof(cfg->environmt));
gpps(sesskey, "UserName", "", cfg->username, sizeof(cfg->username));
gpps(sesskey, "LocalUserName", "", cfg->localusername,
sizeof(cfg->localusername));
gppi(sesskey, "NoPTY", 0, &cfg->nopty);
gppi(sesskey, "Compression", 0, &cfg->compression);
gppi(sesskey, "TryAgent", 1, &cfg->tryagent);
gppi(sesskey, "AgentFwd", 0, &cfg->agentfwd);
gppi(sesskey, "ChangeUsername", 0, &cfg->change_username);
gprefs(sesskey, "Cipher", "\0",
ciphernames, CIPHER_MAX, cfg->ssh_cipherlist);
{
/* Backward-compatibility: we used to have an option to
* disable gex under the "bugs" panel after one report of
* a server which offered it then choked, but we never got
* a server version string or any other reports. */
char *default_kexes;
gppi(sesskey, "BugDHGEx2", 0, &i); i = 2-i;
if (i == FORCE_ON)
default_kexes = "dh-group14-sha1,dh-group1-sha1,WARN,dh-gex-sha1";
else
default_kexes = "dh-gex-sha1,dh-group14-sha1,dh-group1-sha1,WARN";
gprefs(sesskey, "KEX", default_kexes,
kexnames, KEX_MAX, cfg->ssh_kexlist);
}
gppi(sesskey, "RekeyTime", 60, &cfg->ssh_rekey_time);
gpps(sesskey, "RekeyBytes", "1G", cfg->ssh_rekey_data,
sizeof(cfg->ssh_rekey_data));
gppi(sesskey, "SshProt", 2, &cfg->sshprot);
gppi(sesskey, "SSH2DES", 0, &cfg->ssh2_des_cbc);
gppi(sesskey, "SshNoAuth", 0, &cfg->ssh_no_userauth);
gppi(sesskey, "AuthTIS", 0, &cfg->try_tis_auth);
gppi(sesskey, "AuthKI", 1, &cfg->try_ki_auth);
gppi(sesskey, "SshNoShell", 0, &cfg->ssh_no_shell);
gppfile(sesskey, "PublicKeyFile", &cfg->keyfile);
gpps(sesskey, "RemoteCommand", "", cfg->remote_cmd,
sizeof(cfg->remote_cmd));
gppi(sesskey, "RFCEnviron", 0, &cfg->rfc_environ);
gppi(sesskey, "PassiveTelnet", 0, &cfg->passive_telnet);
gppi(sesskey, "BackspaceIsDelete", 1, &cfg->bksp_is_delete);
gppi(sesskey, "RXVTHomeEnd", 0, &cfg->rxvt_homeend);
gppi(sesskey, "LinuxFunctionKeys", 0, &cfg->funky_type);
gppi(sesskey, "NoApplicationKeys", 0, &cfg->no_applic_k);
gppi(sesskey, "NoApplicationCursors", 0, &cfg->no_applic_c);
gppi(sesskey, "NoMouseReporting", 0, &cfg->no_mouse_rep);
gppi(sesskey, "NoRemoteResize", 0, &cfg->no_remote_resize);
gppi(sesskey, "NoAltScreen", 0, &cfg->no_alt_screen);
gppi(sesskey, "NoRemoteWinTitle", 0, &cfg->no_remote_wintitle);
{
/* Backward compatibility */
int no_remote_qtitle;
gppi(sesskey, "NoRemoteQTitle", 1, &no_remote_qtitle);
/* We deliberately interpret the old setting of "no response" as
* "empty string". This changes the behaviour, but hopefully for
* the better; the user can always recover the old behaviour. */
gppi(sesskey, "RemoteQTitleAction",
no_remote_qtitle ? TITLE_EMPTY : TITLE_REAL,
&cfg->remote_qtitle_action);
}
gppi(sesskey, "NoDBackspace", 0, &cfg->no_dbackspace);
gppi(sesskey, "NoRemoteCharset", 0, &cfg->no_remote_charset);
gppi(sesskey, "ApplicationCursorKeys", 0, &cfg->app_cursor);
gppi(sesskey, "ApplicationKeypad", 0, &cfg->app_keypad);
gppi(sesskey, "NetHackKeypad", 0, &cfg->nethack_keypad);
gppi(sesskey, "AltF4", 1, &cfg->alt_f4);
gppi(sesskey, "AltSpace", 0, &cfg->alt_space);
gppi(sesskey, "AltOnly", 0, &cfg->alt_only);
gppi(sesskey, "ComposeKey", 0, &cfg->compose_key);
gppi(sesskey, "CtrlAltKeys", 1, &cfg->ctrlaltkeys);
gppi(sesskey, "TelnetKey", 0, &cfg->telnet_keyboard);
gppi(sesskey, "TelnetRet", 1, &cfg->telnet_newline);
gppi(sesskey, "LocalEcho", AUTO, &cfg->localecho);
gppi(sesskey, "LocalEdit", AUTO, &cfg->localedit);
gpps(sesskey, "Answerback", "PuTTY", cfg->answerback,
sizeof(cfg->answerback));
gppi(sesskey, "AlwaysOnTop", 0, &cfg->alwaysontop);
gppi(sesskey, "FullScreenOnAltEnter", 0, &cfg->fullscreenonaltenter);
gppi(sesskey, "HideMousePtr", 0, &cfg->hide_mouseptr);
gppi(sesskey, "SunkenEdge", 0, &cfg->sunken_edge);
gppi(sesskey, "WindowBorder", 1, &cfg->window_border);
gppi(sesskey, "CurType", 0, &cfg->cursor_type);
gppi(sesskey, "BlinkCur", 0, &cfg->blink_cur);
/* pedantic compiler tells me I can't use &cfg->beep as an int * :-) */
gppi(sesskey, "Beep", 1, &cfg->beep);
gppi(sesskey, "BeepInd", 0, &cfg->beep_ind);
gppfile(sesskey, "BellWaveFile", &cfg->bell_wavefile);
gppi(sesskey, "BellOverload", 1, &cfg->bellovl);
gppi(sesskey, "BellOverloadN", 5, &cfg->bellovl_n);
gppi(sesskey, "BellOverloadT", 2*TICKSPERSEC, &i);
cfg->bellovl_t = i
#ifdef PUTTY_UNIX_H
/ 1000
#endif
;
gppi(sesskey, "BellOverloadS", 5*TICKSPERSEC, &i);
cfg->bellovl_s = i
#ifdef PUTTY_UNIX_H
/ 1000
#endif
;
gppi(sesskey, "ScrollbackLines", 200, &cfg->savelines);
gppi(sesskey, "DECOriginMode", 0, &cfg->dec_om);
gppi(sesskey, "AutoWrapMode", 1, &cfg->wrap_mode);
gppi(sesskey, "LFImpliesCR", 0, &cfg->lfhascr);
gppi(sesskey, "DisableArabicShaping", 0, &cfg->arabicshaping);
gppi(sesskey, "DisableBidi", 0, &cfg->bidi);
gppi(sesskey, "WinNameAlways", 1, &cfg->win_name_always);
gpps(sesskey, "WinTitle", "", cfg->wintitle, sizeof(cfg->wintitle));
gppi(sesskey, "TermWidth", 80, &cfg->width);
gppi(sesskey, "TermHeight", 24, &cfg->height);
gppfont(sesskey, "Font", &cfg->font);
gppi(sesskey, "FontQuality", FQ_DEFAULT, &cfg->font_quality);
gppi(sesskey, "FontVTMode", VT_UNICODE, (int *) &cfg->vtmode);
gppi(sesskey, "UseSystemColours", 0, &cfg->system_colour);
gppi(sesskey, "TryPalette", 0, &cfg->try_palette);
gppi(sesskey, "ANSIColour", 1, &cfg->ansi_colour);
gppi(sesskey, "Xterm256Colour", 1, &cfg->xterm_256_colour);
gppi(sesskey, "BoldAsColour", 1, &cfg->bold_colour);
for (i = 0; i < 22; i++) {
static const char *const defaults[] = {
"187,187,187", "255,255,255", "0,0,0", "85,85,85", "0,0,0",
"0,255,0", "0,0,0", "85,85,85", "187,0,0", "255,85,85",
"0,187,0", "85,255,85", "187,187,0", "255,255,85", "0,0,187",
"85,85,255", "187,0,187", "255,85,255", "0,187,187",
"85,255,255", "187,187,187", "255,255,255"
};
char buf[20], buf2[30];
int c0, c1, c2;
sprintf(buf, "Colour%d", i);
gpps(sesskey, buf, defaults[i], buf2, sizeof(buf2));
if (sscanf(buf2, "%d,%d,%d", &c0, &c1, &c2) == 3) {
cfg->colours[i][0] = c0;
cfg->colours[i][1] = c1;
cfg->colours[i][2] = c2;
}
}
gppi(sesskey, "RawCNP", 0, &cfg->rawcnp);
gppi(sesskey, "PasteRTF", 0, &cfg->rtf_paste);
gppi(sesskey, "MouseIsXterm", 0, &cfg->mouse_is_xterm);
gppi(sesskey, "RectSelect", 0, &cfg->rect_select);
gppi(sesskey, "MouseOverride", 1, &cfg->mouse_override);
for (i = 0; i < 256; i += 32) {
static const char *const defaults[] = {
"0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
"0,1,2,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1",
"1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,2",
"1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1",
"1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
"1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",
"2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2",
"2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2"
};
char buf[20], buf2[256], *p;
int j;
sprintf(buf, "Wordness%d", i);
gpps(sesskey, buf, defaults[i / 32], buf2, sizeof(buf2));
p = buf2;
for (j = i; j < i + 32; j++) {
char *q = p;
while (*p && *p != ',')
p++;
if (*p == ',')
*p++ = '\0';
cfg->wordness[j] = atoi(q);
}
}
/*
* The empty default for LineCodePage will be converted later
* into a plausible default for the locale.
*/
gpps(sesskey, "LineCodePage", "", cfg->line_codepage,
sizeof(cfg->line_codepage));
gppi(sesskey, "CJKAmbigWide", 0, &cfg->cjk_ambig_wide);
gppi(sesskey, "UTF8Override", 1, &cfg->utf8_override);
gpps(sesskey, "Printer", "", cfg->printer, sizeof(cfg->printer));
gppi (sesskey, "CapsLockCyr", 0, &cfg->xlat_capslockcyr);
gppi(sesskey, "ScrollBar", 1, &cfg->scrollbar);
gppi(sesskey, "ScrollBarFullScreen", 0, &cfg->scrollbar_in_fullscreen);
gppi(sesskey, "ScrollOnKey", 0, &cfg->scroll_on_key);
gppi(sesskey, "ScrollOnDisp", 1, &cfg->scroll_on_disp);
gppi(sesskey, "EraseToScrollback", 1, &cfg->erase_to_scrollback);
gppi(sesskey, "LockSize", 0, &cfg->resize_action);
gppi(sesskey, "BCE", 1, &cfg->bce);
gppi(sesskey, "BlinkText", 0, &cfg->blinktext);
gppi(sesskey, "X11Forward", 0, &cfg->x11_forward);
gpps(sesskey, "X11Display", "", cfg->x11_display,
sizeof(cfg->x11_display));
gppi(sesskey, "X11AuthType", X11_MIT, &cfg->x11_auth);
gppi(sesskey, "LocalPortAcceptAll", 0, &cfg->lport_acceptall);
gppi(sesskey, "RemotePortAcceptAll", 0, &cfg->rport_acceptall);
gppmap(sesskey, "PortForwardings", "", cfg->portfwd, lenof(cfg->portfwd));
gppi(sesskey, "BugIgnore1", 0, &i); cfg->sshbug_ignore1 = 2-i;
gppi(sesskey, "BugPlainPW1", 0, &i); cfg->sshbug_plainpw1 = 2-i;
gppi(sesskey, "BugRSA1", 0, &i); cfg->sshbug_rsa1 = 2-i;
{
int i;
gppi(sesskey, "BugHMAC2", 0, &i); cfg->sshbug_hmac2 = 2-i;
if (cfg->sshbug_hmac2 == AUTO) {
gppi(sesskey, "BuggyMAC", 0, &i);
if (i == 1)
cfg->sshbug_hmac2 = FORCE_ON;
}
}
gppi(sesskey, "BugDeriveKey2", 0, &i); cfg->sshbug_derivekey2 = 2-i;
gppi(sesskey, "BugRSAPad2", 0, &i); cfg->sshbug_rsapad2 = 2-i;
gppi(sesskey, "BugPKSessID2", 0, &i); cfg->sshbug_pksessid2 = 2-i;
gppi(sesskey, "BugRekey2", 0, &i); cfg->sshbug_rekey2 = 2-i;
gppi(sesskey, "StampUtmp", 1, &cfg->stamp_utmp);
gppi(sesskey, "LoginShell", 1, &cfg->login_shell);
gppi(sesskey, "ScrollbarOnLeft", 0, &cfg->scrollbar_on_left);
gppi(sesskey, "ShadowBold", 0, &cfg->shadowbold);
gppfont(sesskey, "BoldFont", &cfg->boldfont);
gppfont(sesskey, "WideFont", &cfg->widefont);
gppfont(sesskey, "WideBoldFont", &cfg->wideboldfont);
gppi(sesskey, "ShadowBoldOffset", 1, &cfg->shadowboldoffset);
gpps(sesskey, "SerialLine", "", cfg->serline, sizeof(cfg->serline));
gppi(sesskey, "SerialSpeed", 9600, &cfg->serspeed);
gppi(sesskey, "SerialDataBits", 8, &cfg->serdatabits);
gppi(sesskey, "SerialStopHalfbits", 2, &cfg->serstopbits);
gppi(sesskey, "SerialParity", SER_PAR_NONE, &cfg->serparity);
gppi(sesskey, "SerialFlowControl", SER_FLOW_XONXOFF, &cfg->serflow);
}
void do_defaults(char *session, Config * cfg)
{
load_settings(session, cfg);
}
static int sessioncmp(const void *av, const void *bv)
{
const char *a = *(const char *const *) av;
const char *b = *(const char *const *) bv;
/*
* Alphabetical order, except that "Default Settings" is a
* special case and comes first.
*/
if (!strcmp(a, "Default Settings"))
return -1; /* a comes first */
if (!strcmp(b, "Default Settings"))
return +1; /* b comes first */
/*
* FIXME: perhaps we should ignore the first & in determining
* sort order.
*/
return strcmp(a, b); /* otherwise, compare normally */
}
void get_sesslist(struct sesslist *list, int allocate)
{
char otherbuf[2048];
int buflen, bufsize, i;
char *p, *ret;
void *handle;
if (allocate) {
buflen = bufsize = 0;
list->buffer = NULL;
if ((handle = enum_settings_start()) != NULL) {
do {
ret = enum_settings_next(handle, otherbuf, sizeof(otherbuf));
if (ret) {
int len = strlen(otherbuf) + 1;
if (bufsize < buflen + len) {
bufsize = buflen + len + 2048;
list->buffer = sresize(list->buffer, bufsize, char);
}
strcpy(list->buffer + buflen, otherbuf);
buflen += strlen(list->buffer + buflen) + 1;
}
} while (ret);
enum_settings_finish(handle);
}
list->buffer = sresize(list->buffer, buflen + 1, char);
list->buffer[buflen] = '\0';
/*
* Now set up the list of sessions. Note that "Default
* Settings" must always be claimed to exist, even if it
* doesn't really.
*/
p = list->buffer;
list->nsessions = 1; /* "Default Settings" counts as one */
while (*p) {
if (strcmp(p, "Default Settings"))
list->nsessions++;
while (*p)
p++;
p++;
}
list->sessions = snewn(list->nsessions + 1, char *);
list->sessions[0] = "Default Settings";
p = list->buffer;
i = 1;
while (*p) {
if (strcmp(p, "Default Settings"))
list->sessions[i++] = p;
while (*p)
p++;
p++;
}
qsort(list->sessions, i, sizeof(char *), sessioncmp);
} else {
sfree(list->buffer);
sfree(list->sessions);
list->buffer = NULL;
list->sessions = NULL;
}
}

1422
sFTPlugins/psftp/SFTP.C Normal file

File diff suppressed because it is too large Load Diff

248
sFTPlugins/psftp/SFTP.H Normal file
View File

@@ -0,0 +1,248 @@
/*
* sftp.h: definitions for SFTP and the sftp.c routines.
*/
#include "int64.h"
#define SSH_FXP_INIT 1 /* 0x1 */
#define SSH_FXP_VERSION 2 /* 0x2 */
#define SSH_FXP_OPEN 3 /* 0x3 */
#define SSH_FXP_CLOSE 4 /* 0x4 */
#define SSH_FXP_READ 5 /* 0x5 */
#define SSH_FXP_WRITE 6 /* 0x6 */
#define SSH_FXP_LSTAT 7 /* 0x7 */
#define SSH_FXP_FSTAT 8 /* 0x8 */
#define SSH_FXP_SETSTAT 9 /* 0x9 */
#define SSH_FXP_FSETSTAT 10 /* 0xa */
#define SSH_FXP_OPENDIR 11 /* 0xb */
#define SSH_FXP_READDIR 12 /* 0xc */
#define SSH_FXP_REMOVE 13 /* 0xd */
#define SSH_FXP_MKDIR 14 /* 0xe */
#define SSH_FXP_RMDIR 15 /* 0xf */
#define SSH_FXP_REALPATH 16 /* 0x10 */
#define SSH_FXP_STAT 17 /* 0x11 */
#define SSH_FXP_RENAME 18 /* 0x12 */
#define SSH_FXP_STATUS 101 /* 0x65 */
#define SSH_FXP_HANDLE 102 /* 0x66 */
#define SSH_FXP_DATA 103 /* 0x67 */
#define SSH_FXP_NAME 104 /* 0x68 */
#define SSH_FXP_ATTRS 105 /* 0x69 */
#define SSH_FXP_EXTENDED 200 /* 0xc8 */
#define SSH_FXP_EXTENDED_REPLY 201 /* 0xc9 */
#define SSH_FX_OK 0
#define SSH_FX_EOF 1
#define SSH_FX_NO_SUCH_FILE 2
#define SSH_FX_PERMISSION_DENIED 3
#define SSH_FX_FAILURE 4
#define SSH_FX_BAD_MESSAGE 5
#define SSH_FX_NO_CONNECTION 6
#define SSH_FX_CONNECTION_LOST 7
#define SSH_FX_OP_UNSUPPORTED 8
#define SSH_FILEXFER_ATTR_SIZE 0x00000001
#define SSH_FILEXFER_ATTR_UIDGID 0x00000002
#define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004
#define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008
#define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
#define SSH_FXF_READ 0x00000001
#define SSH_FXF_WRITE 0x00000002
#define SSH_FXF_APPEND 0x00000004
#define SSH_FXF_CREAT 0x00000008
#define SSH_FXF_TRUNC 0x00000010
#define SSH_FXF_EXCL 0x00000020
#define SFTP_PROTO_VERSION 3
/*
* External references. The sftp client module sftp.c expects to be
* able to get at these functions.
*
* sftp_recvdata must never return less than len. It either blocks
* until len is available, or it returns failure.
*
* Both functions return 1 on success, 0 on failure.
*/
int sftp_senddata(char *data, int len);
int sftp_recvdata(char *data, int len);
/*
* Free sftp_requests
*/
void sftp_cleanup_request(void);
struct fxp_attrs {
unsigned long flags;
uint64 size;
unsigned long uid;
unsigned long gid;
unsigned long permissions;
unsigned long atime;
unsigned long mtime;
};
struct fxp_handle {
char *hstring;
int hlen;
};
struct fxp_name {
char *filename, *longname;
struct fxp_attrs attrs;
};
struct fxp_names {
int nnames;
struct fxp_name *names;
};
struct sftp_request;
struct sftp_packet;
const char *fxp_error(void);
int fxp_error_type(void);
/*
* Perform exchange of init/version packets. Return 0 on failure.
*/
int fxp_init(void);
/*
* Canonify a pathname. Concatenate the two given path elements
* with a separating slash, unless the second is NULL.
*/
struct sftp_request *fxp_realpath_send(char *path);
char *fxp_realpath_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Open a file.
*/
struct sftp_request *fxp_open_send(char *path, int type);
struct fxp_handle *fxp_open_recv(struct sftp_packet *pktin,
struct sftp_request *req);
/*
* Open a directory.
*/
struct sftp_request *fxp_opendir_send(char *path);
struct fxp_handle *fxp_opendir_recv(struct sftp_packet *pktin,
struct sftp_request *req);
/*
* Close a file/dir.
*/
struct sftp_request *fxp_close_send(struct fxp_handle *handle);
void fxp_close_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Make a directory.
*/
struct sftp_request *fxp_mkdir_send(char *path);
int fxp_mkdir_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Remove a directory.
*/
struct sftp_request *fxp_rmdir_send(char *path);
int fxp_rmdir_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Remove a file.
*/
struct sftp_request *fxp_remove_send(char *fname);
int fxp_remove_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Rename a file.
*/
struct sftp_request *fxp_rename_send(char *srcfname, char *dstfname);
int fxp_rename_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Return file attributes.
*/
struct sftp_request *fxp_stat_send(char *fname);
int fxp_stat_recv(struct sftp_packet *pktin, struct sftp_request *req,
struct fxp_attrs *attrs);
struct sftp_request *fxp_fstat_send(struct fxp_handle *handle);
int fxp_fstat_recv(struct sftp_packet *pktin, struct sftp_request *req,
struct fxp_attrs *attrs);
/*
* Set file attributes.
*/
struct sftp_request *fxp_setstat_send(char *fname, struct fxp_attrs attrs);
int fxp_setstat_recv(struct sftp_packet *pktin, struct sftp_request *req);
struct sftp_request *fxp_fsetstat_send(struct fxp_handle *handle,
struct fxp_attrs attrs);
int fxp_fsetstat_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Read from a file.
*/
struct sftp_request *fxp_read_send(struct fxp_handle *handle,
uint64 offset, int len);
int fxp_read_recv(struct sftp_packet *pktin, struct sftp_request *req,
char *buffer, int len);
/*
* Write to a file. Returns 0 on error, 1 on OK.
*/
struct sftp_request *fxp_write_send(struct fxp_handle *handle,
char *buffer, uint64 offset, int len);
int fxp_write_recv(struct sftp_packet *pktin, struct sftp_request *req);
/*
* Read from a directory.
*/
struct sftp_request *fxp_readdir_send(struct fxp_handle *handle);
struct fxp_names *fxp_readdir_recv(struct sftp_packet *pktin,
struct sftp_request *req);
/*
* Free up an fxp_names structure.
*/
void fxp_free_names(struct fxp_names *names);
/*
* Duplicate and free fxp_name structures.
*/
struct fxp_name *fxp_dup_name(struct fxp_name *name);
void fxp_free_name(struct fxp_name *name);
/*
* Store user data in an sftp_request structure.
*/
void *fxp_get_userdata(struct sftp_request *req);
void fxp_set_userdata(struct sftp_request *req, void *data);
/*
* These functions might well be temporary placeholders to be
* replaced with more useful similar functions later. They form the
* main dispatch loop for processing incoming SFTP responses.
*/
void sftp_register(struct sftp_request *req);
struct sftp_request *sftp_find_request(struct sftp_packet *pktin);
struct sftp_packet *sftp_recv(void);
/*
* A wrapper to go round fxp_read_* and fxp_write_*, which manages
* the queueing of multiple read/write requests.
*/
struct fxp_xfer;
struct fxp_xfer *xfer_download_init(struct fxp_handle *fh, uint64 offset);
void xfer_download_queue(struct fxp_xfer *xfer);
int xfer_download_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin);
int xfer_download_data(struct fxp_xfer *xfer, void **buf, int *len);
struct fxp_xfer *xfer_upload_init(struct fxp_handle *fh, uint64 offset);
int xfer_upload_ready(struct fxp_xfer *xfer);
void xfer_upload_data(struct fxp_xfer *xfer, char *buffer, int len);
int xfer_upload_gotpkt(struct fxp_xfer *xfer, struct sftp_packet *pktin);
int xfer_done(struct fxp_xfer *xfer);
void xfer_set_error(struct fxp_xfer *xfer);
void xfer_cleanup(struct fxp_xfer *xfer);

9033
sFTPlugins/psftp/SSH.C Normal file

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More