mirror of
https://github.com/jellyfin/jellyfin.git
synced 2026-03-06 10:16:18 +00:00
merge common implementations and server implementations
This commit is contained in:
@@ -1,11 +1,5 @@
|
||||
using Emby.Common.Implementations;
|
||||
using Emby.Common.Implementations.Archiving;
|
||||
using Emby.Common.Implementations.IO;
|
||||
using Emby.Common.Implementations.Reflection;
|
||||
using Emby.Common.Implementations.ScheduledTasks;
|
||||
using Emby.Common.Implementations.Serialization;
|
||||
using Emby.Common.Implementations.TextEncoding;
|
||||
using Emby.Common.Implementations.Xml;
|
||||
using Emby.Dlna;
|
||||
using Emby.Dlna.ConnectionManager;
|
||||
using Emby.Dlna.ContentDirectory;
|
||||
@@ -110,12 +104,28 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Server.Implementations.Archiving;
|
||||
using Emby.Server.Implementations.Cryptography;
|
||||
using Emby.Server.Implementations.Diagnostics;
|
||||
using Emby.Server.Implementations.Net;
|
||||
using Emby.Server.Implementations.Reflection;
|
||||
using Emby.Server.Implementations.ScheduledTasks;
|
||||
using Emby.Server.Implementations.Serialization;
|
||||
using Emby.Server.Implementations.Threading;
|
||||
using Emby.Server.Implementations.Xml;
|
||||
using Emby.Server.MediaEncoding.Subtitles;
|
||||
using MediaBrowser.MediaEncoding.BdInfo;
|
||||
using MediaBrowser.Model.Cryptography;
|
||||
using MediaBrowser.Model.Events;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using MediaBrowser.Model.Threading;
|
||||
using StringExtensions = MediaBrowser.Controller.Extensions.StringExtensions;
|
||||
|
||||
namespace Emby.Server.Implementations
|
||||
@@ -123,8 +133,124 @@ namespace Emby.Server.Implementations
|
||||
/// <summary>
|
||||
/// Class CompositionRoot
|
||||
/// </summary>
|
||||
public abstract class ApplicationHost : BaseApplicationHost<ServerApplicationPaths>, IServerApplicationHost, IDependencyContainer
|
||||
public abstract class ApplicationHost : IServerApplicationHost, IDependencyContainer
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this instance can self restart.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance can self restart; otherwise, <c>false</c>.</value>
|
||||
public abstract bool CanSelfRestart { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance can self update.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance can self update; otherwise, <c>false</c>.</value>
|
||||
public virtual bool CanSelfUpdate
|
||||
{
|
||||
get
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when [has pending restart changed].
|
||||
/// </summary>
|
||||
public event EventHandler HasPendingRestartChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Occurs when [application updated].
|
||||
/// </summary>
|
||||
public event EventHandler<GenericEventArgs<PackageVersionInfo>> ApplicationUpdated;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether this instance has changes that require the entire application to restart.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
|
||||
public bool HasPendingRestart { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the logger.
|
||||
/// </summary>
|
||||
/// <value>The logger.</value>
|
||||
protected ILogger Logger { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the plugins.
|
||||
/// </summary>
|
||||
/// <value>The plugins.</value>
|
||||
public IPlugin[] Plugins { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the log manager.
|
||||
/// </summary>
|
||||
/// <value>The log manager.</value>
|
||||
public ILogManager LogManager { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the application paths.
|
||||
/// </summary>
|
||||
/// <value>The application paths.</value>
|
||||
protected ServerApplicationPaths ApplicationPaths { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets assemblies that failed to load
|
||||
/// </summary>
|
||||
/// <value>The failed assemblies.</value>
|
||||
public List<string> FailedAssemblies { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets all concrete types.
|
||||
/// </summary>
|
||||
/// <value>All concrete types.</value>
|
||||
public Type[] AllConcreteTypes { get; protected set; }
|
||||
|
||||
/// <summary>
|
||||
/// The disposable parts
|
||||
/// </summary>
|
||||
protected readonly List<IDisposable> DisposableParts = new List<IDisposable>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether this instance is first run.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance is first run; otherwise, <c>false</c>.</value>
|
||||
public bool IsFirstRun { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the configuration manager.
|
||||
/// </summary>
|
||||
/// <value>The configuration manager.</value>
|
||||
protected IConfigurationManager ConfigurationManager { get; set; }
|
||||
|
||||
public IFileSystem FileSystemManager { get; set; }
|
||||
|
||||
protected IEnvironmentInfo EnvironmentInfo { get; set; }
|
||||
|
||||
public PackageVersionClass SystemUpdateLevel
|
||||
{
|
||||
get
|
||||
{
|
||||
|
||||
#if BETA
|
||||
return PackageVersionClass.Beta;
|
||||
#endif
|
||||
return PackageVersionClass.Release;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual string OperatingSystemDisplayName
|
||||
{
|
||||
get { return EnvironmentInfo.OperatingSystemName; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The container
|
||||
/// </summary>
|
||||
protected readonly SimpleInjector.Container Container = new SimpleInjector.Container();
|
||||
|
||||
protected ISystemEvents SystemEvents { get; set; }
|
||||
protected IMemoryStreamFactory MemoryStreamFactory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the server configuration manager.
|
||||
/// </summary>
|
||||
@@ -138,7 +264,7 @@ namespace Emby.Server.Implementations
|
||||
/// Gets the configuration manager.
|
||||
/// </summary>
|
||||
/// <returns>IConfigurationManager.</returns>
|
||||
protected override IConfigurationManager GetConfigurationManager()
|
||||
protected IConfigurationManager GetConfigurationManager()
|
||||
{
|
||||
return new ServerConfigurationManager(ApplicationPaths, LogManager, XmlSerializer, FileSystemManager);
|
||||
}
|
||||
@@ -244,6 +370,17 @@ namespace Emby.Server.Implementations
|
||||
|
||||
private readonly Action<string, string, string> _certificateGenerator;
|
||||
private readonly Func<string> _defaultUserNameFactory;
|
||||
protected IProcessFactory ProcessFactory { get; private set; }
|
||||
protected ITimerFactory TimerFactory { get; private set; }
|
||||
protected ICryptoProvider CryptographyProvider = new CryptographyProvider();
|
||||
protected readonly IXmlSerializer XmlSerializer;
|
||||
|
||||
protected ISocketFactory SocketFactory { get; private set; }
|
||||
protected ITaskManager TaskManager { get; private set; }
|
||||
public IHttpClient HttpClient { get; private set; }
|
||||
protected INetworkManager NetworkManager { get; set; }
|
||||
public IJsonSerializer JsonSerializer { get; private set; }
|
||||
protected IIsoManager IsoManager { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ApplicationHost" /> class.
|
||||
@@ -261,14 +398,28 @@ namespace Emby.Server.Implementations
|
||||
INetworkManager networkManager,
|
||||
Action<string, string, string> certificateGenerator,
|
||||
Func<string> defaultUsernameFactory)
|
||||
: base(applicationPaths,
|
||||
logManager,
|
||||
fileSystem,
|
||||
environmentInfo,
|
||||
systemEvents,
|
||||
memoryStreamFactory,
|
||||
networkManager)
|
||||
{
|
||||
// hack alert, until common can target .net core
|
||||
BaseExtensions.CryptographyProvider = CryptographyProvider;
|
||||
|
||||
XmlSerializer = new MyXmlSerializer(fileSystem, logManager.GetLogger("XmlSerializer"));
|
||||
|
||||
NetworkManager = networkManager;
|
||||
EnvironmentInfo = environmentInfo;
|
||||
SystemEvents = systemEvents;
|
||||
MemoryStreamFactory = memoryStreamFactory;
|
||||
|
||||
FailedAssemblies = new List<string>();
|
||||
|
||||
ApplicationPaths = applicationPaths;
|
||||
LogManager = logManager;
|
||||
FileSystemManager = fileSystem;
|
||||
|
||||
ConfigurationManager = GetConfigurationManager();
|
||||
|
||||
// Initialize this early in case the -v command line option is used
|
||||
Logger = LogManager.GetLogger("App");
|
||||
|
||||
StartupOptions = options;
|
||||
_certificateGenerator = certificateGenerator;
|
||||
_releaseAssetFilename = releaseAssetFilename;
|
||||
@@ -292,7 +443,7 @@ namespace Emby.Server.Implementations
|
||||
/// Gets the current application version
|
||||
/// </summary>
|
||||
/// <value>The application version.</value>
|
||||
public override Version ApplicationVersion
|
||||
public Version ApplicationVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -308,11 +459,25 @@ namespace Emby.Server.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
private DeviceId _deviceId;
|
||||
public string SystemId
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_deviceId == null)
|
||||
{
|
||||
_deviceId = new DeviceId(ApplicationPaths, LogManager.GetLogger("SystemId"), FileSystemManager);
|
||||
}
|
||||
|
||||
return _deviceId.Value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name.
|
||||
/// </summary>
|
||||
/// <value>The name.</value>
|
||||
public override string Name
|
||||
public string Name
|
||||
{
|
||||
get
|
||||
{
|
||||
@@ -341,6 +506,159 @@ namespace Emby.Server.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of type and resolves all constructor dependancies
|
||||
/// </summary>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <returns>System.Object.</returns>
|
||||
public object CreateInstance(Type type)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Container.GetInstance(type);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error creating {0}", ex, type.FullName);
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the instance safe.
|
||||
/// </summary>
|
||||
/// <param name="type">The type.</param>
|
||||
/// <returns>System.Object.</returns>
|
||||
protected object CreateInstanceSafe(Type type)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Container.GetInstance(type);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error creating {0}", ex, type.FullName);
|
||||
// Don't blow up in release mode
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the specified obj.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="obj">The obj.</param>
|
||||
/// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
|
||||
protected void RegisterSingleInstance<T>(T obj, bool manageLifetime = true)
|
||||
where T : class
|
||||
{
|
||||
Container.RegisterSingleton(obj);
|
||||
|
||||
if (manageLifetime)
|
||||
{
|
||||
var disposable = obj as IDisposable;
|
||||
|
||||
if (disposable != null)
|
||||
{
|
||||
DisposableParts.Add(disposable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the single instance.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="func">The func.</param>
|
||||
protected void RegisterSingleInstance<T>(Func<T> func)
|
||||
where T : class
|
||||
{
|
||||
Container.RegisterSingleton(func);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves this instance.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns>``0.</returns>
|
||||
public T Resolve<T>()
|
||||
{
|
||||
return (T)Container.GetRegistration(typeof(T), true).GetInstance();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves this instance.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns>``0.</returns>
|
||||
public T TryResolve<T>()
|
||||
{
|
||||
var result = Container.GetRegistration(typeof(T), false);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
return (T)result.GetInstance();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads the assembly.
|
||||
/// </summary>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <returns>Assembly.</returns>
|
||||
protected Assembly LoadAssembly(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Assembly.Load(File.ReadAllBytes(file));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
FailedAssemblies.Add(file);
|
||||
Logger.ErrorException("Error loading assembly {0}", ex, file);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the export types.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <returns>IEnumerable{Type}.</returns>
|
||||
public IEnumerable<Type> GetExportTypes<T>()
|
||||
{
|
||||
var currentType = typeof(T);
|
||||
|
||||
return AllConcreteTypes.Where(currentType.IsAssignableFrom);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the exports.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
|
||||
/// <returns>IEnumerable{``0}.</returns>
|
||||
public IEnumerable<T> GetExports<T>(bool manageLiftime = true)
|
||||
{
|
||||
var parts = GetExportTypes<T>()
|
||||
.Select(CreateInstanceSafe)
|
||||
.Where(i => i != null)
|
||||
.Cast<T>()
|
||||
.ToList();
|
||||
|
||||
if (manageLiftime)
|
||||
{
|
||||
lock (DisposableParts)
|
||||
{
|
||||
DisposableParts.AddRange(parts.OfType<IDisposable>());
|
||||
}
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
private void SetBaseExceptionMessage()
|
||||
{
|
||||
var builder = GetBaseExceptionMessage(ApplicationPaths);
|
||||
@@ -354,9 +672,13 @@ namespace Emby.Server.Implementations
|
||||
/// <summary>
|
||||
/// Runs the startup tasks.
|
||||
/// </summary>
|
||||
public override async Task RunStartupTasks()
|
||||
public async Task RunStartupTasks()
|
||||
{
|
||||
await base.RunStartupTasks().ConfigureAwait(false);
|
||||
Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
|
||||
|
||||
ConfigureAutorun();
|
||||
|
||||
ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
|
||||
|
||||
await MediaEncoder.Init().ConfigureAwait(false);
|
||||
|
||||
@@ -395,7 +717,22 @@ namespace Emby.Server.Implementations
|
||||
LogManager.RemoveConsoleOutput();
|
||||
}
|
||||
|
||||
protected override IJsonSerializer CreateJsonSerializer()
|
||||
/// <summary>
|
||||
/// Configures the autorun.
|
||||
/// </summary>
|
||||
private void ConfigureAutorun()
|
||||
{
|
||||
try
|
||||
{
|
||||
ConfigureAutoRunAtStartup(ConfigurationManager.CommonConfiguration.RunAtStartup);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error configuring autorun", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private IJsonSerializer CreateJsonSerializer()
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -410,7 +747,7 @@ namespace Emby.Server.Implementations
|
||||
return new JsonSerializer(FileSystemManager, LogManager.GetLogger("JsonSerializer"));
|
||||
}
|
||||
|
||||
public override Task Init(IProgress<double> progress)
|
||||
public async Task Init(IProgress<double> progress)
|
||||
{
|
||||
HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
|
||||
HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
|
||||
@@ -422,7 +759,64 @@ namespace Emby.Server.Implementations
|
||||
HttpsPort = ServerConfiguration.DefaultHttpsPort;
|
||||
}
|
||||
|
||||
return base.Init(progress);
|
||||
progress.Report(1);
|
||||
|
||||
JsonSerializer = CreateJsonSerializer();
|
||||
|
||||
OnLoggerLoaded(true);
|
||||
LogManager.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
|
||||
|
||||
IsFirstRun = !ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted;
|
||||
progress.Report(2);
|
||||
|
||||
LogManager.LogSeverity = ConfigurationManager.CommonConfiguration.EnableDebugLevelLogging
|
||||
? LogSeverity.Debug
|
||||
: LogSeverity.Info;
|
||||
|
||||
progress.Report(3);
|
||||
|
||||
DiscoverTypes();
|
||||
progress.Report(14);
|
||||
|
||||
SetHttpLimit();
|
||||
progress.Report(15);
|
||||
|
||||
var innerProgress = new ActionableProgress<double>();
|
||||
innerProgress.RegisterAction(p => progress.Report(.8 * p + 15));
|
||||
|
||||
await RegisterResources(innerProgress).ConfigureAwait(false);
|
||||
|
||||
FindParts();
|
||||
progress.Report(95);
|
||||
|
||||
await InstallIsoMounters(CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
progress.Report(100);
|
||||
}
|
||||
|
||||
protected virtual void OnLoggerLoaded(bool isFirstLoad)
|
||||
{
|
||||
Logger.Info("Application version: {0}", ApplicationVersion);
|
||||
|
||||
if (!isFirstLoad)
|
||||
{
|
||||
LogEnvironmentInfo(Logger, ApplicationPaths, false);
|
||||
}
|
||||
|
||||
// Put the app config in the log for troubleshooting purposes
|
||||
Logger.LogMultiline("Application configuration:", LogSeverity.Info, new StringBuilder(JsonSerializer.SerializeToString(ConfigurationManager.CommonConfiguration)));
|
||||
|
||||
if (Plugins != null)
|
||||
{
|
||||
var pluginBuilder = new StringBuilder();
|
||||
|
||||
foreach (var plugin in Plugins)
|
||||
{
|
||||
pluginBuilder.AppendLine(string.Format("{0} {1}", plugin.Name, plugin.Version));
|
||||
}
|
||||
|
||||
Logger.LogMultiline("Plugins:", LogSeverity.Info, pluginBuilder);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract IConnectManager CreateConnectManager();
|
||||
@@ -431,9 +825,47 @@ namespace Emby.Server.Implementations
|
||||
/// <summary>
|
||||
/// Registers resources that classes will depend on
|
||||
/// </summary>
|
||||
protected override async Task RegisterResources(IProgress<double> progress)
|
||||
protected async Task RegisterResources(IProgress<double> progress)
|
||||
{
|
||||
await base.RegisterResources(progress).ConfigureAwait(false);
|
||||
RegisterSingleInstance(ConfigurationManager);
|
||||
RegisterSingleInstance<IApplicationHost>(this);
|
||||
|
||||
RegisterSingleInstance<IApplicationPaths>(ApplicationPaths);
|
||||
|
||||
RegisterSingleInstance(JsonSerializer);
|
||||
RegisterSingleInstance(MemoryStreamFactory);
|
||||
RegisterSingleInstance(SystemEvents);
|
||||
|
||||
RegisterSingleInstance(LogManager);
|
||||
RegisterSingleInstance(Logger);
|
||||
|
||||
RegisterSingleInstance(EnvironmentInfo);
|
||||
|
||||
RegisterSingleInstance(FileSystemManager);
|
||||
|
||||
HttpClient = new HttpClientManager.HttpClientManager(ApplicationPaths, LogManager.GetLogger("HttpClient"), FileSystemManager, MemoryStreamFactory, GetDefaultUserAgent);
|
||||
RegisterSingleInstance(HttpClient);
|
||||
|
||||
RegisterSingleInstance(NetworkManager);
|
||||
|
||||
IsoManager = new IsoManager();
|
||||
RegisterSingleInstance(IsoManager);
|
||||
|
||||
TaskManager = new TaskManager(ApplicationPaths, JsonSerializer, LogManager.GetLogger("TaskManager"), FileSystemManager, SystemEvents);
|
||||
RegisterSingleInstance(TaskManager);
|
||||
|
||||
RegisterSingleInstance(XmlSerializer);
|
||||
|
||||
ProcessFactory = new ProcessFactory();
|
||||
RegisterSingleInstance(ProcessFactory);
|
||||
|
||||
TimerFactory = new TimerFactory();
|
||||
RegisterSingleInstance(TimerFactory);
|
||||
|
||||
RegisterSingleInstance(CryptographyProvider);
|
||||
|
||||
SocketFactory = new SocketFactory(LogManager.GetLogger("SocketFactory"));
|
||||
RegisterSingleInstance(SocketFactory);
|
||||
|
||||
RegisterSingleInstance(PowerManagement);
|
||||
|
||||
@@ -460,7 +892,7 @@ namespace Emby.Server.Implementations
|
||||
StringExtensions.LocalizationManager = LocalizationManager;
|
||||
RegisterSingleInstance(LocalizationManager);
|
||||
|
||||
ITextEncoding textEncoding = new TextEncoding(FileSystemManager, LogManager.GetLogger("TextEncoding"), JsonSerializer);
|
||||
ITextEncoding textEncoding = new TextEncoding.TextEncoding(FileSystemManager, LogManager.GetLogger("TextEncoding"), JsonSerializer);
|
||||
RegisterSingleInstance(textEncoding);
|
||||
Utilities.EncodingHelper = textEncoding;
|
||||
RegisterSingleInstance<IBlurayExaminer>(() => new BdInfoExaminer(FileSystemManager, textEncoding));
|
||||
@@ -627,6 +1059,106 @@ namespace Emby.Server.Implementations
|
||||
await ((UserManager)UserManager).Initialize().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, bool isStartup)
|
||||
{
|
||||
logger.LogMultiline("Emby", LogSeverity.Info, GetBaseExceptionMessage(appPaths));
|
||||
}
|
||||
|
||||
protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
|
||||
builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", Environment.GetCommandLineArgs())));
|
||||
|
||||
builder.AppendLine(string.Format("Operating system: {0}", Environment.OSVersion));
|
||||
builder.AppendLine(string.Format("64-Bit OS: {0}", Environment.Is64BitOperatingSystem));
|
||||
builder.AppendLine(string.Format("64-Bit Process: {0}", Environment.Is64BitProcess));
|
||||
|
||||
Type type = Type.GetType("Mono.Runtime");
|
||||
if (type != null)
|
||||
{
|
||||
MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
|
||||
if (displayName != null)
|
||||
{
|
||||
builder.AppendLine("Mono: " + displayName.Invoke(null, null));
|
||||
}
|
||||
}
|
||||
|
||||
builder.AppendLine(string.Format("Processor count: {0}", Environment.ProcessorCount));
|
||||
builder.AppendLine(string.Format("Program data path: {0}", appPaths.ProgramDataPath));
|
||||
builder.AppendLine(string.Format("Application directory: {0}", appPaths.ProgramSystemPath));
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
private void SetHttpLimit()
|
||||
{
|
||||
try
|
||||
{
|
||||
// Increase the max http request limit
|
||||
ServicePointManager.DefaultConnectionLimit = Math.Max(96, ServicePointManager.DefaultConnectionLimit);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error setting http limit", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Installs the iso mounters.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
private async Task InstallIsoMounters(CancellationToken cancellationToken)
|
||||
{
|
||||
var list = new List<IIsoMounter>();
|
||||
|
||||
foreach (var isoMounter in GetExports<IIsoMounter>())
|
||||
{
|
||||
try
|
||||
{
|
||||
if (isoMounter.RequiresInstallation && !isoMounter.IsInstalled)
|
||||
{
|
||||
Logger.Info("Installing {0}", isoMounter.Name);
|
||||
|
||||
await isoMounter.Install(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
list.Add(isoMounter);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("{0} failed to load.", ex, isoMounter.Name);
|
||||
}
|
||||
}
|
||||
|
||||
IsoManager.AddParts(list);
|
||||
}
|
||||
|
||||
private string GetDefaultUserAgent()
|
||||
{
|
||||
var name = FormatAttribute(Name);
|
||||
|
||||
return name + "/" + ApplicationVersion;
|
||||
}
|
||||
|
||||
private string FormatAttribute(string str)
|
||||
{
|
||||
var arr = str.ToCharArray();
|
||||
|
||||
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|
||||
|| char.IsWhiteSpace(c))));
|
||||
|
||||
var result = new string(arr);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(result))
|
||||
{
|
||||
result = "Emby";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
protected virtual bool SupportsDualModeSockets
|
||||
{
|
||||
get
|
||||
@@ -889,7 +1421,7 @@ namespace Emby.Server.Implementations
|
||||
/// <summary>
|
||||
/// Finds the parts.
|
||||
/// </summary>
|
||||
protected override void FindParts()
|
||||
protected void FindParts()
|
||||
{
|
||||
if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
|
||||
{
|
||||
@@ -900,7 +1432,8 @@ namespace Emby.Server.Implementations
|
||||
|
||||
RegisterModules();
|
||||
|
||||
base.FindParts();
|
||||
ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
|
||||
Plugins = GetExports<IPlugin>().Select(LoadPlugin).Where(i => i != null).ToArray();
|
||||
|
||||
HttpServer.Init(GetExports<IService>(false));
|
||||
|
||||
@@ -937,6 +1470,104 @@ namespace Emby.Server.Implementations
|
||||
SyncManager.AddParts(GetExports<ISyncProvider>());
|
||||
}
|
||||
|
||||
private IPlugin LoadPlugin(IPlugin plugin)
|
||||
{
|
||||
try
|
||||
{
|
||||
var assemblyPlugin = plugin as IPluginAssembly;
|
||||
|
||||
if (assemblyPlugin != null)
|
||||
{
|
||||
var assembly = plugin.GetType().Assembly;
|
||||
var assemblyName = assembly.GetName();
|
||||
|
||||
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
|
||||
var assemblyId = new Guid(attribute.Value);
|
||||
|
||||
var assemblyFileName = assemblyName.Name + ".dll";
|
||||
var assemblyFilePath = Path.Combine(ApplicationPaths.PluginsPath, assemblyFileName);
|
||||
|
||||
assemblyPlugin.SetAttributes(assemblyFilePath, assemblyFileName, assemblyName.Version, assemblyId);
|
||||
}
|
||||
|
||||
var isFirstRun = !File.Exists(plugin.ConfigurationFilePath);
|
||||
plugin.SetStartupInfo(isFirstRun, File.GetLastWriteTimeUtc, s => Directory.CreateDirectory(s));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error loading plugin {0}", ex, plugin.GetType().FullName);
|
||||
return null;
|
||||
}
|
||||
|
||||
return plugin;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discovers the types.
|
||||
/// </summary>
|
||||
protected void DiscoverTypes()
|
||||
{
|
||||
FailedAssemblies.Clear();
|
||||
|
||||
var assemblies = GetComposablePartAssemblies().ToList();
|
||||
|
||||
foreach (var assembly in assemblies)
|
||||
{
|
||||
Logger.Info("Loading {0}", assembly.FullName);
|
||||
}
|
||||
|
||||
AllConcreteTypes = assemblies
|
||||
.SelectMany(GetTypes)
|
||||
.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a list of types within an assembly
|
||||
/// This will handle situations that would normally throw an exception - such as a type within the assembly that depends on some other non-existant reference
|
||||
/// </summary>
|
||||
/// <param name="assembly">The assembly.</param>
|
||||
/// <returns>IEnumerable{Type}.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">assembly</exception>
|
||||
protected List<Type> GetTypes(Assembly assembly)
|
||||
{
|
||||
if (assembly == null)
|
||||
{
|
||||
return new List<Type>();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// This null checking really shouldn't be needed but adding it due to some
|
||||
// unhandled exceptions in mono 5.0 that are a little hard to hunt down
|
||||
var types = assembly.GetTypes() ?? new Type[] { };
|
||||
return types.Where(t => t != null).ToList();
|
||||
}
|
||||
catch (ReflectionTypeLoadException ex)
|
||||
{
|
||||
if (ex.LoaderExceptions != null)
|
||||
{
|
||||
foreach (var loaderException in ex.LoaderExceptions)
|
||||
{
|
||||
if (loaderException != null)
|
||||
{
|
||||
Logger.Error("LoaderException: " + loaderException.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If it fails we can still get a list of the Types it was able to resolve
|
||||
var types = ex.Types ?? new Type[] { };
|
||||
return types.Where(t => t != null).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error loading types from assembly", ex);
|
||||
|
||||
return new List<Type>();
|
||||
}
|
||||
}
|
||||
|
||||
private CertificateInfo CertificateInfo { get; set; }
|
||||
private ICertificate Certificate { get; set; }
|
||||
|
||||
@@ -1043,9 +1674,9 @@ namespace Emby.Server.Implementations
|
||||
/// </summary>
|
||||
/// <param name="sender">The sender.</param>
|
||||
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
|
||||
protected override void OnConfigurationUpdated(object sender, EventArgs e)
|
||||
protected void OnConfigurationUpdated(object sender, EventArgs e)
|
||||
{
|
||||
base.OnConfigurationUpdated(sender, e);
|
||||
ConfigureAutorun();
|
||||
|
||||
var requiresRestart = false;
|
||||
|
||||
@@ -1088,10 +1719,27 @@ namespace Emby.Server.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notifies that the kernel that a change has been made that requires a restart
|
||||
/// </summary>
|
||||
public void NotifyPendingRestart()
|
||||
{
|
||||
Logger.Info("App needs to be restarted.");
|
||||
|
||||
var changed = !HasPendingRestart;
|
||||
|
||||
HasPendingRestart = true;
|
||||
|
||||
if (changed)
|
||||
{
|
||||
EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Restarts this instance.
|
||||
/// </summary>
|
||||
public override async Task Restart()
|
||||
public async Task Restart()
|
||||
{
|
||||
if (!CanSelfRestart)
|
||||
{
|
||||
@@ -1118,7 +1766,7 @@ namespace Emby.Server.Implementations
|
||||
/// Gets the composable part assemblies.
|
||||
/// </summary>
|
||||
/// <returns>IEnumerable{Assembly}.</returns>
|
||||
protected override IEnumerable<Assembly> GetComposablePartAssemblies()
|
||||
protected IEnumerable<Assembly> GetComposablePartAssemblies()
|
||||
{
|
||||
var list = GetPluginAssemblies()
|
||||
.ToList();
|
||||
@@ -1442,7 +2090,7 @@ namespace Emby.Server.Implementations
|
||||
/// <summary>
|
||||
/// Shuts down.
|
||||
/// </summary>
|
||||
public override async Task Shutdown()
|
||||
public async Task Shutdown()
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -1503,13 +2151,24 @@ namespace Emby.Server.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the plugin.
|
||||
/// </summary>
|
||||
/// <param name="plugin">The plugin.</param>
|
||||
public void RemovePlugin(IPlugin plugin)
|
||||
{
|
||||
var list = Plugins.ToList();
|
||||
list.Remove(plugin);
|
||||
Plugins = list.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks for update.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <param name="progress">The progress.</param>
|
||||
/// <returns>Task{CheckForUpdateResult}.</returns>
|
||||
public override async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
|
||||
public async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
var cacheLength = TimeSpan.FromHours(1);
|
||||
var updateLevel = SystemUpdateLevel;
|
||||
@@ -1533,7 +2192,7 @@ namespace Emby.Server.Implementations
|
||||
/// <param name="package">The package that contains the update</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <param name="progress">The progress.</param>
|
||||
public override async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
public async Task UpdateApplication(PackageVersionInfo package, CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
await InstallationManager.InstallPackage(package, false, progress, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
@@ -1546,7 +2205,7 @@ namespace Emby.Server.Implementations
|
||||
/// Configures the automatic run at startup.
|
||||
/// </summary>
|
||||
/// <param name="autorun">if set to <c>true</c> [autorun].</param>
|
||||
protected override void ConfigureAutoRunAtStartup(bool autorun)
|
||||
protected void ConfigureAutoRunAtStartup(bool autorun)
|
||||
{
|
||||
if (SupportsAutoRunAtStartup)
|
||||
{
|
||||
@@ -1641,6 +2300,62 @@ namespace Emby.Server.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called when [application updated].
|
||||
/// </summary>
|
||||
/// <param name="package">The package.</param>
|
||||
protected void OnApplicationUpdated(PackageVersionInfo package)
|
||||
{
|
||||
Logger.Info("Application has been updated to version {0}", package.versionStr);
|
||||
|
||||
EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
|
||||
{
|
||||
Argument = package
|
||||
|
||||
}, Logger);
|
||||
|
||||
NotifyPendingRestart();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged and - optionally - managed resources.
|
||||
/// </summary>
|
||||
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
|
||||
protected virtual void Dispose(bool dispose)
|
||||
{
|
||||
if (dispose)
|
||||
{
|
||||
var type = GetType();
|
||||
|
||||
Logger.Info("Disposing " + type.Name);
|
||||
|
||||
var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
|
||||
DisposableParts.Clear();
|
||||
|
||||
foreach (var part in parts)
|
||||
{
|
||||
Logger.Info("Disposing " + part.GetType().Name);
|
||||
|
||||
try
|
||||
{
|
||||
part.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error disposing {0}", ex, part.GetType().Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IDependencyContainer.RegisterSingleInstance<T>(T obj, bool manageLifetime)
|
||||
{
|
||||
RegisterSingleInstance(obj, manageLifetime);
|
||||
|
||||
193
Emby.Server.Implementations/Archiving/ZipClient.cs
Normal file
193
Emby.Server.Implementations/Archiving/ZipClient.cs
Normal file
@@ -0,0 +1,193 @@
|
||||
using System.IO;
|
||||
using MediaBrowser.Model.IO;
|
||||
using SharpCompress.Archives.Rar;
|
||||
using SharpCompress.Archives.SevenZip;
|
||||
using SharpCompress.Archives.Tar;
|
||||
using SharpCompress.Readers;
|
||||
using SharpCompress.Readers.Zip;
|
||||
|
||||
namespace Emby.Server.Implementations.Archiving
|
||||
{
|
||||
/// <summary>
|
||||
/// Class DotNetZipClient
|
||||
/// </summary>
|
||||
public class ZipClient : IZipClient
|
||||
{
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
public ZipClient(IFileSystem fileSystem)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">The source file.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAll(string sourceFile, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var fileStream = _fileSystem.OpenRead(sourceFile))
|
||||
{
|
||||
ExtractAll(fileStream, targetPath, overwriteExistingFiles);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all.
|
||||
/// </summary>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAll(Stream source, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var reader = ReaderFactory.Open(source))
|
||||
{
|
||||
var options = new ExtractionOptions();
|
||||
options.ExtractFullPath = true;
|
||||
|
||||
if (overwriteExistingFiles)
|
||||
{
|
||||
options.Overwrite = true;
|
||||
}
|
||||
|
||||
reader.WriteAllToDirectory(targetPath, options);
|
||||
}
|
||||
}
|
||||
|
||||
public void ExtractAllFromZip(Stream source, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var reader = ZipReader.Open(source))
|
||||
{
|
||||
var options = new ExtractionOptions();
|
||||
options.ExtractFullPath = true;
|
||||
|
||||
if (overwriteExistingFiles)
|
||||
{
|
||||
options.Overwrite = true;
|
||||
}
|
||||
|
||||
reader.WriteAllToDirectory(targetPath, options);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all from7z.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">The source file.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAllFrom7z(string sourceFile, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var fileStream = _fileSystem.OpenRead(sourceFile))
|
||||
{
|
||||
ExtractAllFrom7z(fileStream, targetPath, overwriteExistingFiles);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all from7z.
|
||||
/// </summary>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAllFrom7z(Stream source, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var archive = SevenZipArchive.Open(source))
|
||||
{
|
||||
using (var reader = archive.ExtractAllEntries())
|
||||
{
|
||||
var options = new ExtractionOptions();
|
||||
options.ExtractFullPath = true;
|
||||
|
||||
if (overwriteExistingFiles)
|
||||
{
|
||||
options.Overwrite = true;
|
||||
}
|
||||
|
||||
reader.WriteAllToDirectory(targetPath, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all from tar.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">The source file.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAllFromTar(string sourceFile, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var fileStream = _fileSystem.OpenRead(sourceFile))
|
||||
{
|
||||
ExtractAllFromTar(fileStream, targetPath, overwriteExistingFiles);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all from tar.
|
||||
/// </summary>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAllFromTar(Stream source, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var archive = TarArchive.Open(source))
|
||||
{
|
||||
using (var reader = archive.ExtractAllEntries())
|
||||
{
|
||||
var options = new ExtractionOptions();
|
||||
options.ExtractFullPath = true;
|
||||
|
||||
if (overwriteExistingFiles)
|
||||
{
|
||||
options.Overwrite = true;
|
||||
}
|
||||
|
||||
reader.WriteAllToDirectory(targetPath, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all from rar.
|
||||
/// </summary>
|
||||
/// <param name="sourceFile">The source file.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAllFromRar(string sourceFile, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var fileStream = _fileSystem.OpenRead(sourceFile))
|
||||
{
|
||||
ExtractAllFromRar(fileStream, targetPath, overwriteExistingFiles);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts all from rar.
|
||||
/// </summary>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <param name="overwriteExistingFiles">if set to <c>true</c> [overwrite existing files].</param>
|
||||
public void ExtractAllFromRar(Stream source, string targetPath, bool overwriteExistingFiles)
|
||||
{
|
||||
using (var archive = RarArchive.Open(source))
|
||||
{
|
||||
using (var reader = archive.ExtractAllEntries())
|
||||
{
|
||||
var options = new ExtractionOptions();
|
||||
options.ExtractFullPath = true;
|
||||
|
||||
if (overwriteExistingFiles)
|
||||
{
|
||||
options.Overwrite = true;
|
||||
}
|
||||
|
||||
reader.WriteAllToDirectory(targetPath, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MediaBrowser.Model.Cryptography;
|
||||
|
||||
namespace Emby.Server.Implementations.Cryptography
|
||||
{
|
||||
public class CryptographyProvider : ICryptoProvider
|
||||
{
|
||||
public Guid GetMD5(string str)
|
||||
{
|
||||
return new Guid(ComputeMD5(Encoding.Unicode.GetBytes(str)));
|
||||
}
|
||||
|
||||
public byte[] ComputeSHA1(byte[] bytes)
|
||||
{
|
||||
using (var provider = SHA1.Create())
|
||||
{
|
||||
return provider.ComputeHash(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] ComputeMD5(Stream str)
|
||||
{
|
||||
using (var provider = MD5.Create())
|
||||
{
|
||||
return provider.ComputeHash(str);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] ComputeMD5(byte[] bytes)
|
||||
{
|
||||
using (var provider = MD5.Create())
|
||||
{
|
||||
return provider.ComputeHash(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
109
Emby.Server.Implementations/Devices/DeviceId.cs
Normal file
109
Emby.Server.Implementations/Devices/DeviceId.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
|
||||
namespace Emby.Server.Implementations.Devices
|
||||
{
|
||||
public class DeviceId
|
||||
{
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
private readonly ILogger _logger;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
private readonly object _syncLock = new object();
|
||||
|
||||
private string CachePath
|
||||
{
|
||||
get { return Path.Combine(_appPaths.DataPath, "device.txt"); }
|
||||
}
|
||||
|
||||
private string GetCachedId()
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_syncLock)
|
||||
{
|
||||
var value = File.ReadAllText(CachePath, Encoding.UTF8);
|
||||
|
||||
Guid guid;
|
||||
if (Guid.TryParse(value, out guid))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
_logger.Error("Invalid value found in device id file");
|
||||
}
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error reading file", ex);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void SaveId(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = CachePath;
|
||||
|
||||
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(path));
|
||||
|
||||
lock (_syncLock)
|
||||
{
|
||||
_fileSystem.WriteAllText(path, id, Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error writing to file", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private string GetNewId()
|
||||
{
|
||||
return Guid.NewGuid().ToString("N");
|
||||
}
|
||||
|
||||
private string GetDeviceId()
|
||||
{
|
||||
var id = GetCachedId();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
id = GetNewId();
|
||||
SaveId(id);
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
private string _id;
|
||||
|
||||
public DeviceId(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
|
||||
{
|
||||
if (fileSystem == null) {
|
||||
throw new ArgumentNullException ("fileSystem");
|
||||
}
|
||||
|
||||
_appPaths = appPaths;
|
||||
_logger = logger;
|
||||
_fileSystem = fileSystem;
|
||||
}
|
||||
|
||||
public string Value
|
||||
{
|
||||
get { return _id ?? (_id = GetDeviceId()); }
|
||||
}
|
||||
}
|
||||
}
|
||||
109
Emby.Server.Implementations/Diagnostics/CommonProcess.cs
Normal file
109
Emby.Server.Implementations/Diagnostics/CommonProcess.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
|
||||
namespace Emby.Server.Implementations.Diagnostics
|
||||
{
|
||||
public class CommonProcess : IProcess
|
||||
{
|
||||
public event EventHandler Exited;
|
||||
|
||||
private readonly ProcessOptions _options;
|
||||
private readonly Process _process;
|
||||
|
||||
public CommonProcess(ProcessOptions options)
|
||||
{
|
||||
_options = options;
|
||||
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
Arguments = options.Arguments,
|
||||
FileName = options.FileName,
|
||||
WorkingDirectory = options.WorkingDirectory,
|
||||
UseShellExecute = options.UseShellExecute,
|
||||
CreateNoWindow = options.CreateNoWindow,
|
||||
RedirectStandardError = options.RedirectStandardError,
|
||||
RedirectStandardInput = options.RedirectStandardInput,
|
||||
RedirectStandardOutput = options.RedirectStandardOutput
|
||||
};
|
||||
|
||||
startInfo.ErrorDialog = options.ErrorDialog;
|
||||
|
||||
if (options.IsHidden)
|
||||
{
|
||||
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
|
||||
}
|
||||
|
||||
_process = new Process
|
||||
{
|
||||
StartInfo = startInfo
|
||||
};
|
||||
|
||||
if (options.EnableRaisingEvents)
|
||||
{
|
||||
_process.EnableRaisingEvents = true;
|
||||
_process.Exited += _process_Exited;
|
||||
}
|
||||
}
|
||||
|
||||
private void _process_Exited(object sender, EventArgs e)
|
||||
{
|
||||
if (Exited != null)
|
||||
{
|
||||
Exited(this, e);
|
||||
}
|
||||
}
|
||||
|
||||
public ProcessOptions StartInfo
|
||||
{
|
||||
get { return _options; }
|
||||
}
|
||||
|
||||
public StreamWriter StandardInput
|
||||
{
|
||||
get { return _process.StandardInput; }
|
||||
}
|
||||
|
||||
public StreamReader StandardError
|
||||
{
|
||||
get { return _process.StandardError; }
|
||||
}
|
||||
|
||||
public StreamReader StandardOutput
|
||||
{
|
||||
get { return _process.StandardOutput; }
|
||||
}
|
||||
|
||||
public int ExitCode
|
||||
{
|
||||
get { return _process.ExitCode; }
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_process.Start();
|
||||
}
|
||||
|
||||
public void Kill()
|
||||
{
|
||||
_process.Kill();
|
||||
}
|
||||
|
||||
public bool WaitForExit(int timeMs)
|
||||
{
|
||||
return _process.WaitForExit(timeMs);
|
||||
}
|
||||
|
||||
public Task<bool> WaitForExitAsync(int timeMs)
|
||||
{
|
||||
return Task.FromResult(_process.WaitForExit(timeMs));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_process.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
12
Emby.Server.Implementations/Diagnostics/ProcessFactory.cs
Normal file
12
Emby.Server.Implementations/Diagnostics/ProcessFactory.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
|
||||
namespace Emby.Server.Implementations.Diagnostics
|
||||
{
|
||||
public class ProcessFactory : IProcessFactory
|
||||
{
|
||||
public IProcess Create(ProcessOptions options)
|
||||
{
|
||||
return new CommonProcess(options);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,7 @@
|
||||
<Compile Include="AppBase\ConfigurationHelper.cs" />
|
||||
<Compile Include="ApplicationHost.cs" />
|
||||
<Compile Include="ApplicationPathHelper.cs" />
|
||||
<Compile Include="Archiving\ZipClient.cs" />
|
||||
<Compile Include="Branding\BrandingConfigurationFactory.cs" />
|
||||
<Compile Include="Browser\BrowserLauncher.cs" />
|
||||
<Compile Include="Channels\ChannelConfigurations.cs" />
|
||||
@@ -61,6 +62,7 @@
|
||||
<Compile Include="Cryptography\BitConverterLE.cs" />
|
||||
<Compile Include="Cryptography\CertificateGenerator.cs" />
|
||||
<Compile Include="Cryptography\CryptoConvert.cs" />
|
||||
<Compile Include="Cryptography\CryptographyProvider.cs" />
|
||||
<Compile Include="Cryptography\PfxGenerator.cs" />
|
||||
<Compile Include="Cryptography\PKCS1.cs" />
|
||||
<Compile Include="Cryptography\PKCS12.cs" />
|
||||
@@ -81,8 +83,11 @@
|
||||
<Compile Include="Data\SqliteUserRepository.cs" />
|
||||
<Compile Include="Data\TypeMapper.cs" />
|
||||
<Compile Include="Devices\CameraUploadsDynamicFolder.cs" />
|
||||
<Compile Include="Devices\DeviceId.cs" />
|
||||
<Compile Include="Devices\DeviceManager.cs" />
|
||||
<Compile Include="Devices\DeviceRepository.cs" />
|
||||
<Compile Include="Diagnostics\CommonProcess.cs" />
|
||||
<Compile Include="Diagnostics\ProcessFactory.cs" />
|
||||
<Compile Include="Dto\DtoService.cs" />
|
||||
<Compile Include="EntryPoints\AutomaticRestartEntryPoint.cs" />
|
||||
<Compile Include="EntryPoints\ExternalPortForwarding.cs" />
|
||||
@@ -98,9 +103,12 @@
|
||||
<Compile Include="EntryPoints\UsageEntryPoint.cs" />
|
||||
<Compile Include="EntryPoints\UsageReporter.cs" />
|
||||
<Compile Include="EntryPoints\UserDataChangeNotifier.cs" />
|
||||
<Compile Include="EnvironmentInfo\EnvironmentInfo.cs" />
|
||||
<Compile Include="FFMpeg\FFMpegInfo.cs" />
|
||||
<Compile Include="FFMpeg\FFMpegInstallInfo.cs" />
|
||||
<Compile Include="FFMpeg\FFMpegLoader.cs" />
|
||||
<Compile Include="HttpClientManager\HttpClientInfo.cs" />
|
||||
<Compile Include="HttpClientManager\HttpClientManager.cs" />
|
||||
<Compile Include="HttpServerFactory.cs" />
|
||||
<Compile Include="HttpServer\FileWriter.cs" />
|
||||
<Compile Include="HttpServer\HttpListenerHost.cs" />
|
||||
@@ -123,9 +131,237 @@
|
||||
<Compile Include="Images\BaseDynamicImageProvider.cs" />
|
||||
<Compile Include="IO\AsyncStreamCopier.cs" />
|
||||
<Compile Include="IO\FileRefresher.cs" />
|
||||
<Compile Include="IO\IsoManager.cs" />
|
||||
<Compile Include="IO\LibraryMonitor.cs" />
|
||||
<Compile Include="IO\LnkShortcutHandler.cs" />
|
||||
<Compile Include="IO\ManagedFileSystem.cs" />
|
||||
<Compile Include="IO\MbLinkShortcutHandler.cs" />
|
||||
<Compile Include="IO\MemoryStreamProvider.cs" />
|
||||
<Compile Include="IO\ProgressStream.cs" />
|
||||
<Compile Include="IO\SharpCifsFileSystem.cs" />
|
||||
<Compile Include="IO\SharpCifs\Config.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcBind.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcBinding.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcConstants.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcError.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcException.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcHandle.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcMessage.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcPipeHandle.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\DcerpcSecurityProvider.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\LsaPolicyHandle.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\Lsarpc.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\LsarSidArrayX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcDfsRootEnum.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcEnumerateAliasesInDomain.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcGetMembersInAlias.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcLookupSids.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcLsarOpenPolicy2.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcQueryInformationPolicy.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcSamrConnect2.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcSamrConnect4.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcSamrOpenAlias.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcSamrOpenDomain.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcShareEnum.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\MsrpcShareGetInfo.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\Netdfs.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\Samr.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\SamrAliasHandle.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\SamrDomainHandle.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\SamrPolicyHandle.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Msrpc\Srvsvc.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrBuffer.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrException.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrHyper.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrLong.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrObject.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrShort.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Ndr\NdrSmall.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\Rpc.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\UnicodeString.cs" />
|
||||
<Compile Include="IO\SharpCifs\Dcerpc\UUID.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\Lmhosts.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\Name.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NameQueryRequest.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NameQueryResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NameServiceClient.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NameServicePacket.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NbtAddress.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NbtException.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NodeStatusRequest.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\NodeStatusResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\SessionRequestPacket.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\SessionRetargetResponsePacket.cs" />
|
||||
<Compile Include="IO\SharpCifs\Netbios\SessionServicePacket.cs" />
|
||||
<Compile Include="IO\SharpCifs\Ntlmssp\NtlmFlags.cs" />
|
||||
<Compile Include="IO\SharpCifs\Ntlmssp\NtlmMessage.cs" />
|
||||
<Compile Include="IO\SharpCifs\Ntlmssp\Type1Message.cs" />
|
||||
<Compile Include="IO\SharpCifs\Ntlmssp\Type2Message.cs" />
|
||||
<Compile Include="IO\SharpCifs\Ntlmssp\Type3Message.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\ACE.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\AllocInfo.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\AndXServerMessageBlock.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\BufferCache.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Dfs.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\DfsReferral.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\DosError.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\DosFileFilter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\FileEntry.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\IInfo.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NetServerEnum2.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NetServerEnum2Response.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NetShareEnum.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NetShareEnumResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtlmAuthenticator.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtlmChallenge.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtlmContext.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtlmPasswordAuthentication.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtStatus.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtTransQuerySecurityDesc.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\NtTransQuerySecurityDescResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Principal.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SecurityDescriptor.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\ServerMessageBlock.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SID.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SigningDigest.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbAuthException.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComBlankResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComClose.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComCreateDirectory.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComDelete.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComDeleteDirectory.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComFindClose2.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComLogoffAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComNegotiate.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComNegotiateResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComNTCreateAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComNTCreateAndXResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComNtTransaction.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComNtTransactionResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComOpenAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComOpenAndXResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComQueryInformation.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComQueryInformationResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComReadAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComReadAndXResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComRename.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComSessionSetupAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComSessionSetupAndXResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComTransaction.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComTransactionResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComTreeConnectAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComTreeConnectAndXResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComTreeDisconnect.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComWrite.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComWriteAndX.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComWriteAndXResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbComWriteResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbConstants.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbException.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbFile.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbFileExtensions.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbFileFilter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbFileInputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbFilenameFilter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbFileOutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbNamedPipe.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbRandomAccessFile.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbSession.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbShareInfo.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbTransport.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\SmbTree.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2FindFirst2.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2FindFirst2Response.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2FindNext2.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2GetDfsReferral.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2GetDfsReferralResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2QueryFSInformation.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2QueryFSInformationResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2QueryPathInformation.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2QueryPathInformationResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2SetFileInformation.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\Trans2SetFileInformationResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransactNamedPipeInputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransactNamedPipeOutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransCallNamedPipe.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransCallNamedPipeResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransPeekNamedPipe.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransPeekNamedPipeResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransTransactNamedPipe.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransTransactNamedPipeResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransWaitNamedPipe.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\TransWaitNamedPipeResponse.cs" />
|
||||
<Compile Include="IO\SharpCifs\Smb\WinError.cs" />
|
||||
<Compile Include="IO\SharpCifs\UniAddress.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Base64.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\DES.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Encdec.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Hexdump.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\HMACT64.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\LogStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\MD4.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\RC4.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\AbstractMap.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Arrays.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\BufferedReader.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\BufferedWriter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\CharBuffer.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\CharSequence.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Collections.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ConcurrentHashMap.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\DateFormat.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\EnumeratorWrapper.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Exceptions.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Extensions.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FileInputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FileOutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FilePath.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FileReader.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FileWriter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FilterInputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\FilterOutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Hashtable.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\HttpURLConnection.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ICallable.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\IConcurrentMap.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\IExecutor.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\IFilenameFilter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\IFuture.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\InputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\InputStreamReader.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\IPrivilegedAction.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\IRunnable.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Iterator.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\LinkageError.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Matcher.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\MD5.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\MD5Managed.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\MessageDigest.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\NetworkStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ObjectInputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ObjectOutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\OutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\OutputStreamWriter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\PipedInputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\PipedOutputStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\PrintWriter.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Properties.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\RandomAccessFile.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ReentrantLock.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Reference.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Runtime.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\SimpleDateFormat.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\SocketEx.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\StringTokenizer.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\SynchronizedList.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\Thread.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ThreadFactory.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\ThreadPoolExecutor.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Sharpen\WrappedSystemStream.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Transport\Request.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Transport\Response.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Transport\Transport.cs" />
|
||||
<Compile Include="IO\SharpCifs\Util\Transport\TransportException.cs" />
|
||||
<Compile Include="IO\ThrottledStream.cs" />
|
||||
<Compile Include="Library\CoreResolutionIgnoreRule.cs" />
|
||||
<Compile Include="Library\LibraryManager.cs" />
|
||||
@@ -198,9 +434,17 @@
|
||||
<Compile Include="Localization\LocalizationManager.cs" />
|
||||
<Compile Include="Localization\TextLocalizer.cs" />
|
||||
<Compile Include="Logging\ConsoleLogger.cs" />
|
||||
<Compile Include="Logging\NLogger.cs" />
|
||||
<Compile Include="Logging\NlogManager.cs" />
|
||||
<Compile Include="Logging\UnhandledExceptionWriter.cs" />
|
||||
<Compile Include="MediaEncoder\EncodingManager.cs" />
|
||||
<Compile Include="Migrations\IVersionMigration.cs" />
|
||||
<Compile Include="Networking\NetworkManager.cs" />
|
||||
<Compile Include="Net\DisposableManagedObjectBase.cs" />
|
||||
<Compile Include="Net\NetAcceptSocket.cs" />
|
||||
<Compile Include="Net\SocketAcceptor.cs" />
|
||||
<Compile Include="Net\SocketFactory.cs" />
|
||||
<Compile Include="Net\UdpSocket.cs" />
|
||||
<Compile Include="News\NewsEntryPoint.cs" />
|
||||
<Compile Include="News\NewsService.cs" />
|
||||
<Compile Include="Notifications\CoreNotificationTypes.cs" />
|
||||
@@ -219,16 +463,29 @@
|
||||
<Compile Include="Playlists\PlaylistManager.cs" />
|
||||
<Compile Include="Playlists\PlaylistsDynamicFolder.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Reflection\AssemblyInfo.cs" />
|
||||
<Compile Include="ScheduledTasks\ChapterImagesTask.cs" />
|
||||
<Compile Include="ScheduledTasks\DailyTrigger.cs" />
|
||||
<Compile Include="ScheduledTasks\IntervalTrigger.cs" />
|
||||
<Compile Include="ScheduledTasks\PeopleValidationTask.cs" />
|
||||
<Compile Include="ScheduledTasks\PluginUpdateTask.cs" />
|
||||
<Compile Include="ScheduledTasks\RefreshMediaLibraryTask.cs" />
|
||||
<Compile Include="ScheduledTasks\ScheduledTaskWorker.cs" />
|
||||
<Compile Include="ScheduledTasks\StartupTrigger.cs" />
|
||||
<Compile Include="ScheduledTasks\SystemEventTrigger.cs" />
|
||||
<Compile Include="ScheduledTasks\SystemUpdateTask.cs" />
|
||||
<Compile Include="ScheduledTasks\TaskManager.cs" />
|
||||
<Compile Include="ScheduledTasks\Tasks\DeleteCacheFileTask.cs" />
|
||||
<Compile Include="ScheduledTasks\Tasks\DeleteLogFileTask.cs" />
|
||||
<Compile Include="ScheduledTasks\Tasks\ReloadLoggerFileTask.cs" />
|
||||
<Compile Include="ScheduledTasks\WeeklyTrigger.cs" />
|
||||
<Compile Include="Security\AuthenticationRepository.cs" />
|
||||
<Compile Include="Security\EncryptionManager.cs" />
|
||||
<Compile Include="Security\MBLicenseFile.cs" />
|
||||
<Compile Include="Security\PluginSecurityManager.cs" />
|
||||
<Compile Include="Security\RegRecord.cs" />
|
||||
<Compile Include="Serialization\JsonSerializer.cs" />
|
||||
<Compile Include="Serialization\XmlSerializer.cs" />
|
||||
<Compile Include="ServerApplicationPaths.cs" />
|
||||
<Compile Include="ServerManager\ServerManager.cs" />
|
||||
<Compile Include="ServerManager\WebSocketConnection.cs" />
|
||||
@@ -277,21 +534,72 @@
|
||||
<Compile Include="Sorting\StudioComparer.cs" />
|
||||
<Compile Include="StartupOptions.cs" />
|
||||
<Compile Include="SystemEvents.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Detector.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\DetectorFactory.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\ErrorCode.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Extensions\CharExtensions.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Extensions\RandomExtensions.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Extensions\StringExtensions.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Extensions\UnicodeBlock.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\GenProfile.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\InternalException.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Language.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\LanguageDetector.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\NLangDetectException.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\ProbVector.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Utils\LangProfile.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Utils\Messages.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Utils\NGram.cs" />
|
||||
<Compile Include="TextEncoding\NLangDetect\Utils\TagExtractor.cs" />
|
||||
<Compile Include="TextEncoding\TextEncoding.cs" />
|
||||
<Compile Include="TextEncoding\TextEncodingDetect.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\CharsetDetector.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\Big5Prober.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\BitPackage.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\CharDistributionAnalyser.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\CharsetProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\Charsets.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\CodingStateMachine.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\EscCharsetProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\EscSM.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\EUCJPProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\EUCKRProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\EUCTWProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\GB18030Prober.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\HebrewProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\JapaneseContextAnalyser.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\LangBulgarianModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\LangCyrillicModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\LangGreekModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\LangHebrewModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\LangHungarianModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\LangThaiModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\Latin1Prober.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\MBCSGroupProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\MBCSSM.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\SBCharsetProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\SBCSGroupProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\SequenceModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\SJISProber.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\SMModel.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\UniversalDetector.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\Core\UTF8Prober.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\DetectionConfidence.cs" />
|
||||
<Compile Include="TextEncoding\UniversalDetector\ICharsetDetector.cs" />
|
||||
<Compile Include="Threading\CommonTimer.cs" />
|
||||
<Compile Include="Threading\TimerFactory.cs" />
|
||||
<Compile Include="TV\SeriesPostScanTask.cs" />
|
||||
<Compile Include="TV\TVSeriesManager.cs" />
|
||||
<Compile Include="Udp\UdpServer.cs" />
|
||||
<Compile Include="Updates\InstallationManager.cs" />
|
||||
<Compile Include="UserViews\CollectionFolderImageProvider.cs" />
|
||||
<Compile Include="UserViews\DynamicImageProvider.cs" />
|
||||
<Compile Include="Xml\XmlReaderSettingsFactory.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Localization\iso6392.txt" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Emby.Common.Implementations\Emby.Common.Implementations.csproj">
|
||||
<Project>{1e37a338-9f57-4b70-bd6d-bb9c591e319b}</Project>
|
||||
<Name>Emby.Common.Implementations</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\Emby.Dlna\Emby.Dlna.csproj">
|
||||
<Project>{805844ab-e92f-45e6-9d99-4f6d48d129a5}</Project>
|
||||
<Name>Emby.Dlna</Name>
|
||||
@@ -366,10 +674,16 @@
|
||||
<Reference Include="Microsoft.IO.RecyclableMemoryStream, Version=1.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Microsoft.IO.RecyclableMemoryStream.1.2.2\lib\net45\Microsoft.IO.RecyclableMemoryStream.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.4.12\lib\net45\NLog.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="ServiceStack.Text, Version=4.5.8.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\ServiceStack.Text.4.5.8\lib\net45\ServiceStack.Text.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="SharpCompress, Version=0.14.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\SharpCompress.0.14.0\lib\net45\SharpCompress.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="SimpleInjector, Version=4.0.8.0, Culture=neutral, PublicKeyToken=984cb50dea722e99, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\SimpleInjector.4.0.8\lib\net45\SimpleInjector.dll</HintPath>
|
||||
</Reference>
|
||||
@@ -436,6 +750,60 @@
|
||||
<EmbeddedResource Include="Localization\Core\zh-TW.json" />
|
||||
<EmbeddedResource Include="Localization\countries.json" />
|
||||
<None Include="packages.config" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\afr" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ara" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ben" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\bul" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ces" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\dan" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\deu" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ell" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\eng" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\est" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\fas" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\fin" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\fra" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\guj" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\heb" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\hin" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\hrv" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\hun" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ind" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ita" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\jpn" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\kan" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\kor" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\lav" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\lit" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\mal" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\mar" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\mkd" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\nep" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\nld" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\nor" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\pan" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\pol" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\por" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ron" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\rus" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\slk" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\slv" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\som" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\spa" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\sqi" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\swa" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\swe" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\tam" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\tel" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\tgl" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\tha" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\tur" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\ukr" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\urd" />
|
||||
<None Include="TextEncoding\NLangDetect\Profiles\vie" />
|
||||
<EmbeddedResource Include="TextEncoding\NLangDetect\Profiles\zh-cn" />
|
||||
<EmbeddedResource Include="TextEncoding\NLangDetect\Profiles\zh-tw" />
|
||||
<EmbeddedResource Include="TextEncoding\NLangDetect\Utils\messages.properties" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Localization\Ratings\au.txt" />
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using MediaBrowser.Model.System;
|
||||
|
||||
namespace Emby.Server.Implementations.EnvironmentInfo
|
||||
{
|
||||
public class EnvironmentInfo : IEnvironmentInfo
|
||||
{
|
||||
public Architecture? CustomArchitecture { get; set; }
|
||||
public MediaBrowser.Model.System.OperatingSystem? CustomOperatingSystem { get; set; }
|
||||
|
||||
public virtual MediaBrowser.Model.System.OperatingSystem OperatingSystem
|
||||
{
|
||||
get
|
||||
{
|
||||
if (CustomOperatingSystem.HasValue)
|
||||
{
|
||||
return CustomOperatingSystem.Value;
|
||||
}
|
||||
|
||||
switch (Environment.OSVersion.Platform)
|
||||
{
|
||||
case PlatformID.MacOSX:
|
||||
return MediaBrowser.Model.System.OperatingSystem.OSX;
|
||||
case PlatformID.Win32NT:
|
||||
return MediaBrowser.Model.System.OperatingSystem.Windows;
|
||||
case PlatformID.Unix:
|
||||
return MediaBrowser.Model.System.OperatingSystem.Linux;
|
||||
}
|
||||
|
||||
return MediaBrowser.Model.System.OperatingSystem.Windows;
|
||||
}
|
||||
}
|
||||
|
||||
public string OperatingSystemName
|
||||
{
|
||||
get
|
||||
{
|
||||
return Environment.OSVersion.Platform.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public string OperatingSystemVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
return Environment.OSVersion.Version.ToString() + " " + Environment.OSVersion.ServicePack.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public char PathSeparator
|
||||
{
|
||||
get
|
||||
{
|
||||
return Path.PathSeparator;
|
||||
}
|
||||
}
|
||||
|
||||
public Architecture SystemArchitecture
|
||||
{
|
||||
get
|
||||
{
|
||||
if (CustomArchitecture.HasValue)
|
||||
{
|
||||
return CustomArchitecture.Value;
|
||||
}
|
||||
|
||||
return Environment.Is64BitOperatingSystem ? MediaBrowser.Model.System.Architecture.X64 : MediaBrowser.Model.System.Architecture.X86;
|
||||
}
|
||||
}
|
||||
|
||||
public string GetEnvironmentVariable(string name)
|
||||
{
|
||||
return Environment.GetEnvironmentVariable(name);
|
||||
}
|
||||
|
||||
public virtual string GetUserId()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public string StackTrace
|
||||
{
|
||||
get { return Environment.StackTrace; }
|
||||
}
|
||||
|
||||
public void SetProcessEnvironmentVariable(string name, string value)
|
||||
{
|
||||
Environment.SetEnvironmentVariable(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpClientManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Class HttpClientInfo
|
||||
/// </summary>
|
||||
public class HttpClientInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the last timeout.
|
||||
/// </summary>
|
||||
/// <value>The last timeout.</value>
|
||||
public DateTime LastTimeout { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,975 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Server.Implementations.IO;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.Net;
|
||||
|
||||
namespace Emby.Server.Implementations.HttpClientManager
|
||||
{
|
||||
/// <summary>
|
||||
/// Class HttpClientManager
|
||||
/// </summary>
|
||||
public class HttpClientManager : IHttpClient
|
||||
{
|
||||
/// <summary>
|
||||
/// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
|
||||
/// </summary>
|
||||
private const int TimeoutSeconds = 30;
|
||||
|
||||
/// <summary>
|
||||
/// The _logger
|
||||
/// </summary>
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// The _app paths
|
||||
/// </summary>
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IMemoryStreamFactory _memoryStreamProvider;
|
||||
private readonly Func<string> _defaultUserAgentFn;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpClientManager" /> class.
|
||||
/// </summary>
|
||||
public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem, IMemoryStreamFactory memoryStreamProvider, Func<string> defaultUserAgentFn)
|
||||
{
|
||||
if (appPaths == null)
|
||||
{
|
||||
throw new ArgumentNullException("appPaths");
|
||||
}
|
||||
if (logger == null)
|
||||
{
|
||||
throw new ArgumentNullException("logger");
|
||||
}
|
||||
|
||||
_logger = logger;
|
||||
_fileSystem = fileSystem;
|
||||
_memoryStreamProvider = memoryStreamProvider;
|
||||
_appPaths = appPaths;
|
||||
_defaultUserAgentFn = defaultUserAgentFn;
|
||||
|
||||
// http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
|
||||
ServicePointManager.Expect100Continue = false;
|
||||
|
||||
// Trakt requests sometimes fail without this
|
||||
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
|
||||
/// DON'T dispose it after use.
|
||||
/// </summary>
|
||||
/// <value>The HTTP clients.</value>
|
||||
private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets
|
||||
/// </summary>
|
||||
/// <param name="host">The host.</param>
|
||||
/// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
|
||||
/// <returns>HttpClient.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">host</exception>
|
||||
private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
|
||||
{
|
||||
if (string.IsNullOrEmpty(host))
|
||||
{
|
||||
throw new ArgumentNullException("host");
|
||||
}
|
||||
|
||||
HttpClientInfo client;
|
||||
|
||||
var key = host + enableHttpCompression;
|
||||
|
||||
if (!_httpClients.TryGetValue(key, out client))
|
||||
{
|
||||
client = new HttpClientInfo();
|
||||
|
||||
_httpClients.TryAdd(key, client);
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
private WebRequest CreateWebRequest(string url)
|
||||
{
|
||||
try
|
||||
{
|
||||
return WebRequest.Create(url);
|
||||
}
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
//Webrequest creation does fail on MONO randomly when using WebRequest.Create
|
||||
//the issue occurs in the GetCreator method here: http://www.oschina.net/code/explore/mono-2.8.1/mcs/class/System/System.Net/WebRequest.cs
|
||||
|
||||
var type = Type.GetType("System.Net.HttpRequestCreator, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089");
|
||||
var creator = Activator.CreateInstance(type, nonPublic: true) as IWebRequestCreate;
|
||||
return creator.Create(new Uri(url)) as HttpWebRequest;
|
||||
}
|
||||
}
|
||||
|
||||
private void AddIpv4Option(HttpWebRequest request, HttpRequestOptions options)
|
||||
{
|
||||
request.ServicePoint.BindIPEndPointDelegate = (servicePount, remoteEndPoint, retryCount) =>
|
||||
{
|
||||
if (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
return new IPEndPoint(IPAddress.Any, 0);
|
||||
}
|
||||
throw new InvalidOperationException("no IPv4 address");
|
||||
};
|
||||
}
|
||||
|
||||
private WebRequest GetRequest(HttpRequestOptions options, string method)
|
||||
{
|
||||
var url = options.Url;
|
||||
|
||||
var uriAddress = new Uri(url);
|
||||
var userInfo = uriAddress.UserInfo;
|
||||
if (!string.IsNullOrWhiteSpace(userInfo))
|
||||
{
|
||||
_logger.Info("Found userInfo in url: {0} ... url: {1}", userInfo, url);
|
||||
url = url.Replace(userInfo + "@", string.Empty);
|
||||
}
|
||||
|
||||
var request = CreateWebRequest(url);
|
||||
var httpWebRequest = request as HttpWebRequest;
|
||||
|
||||
if (httpWebRequest != null)
|
||||
{
|
||||
if (options.PreferIpv4)
|
||||
{
|
||||
AddIpv4Option(httpWebRequest, options);
|
||||
}
|
||||
|
||||
AddRequestHeaders(httpWebRequest, options);
|
||||
|
||||
if (options.EnableHttpCompression)
|
||||
{
|
||||
if (options.DecompressionMethod.HasValue)
|
||||
{
|
||||
httpWebRequest.AutomaticDecompression = options.DecompressionMethod.Value == CompressionMethod.Gzip
|
||||
? DecompressionMethods.GZip
|
||||
: DecompressionMethods.Deflate;
|
||||
}
|
||||
else
|
||||
{
|
||||
httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
|
||||
|
||||
if (httpWebRequest != null)
|
||||
{
|
||||
if (options.EnableKeepAlive)
|
||||
{
|
||||
httpWebRequest.KeepAlive = true;
|
||||
}
|
||||
}
|
||||
|
||||
request.Method = method;
|
||||
request.Timeout = options.TimeoutMs;
|
||||
|
||||
if (httpWebRequest != null)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(options.Host))
|
||||
{
|
||||
httpWebRequest.Host = options.Host;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(options.Referer))
|
||||
{
|
||||
httpWebRequest.Referer = options.Referer;
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(userInfo))
|
||||
{
|
||||
var parts = userInfo.Split(':');
|
||||
if (parts.Length == 2)
|
||||
{
|
||||
request.Credentials = GetCredential(url, parts[0], parts[1]);
|
||||
// TODO: .net core ??
|
||||
request.PreAuthenticate = true;
|
||||
}
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
private CredentialCache GetCredential(string url, string username, string password)
|
||||
{
|
||||
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
|
||||
CredentialCache credentialCache = new CredentialCache();
|
||||
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
|
||||
return credentialCache;
|
||||
}
|
||||
|
||||
private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
|
||||
{
|
||||
var hasUserAgent = false;
|
||||
|
||||
foreach (var header in options.RequestHeaders.ToList())
|
||||
{
|
||||
if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
request.Accept = header.Value;
|
||||
}
|
||||
else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
SetUserAgent(request, header.Value);
|
||||
hasUserAgent = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
request.Headers.Set(header.Key, header.Value);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasUserAgent && options.EnableDefaultUserAgent)
|
||||
{
|
||||
SetUserAgent(request, _defaultUserAgentFn());
|
||||
}
|
||||
}
|
||||
|
||||
private void SetUserAgent(HttpWebRequest request, string userAgent)
|
||||
{
|
||||
request.UserAgent = userAgent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the response internal.
|
||||
/// </summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>Task{HttpResponseInfo}.</returns>
|
||||
public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
|
||||
{
|
||||
return SendAsync(options, "GET");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a GET request and returns the resulting stream
|
||||
/// </summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>Task{Stream}.</returns>
|
||||
public async Task<Stream> Get(HttpRequestOptions options)
|
||||
{
|
||||
var response = await GetResponse(options).ConfigureAwait(false);
|
||||
|
||||
return response.Content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a GET request and returns the resulting stream
|
||||
/// </summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <param name="resourcePool">The resource pool.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task{Stream}.</returns>
|
||||
public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
|
||||
{
|
||||
return Get(new HttpRequestOptions
|
||||
{
|
||||
Url = url,
|
||||
ResourcePool = resourcePool,
|
||||
CancellationToken = cancellationToken,
|
||||
BufferContent = resourcePool != null
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the specified URL.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task{Stream}.</returns>
|
||||
public Task<Stream> Get(string url, CancellationToken cancellationToken)
|
||||
{
|
||||
return Get(url, null, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// send as an asynchronous operation.
|
||||
/// </summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="httpMethod">The HTTP method.</param>
|
||||
/// <returns>Task{HttpResponseInfo}.</returns>
|
||||
/// <exception cref="HttpException">
|
||||
/// </exception>
|
||||
public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
|
||||
{
|
||||
if (options.CacheMode == CacheMode.None)
|
||||
{
|
||||
return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var url = options.Url;
|
||||
var urlHash = url.ToLower().GetMD5().ToString("N");
|
||||
|
||||
var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
|
||||
|
||||
var response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
|
||||
if (response != null)
|
||||
{
|
||||
return response;
|
||||
}
|
||||
|
||||
response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.OK)
|
||||
{
|
||||
await CacheResponse(response, responseCachePath).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
|
||||
{
|
||||
_logger.Info("Checking for cache file {0}", responseCachePath);
|
||||
|
||||
try
|
||||
{
|
||||
if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
|
||||
{
|
||||
using (var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
|
||||
{
|
||||
var memoryStream = _memoryStreamProvider.CreateNew();
|
||||
|
||||
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
|
||||
memoryStream.Position = 0;
|
||||
|
||||
return new HttpResponseInfo
|
||||
{
|
||||
ResponseUrl = url,
|
||||
Content = memoryStream,
|
||||
StatusCode = HttpStatusCode.OK,
|
||||
ContentLength = memoryStream.Length
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
|
||||
{
|
||||
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(responseCachePath));
|
||||
|
||||
using (var responseStream = response.Content)
|
||||
{
|
||||
var memoryStream = _memoryStreamProvider.CreateNew();
|
||||
await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
|
||||
memoryStream.Position = 0;
|
||||
|
||||
using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
|
||||
{
|
||||
await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
|
||||
|
||||
memoryStream.Position = 0;
|
||||
response.Content = memoryStream;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
|
||||
{
|
||||
ValidateParams(options);
|
||||
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
|
||||
|
||||
if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
|
||||
{
|
||||
throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
|
||||
{
|
||||
IsTimedOut = true
|
||||
};
|
||||
}
|
||||
|
||||
var httpWebRequest = GetRequest(options, httpMethod);
|
||||
|
||||
if (options.RequestContentBytes != null ||
|
||||
!string.IsNullOrEmpty(options.RequestContent) ||
|
||||
string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
var bytes = options.RequestContentBytes ??
|
||||
Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
|
||||
|
||||
httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
|
||||
|
||||
httpWebRequest.ContentLength = bytes.Length;
|
||||
(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new HttpException(ex.Message) { IsTimedOut = true };
|
||||
}
|
||||
}
|
||||
|
||||
if (options.ResourcePool != null)
|
||||
{
|
||||
await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
|
||||
{
|
||||
if (options.ResourcePool != null)
|
||||
{
|
||||
options.ResourcePool.Release();
|
||||
}
|
||||
|
||||
throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
|
||||
}
|
||||
|
||||
if (options.LogRequest)
|
||||
{
|
||||
_logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (!options.BufferContent)
|
||||
{
|
||||
var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
|
||||
|
||||
var httpResponse = (HttpWebResponse)response;
|
||||
|
||||
EnsureSuccessStatusCode(client, httpResponse, options);
|
||||
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
|
||||
}
|
||||
|
||||
using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
|
||||
{
|
||||
var httpResponse = (HttpWebResponse)response;
|
||||
|
||||
EnsureSuccessStatusCode(client, httpResponse, options);
|
||||
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
using (var stream = httpResponse.GetResponseStream())
|
||||
{
|
||||
var memoryStream = _memoryStreamProvider.CreateNew();
|
||||
|
||||
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
|
||||
|
||||
memoryStream.Position = 0;
|
||||
|
||||
return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
throw GetCancellationException(options, client, options.CancellationToken, ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw GetException(ex, options, client);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (options.ResourcePool != null)
|
||||
{
|
||||
options.ResourcePool.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
|
||||
{
|
||||
var responseInfo = new HttpResponseInfo(disposable)
|
||||
{
|
||||
Content = content,
|
||||
|
||||
StatusCode = httpResponse.StatusCode,
|
||||
|
||||
ContentType = httpResponse.ContentType,
|
||||
|
||||
ContentLength = contentLength,
|
||||
|
||||
ResponseUrl = httpResponse.ResponseUri.ToString()
|
||||
};
|
||||
|
||||
if (httpResponse.Headers != null)
|
||||
{
|
||||
SetHeaders(httpResponse.Headers, responseInfo);
|
||||
}
|
||||
|
||||
return responseInfo;
|
||||
}
|
||||
|
||||
private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
|
||||
{
|
||||
var responseInfo = new HttpResponseInfo
|
||||
{
|
||||
TempFilePath = tempFile,
|
||||
|
||||
StatusCode = httpResponse.StatusCode,
|
||||
|
||||
ContentType = httpResponse.ContentType,
|
||||
|
||||
ContentLength = contentLength
|
||||
};
|
||||
|
||||
if (httpResponse.Headers != null)
|
||||
{
|
||||
SetHeaders(httpResponse.Headers, responseInfo);
|
||||
}
|
||||
|
||||
return responseInfo;
|
||||
}
|
||||
|
||||
private void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo)
|
||||
{
|
||||
foreach (var key in headers.AllKeys)
|
||||
{
|
||||
responseInfo.Headers[key] = headers[key];
|
||||
}
|
||||
}
|
||||
|
||||
public Task<HttpResponseInfo> Post(HttpRequestOptions options)
|
||||
{
|
||||
return SendAsync(options, "POST");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a POST request
|
||||
/// </summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="postData">Params to add to the POST data.</param>
|
||||
/// <returns>stream on success, null on failure</returns>
|
||||
public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
|
||||
{
|
||||
options.SetPostData(postData);
|
||||
|
||||
var response = await Post(options).ConfigureAwait(false);
|
||||
|
||||
return response.Content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a POST request
|
||||
/// </summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <param name="postData">Params to add to the POST data.</param>
|
||||
/// <param name="resourcePool">The resource pool.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>stream on success, null on failure</returns>
|
||||
public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
|
||||
{
|
||||
return Post(new HttpRequestOptions
|
||||
{
|
||||
Url = url,
|
||||
ResourcePool = resourcePool,
|
||||
CancellationToken = cancellationToken,
|
||||
BufferContent = resourcePool != null
|
||||
|
||||
}, postData);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads the contents of a given url into a temporary location
|
||||
/// </summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>Task{System.String}.</returns>
|
||||
public async Task<string> GetTempFile(HttpRequestOptions options)
|
||||
{
|
||||
var response = await GetTempFileResponse(options).ConfigureAwait(false);
|
||||
|
||||
return response.TempFilePath;
|
||||
}
|
||||
|
||||
public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
|
||||
{
|
||||
ValidateParams(options);
|
||||
|
||||
_fileSystem.CreateDirectory(_appPaths.TempDirectory);
|
||||
|
||||
var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
|
||||
|
||||
if (options.Progress == null)
|
||||
{
|
||||
throw new ArgumentNullException("progress");
|
||||
}
|
||||
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var httpWebRequest = GetRequest(options, "GET");
|
||||
|
||||
if (options.ResourcePool != null)
|
||||
{
|
||||
await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
options.Progress.Report(0);
|
||||
|
||||
if (options.LogRequest)
|
||||
{
|
||||
_logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
|
||||
}
|
||||
|
||||
var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
|
||||
|
||||
try
|
||||
{
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
|
||||
{
|
||||
var httpResponse = (HttpWebResponse)response;
|
||||
|
||||
EnsureSuccessStatusCode(client, httpResponse, options);
|
||||
|
||||
options.CancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var contentLength = GetContentLength(httpResponse);
|
||||
|
||||
if (!contentLength.HasValue)
|
||||
{
|
||||
// We're not able to track progress
|
||||
using (var stream = httpResponse.GetResponseStream())
|
||||
{
|
||||
using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
|
||||
{
|
||||
await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
|
||||
{
|
||||
using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
|
||||
{
|
||||
await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
options.Progress.Report(100);
|
||||
|
||||
return GetResponseInfo(httpResponse, tempFile, contentLength);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
DeleteTempFile(tempFile);
|
||||
throw GetException(ex, options, client);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (options.ResourcePool != null)
|
||||
{
|
||||
options.ResourcePool.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private long? GetContentLength(HttpWebResponse response)
|
||||
{
|
||||
var length = response.ContentLength;
|
||||
|
||||
if (length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return length;
|
||||
}
|
||||
|
||||
protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
|
||||
|
||||
private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
|
||||
{
|
||||
if (ex is HttpException)
|
||||
{
|
||||
return ex;
|
||||
}
|
||||
|
||||
var webException = ex as WebException
|
||||
?? ex.InnerException as WebException;
|
||||
|
||||
if (webException != null)
|
||||
{
|
||||
if (options.LogErrors)
|
||||
{
|
||||
_logger.ErrorException("Error " + webException.Status + " getting response from " + options.Url, webException);
|
||||
}
|
||||
|
||||
var exception = new HttpException(webException.Message, webException);
|
||||
|
||||
var response = webException.Response as HttpWebResponse;
|
||||
if (response != null)
|
||||
{
|
||||
exception.StatusCode = response.StatusCode;
|
||||
|
||||
if ((int)response.StatusCode == 429)
|
||||
{
|
||||
client.LastTimeout = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
if (!exception.StatusCode.HasValue)
|
||||
{
|
||||
if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
|
||||
webException.Status == WebExceptionStatus.ConnectFailure)
|
||||
{
|
||||
exception.IsTimedOut = true;
|
||||
}
|
||||
}
|
||||
|
||||
return exception;
|
||||
}
|
||||
|
||||
var operationCanceledException = ex as OperationCanceledException
|
||||
?? ex.InnerException as OperationCanceledException;
|
||||
|
||||
if (operationCanceledException != null)
|
||||
{
|
||||
return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
|
||||
}
|
||||
|
||||
if (options.LogErrors)
|
||||
{
|
||||
_logger.ErrorException("Error getting response from " + options.Url, ex);
|
||||
}
|
||||
|
||||
return ex;
|
||||
}
|
||||
|
||||
private void DeleteTempFile(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
_fileSystem.DeleteFile(file);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Might not have been created at all. No need to worry.
|
||||
}
|
||||
}
|
||||
|
||||
private void ValidateParams(HttpRequestOptions options)
|
||||
{
|
||||
if (string.IsNullOrEmpty(options.Url))
|
||||
{
|
||||
throw new ArgumentNullException("options");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the host from URL.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
private string GetHostFromUrl(string url)
|
||||
{
|
||||
var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (index != -1)
|
||||
{
|
||||
url = url.Substring(index + 3);
|
||||
var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(host))
|
||||
{
|
||||
return host;
|
||||
}
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged and - optionally - managed resources.
|
||||
/// </summary>
|
||||
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
|
||||
protected virtual void Dispose(bool dispose)
|
||||
{
|
||||
if (dispose)
|
||||
{
|
||||
_httpClients.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Throws the cancellation exception.
|
||||
/// </summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <param name="client">The client.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <param name="exception">The exception.</param>
|
||||
/// <returns>Exception.</returns>
|
||||
private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
|
||||
{
|
||||
// If the HttpClient's timeout is reached, it will cancel the Task internally
|
||||
if (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
var msg = string.Format("Connection to {0} timed out", options.Url);
|
||||
|
||||
if (options.LogErrors)
|
||||
{
|
||||
_logger.Error(msg);
|
||||
}
|
||||
|
||||
client.LastTimeout = DateTime.UtcNow;
|
||||
|
||||
// Throw an HttpException so that the caller doesn't think it was cancelled by user code
|
||||
return new HttpException(msg, exception)
|
||||
{
|
||||
IsTimedOut = true
|
||||
};
|
||||
}
|
||||
|
||||
return exception;
|
||||
}
|
||||
|
||||
private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
|
||||
{
|
||||
var statusCode = response.StatusCode;
|
||||
|
||||
var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
|
||||
|
||||
if (!isSuccessful)
|
||||
{
|
||||
if (options.LogErrorResponseBody)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var stream = response.GetResponseStream())
|
||||
{
|
||||
if (stream != null)
|
||||
{
|
||||
using (var reader = new StreamReader(stream))
|
||||
{
|
||||
var msg = reader.ReadToEnd();
|
||||
|
||||
_logger.Error(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
throw new HttpException(response.StatusDescription)
|
||||
{
|
||||
StatusCode = response.StatusCode
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Posts the specified URL.
|
||||
/// </summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <param name="postData">The post data.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task{Stream}.</returns>
|
||||
public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
|
||||
{
|
||||
return Post(url, postData, null, cancellationToken);
|
||||
}
|
||||
|
||||
private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
|
||||
{
|
||||
var taskCompletion = new TaskCompletionSource<WebResponse>();
|
||||
|
||||
Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
|
||||
|
||||
ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
|
||||
var callback = new TaskCallback { taskCompletion = taskCompletion };
|
||||
asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
|
||||
|
||||
// Handle errors
|
||||
asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
|
||||
|
||||
return taskCompletion.Task;
|
||||
}
|
||||
|
||||
private static void TimeoutCallback(object state, bool timedOut)
|
||||
{
|
||||
if (timedOut)
|
||||
{
|
||||
WebRequest request = (WebRequest)state;
|
||||
if (state != null)
|
||||
{
|
||||
request.Abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class TaskCallback
|
||||
{
|
||||
public TaskCompletionSource<WebResponse> taskCompletion;
|
||||
|
||||
public void OnSuccess(Task<WebResponse> task)
|
||||
{
|
||||
taskCompletion.TrySetResult(task.Result);
|
||||
}
|
||||
|
||||
public void OnError(Task<WebResponse> task)
|
||||
{
|
||||
if (task.Exception != null)
|
||||
{
|
||||
taskCompletion.TrySetException(task.Exception);
|
||||
}
|
||||
else
|
||||
{
|
||||
taskCompletion.TrySetException(new List<Exception>());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ using System.IO;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading.Tasks;
|
||||
using Emby.Common.Implementations.Net;
|
||||
using Emby.Server.Implementations.HttpServer;
|
||||
using Emby.Server.Implementations.Net;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
|
||||
75
Emby.Server.Implementations/IO/IsoManager.cs
Normal file
75
Emby.Server.Implementations/IO/IsoManager.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace Emby.Server.Implementations.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// Class IsoManager
|
||||
/// </summary>
|
||||
public class IsoManager : IIsoManager
|
||||
{
|
||||
/// <summary>
|
||||
/// The _mounters
|
||||
/// </summary>
|
||||
private readonly List<IIsoMounter> _mounters = new List<IIsoMounter>();
|
||||
|
||||
/// <summary>
|
||||
/// Mounts the specified iso path.
|
||||
/// </summary>
|
||||
/// <param name="isoPath">The iso path.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>IsoMount.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">isoPath</exception>
|
||||
/// <exception cref="System.ArgumentException"></exception>
|
||||
public Task<IIsoMount> Mount(string isoPath, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(isoPath))
|
||||
{
|
||||
throw new ArgumentNullException("isoPath");
|
||||
}
|
||||
|
||||
var mounter = _mounters.FirstOrDefault(i => i.CanMount(isoPath));
|
||||
|
||||
if (mounter == null)
|
||||
{
|
||||
throw new ArgumentException(string.Format("No mounters are able to mount {0}", isoPath));
|
||||
}
|
||||
|
||||
return mounter.Mount(isoPath, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether this instance can mount the specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns><c>true</c> if this instance can mount the specified path; otherwise, <c>false</c>.</returns>
|
||||
public bool CanMount(string path)
|
||||
{
|
||||
return _mounters.Any(i => i.CanMount(path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the parts.
|
||||
/// </summary>
|
||||
/// <param name="mounters">The mounters.</param>
|
||||
public void AddParts(IEnumerable<IIsoMounter> mounters)
|
||||
{
|
||||
_mounters.AddRange(mounters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var mounter in _mounters)
|
||||
{
|
||||
mounter.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
332
Emby.Server.Implementations/IO/LnkShortcutHandler.cs
Normal file
332
Emby.Server.Implementations/IO/LnkShortcutHandler.cs
Normal file
@@ -0,0 +1,332 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.InteropServices.ComTypes;
|
||||
using System.Text;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace Emby.Server.Implementations.IO
|
||||
{
|
||||
public class LnkShortcutHandler :IShortcutHandler
|
||||
{
|
||||
public string Extension
|
||||
{
|
||||
get { return ".lnk"; }
|
||||
}
|
||||
|
||||
public string Resolve(string shortcutPath)
|
||||
{
|
||||
var link = new ShellLink();
|
||||
((IPersistFile)link).Load(shortcutPath, NativeMethods.STGM_READ);
|
||||
// ((IShellLinkW)link).Resolve(hwnd, 0)
|
||||
var sb = new StringBuilder(NativeMethods.MAX_PATH);
|
||||
WIN32_FIND_DATA data;
|
||||
((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public void Create(string shortcutPath, string targetPath)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Class NativeMethods
|
||||
/// </summary>
|
||||
public static class NativeMethods
|
||||
{
|
||||
/// <summary>
|
||||
/// The MA x_ PATH
|
||||
/// </summary>
|
||||
public const int MAX_PATH = 260;
|
||||
/// <summary>
|
||||
/// The MA x_ ALTERNATE
|
||||
/// </summary>
|
||||
public const int MAX_ALTERNATE = 14;
|
||||
/// <summary>
|
||||
/// The INVALI d_ HANDL e_ VALUE
|
||||
/// </summary>
|
||||
public static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
|
||||
/// <summary>
|
||||
/// The STG m_ READ
|
||||
/// </summary>
|
||||
public const int STGM_READ = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Struct FILETIME
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct FILETIME
|
||||
{
|
||||
/// <summary>
|
||||
/// The dw low date time
|
||||
/// </summary>
|
||||
public uint dwLowDateTime;
|
||||
/// <summary>
|
||||
/// The dw high date time
|
||||
/// </summary>
|
||||
public uint dwHighDateTime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Struct WIN32_FIND_DATA
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct WIN32_FIND_DATA
|
||||
{
|
||||
/// <summary>
|
||||
/// The dw file attributes
|
||||
/// </summary>
|
||||
public FileAttributes dwFileAttributes;
|
||||
/// <summary>
|
||||
/// The ft creation time
|
||||
/// </summary>
|
||||
public FILETIME ftCreationTime;
|
||||
/// <summary>
|
||||
/// The ft last access time
|
||||
/// </summary>
|
||||
public FILETIME ftLastAccessTime;
|
||||
/// <summary>
|
||||
/// The ft last write time
|
||||
/// </summary>
|
||||
public FILETIME ftLastWriteTime;
|
||||
/// <summary>
|
||||
/// The n file size high
|
||||
/// </summary>
|
||||
public int nFileSizeHigh;
|
||||
/// <summary>
|
||||
/// The n file size low
|
||||
/// </summary>
|
||||
public int nFileSizeLow;
|
||||
/// <summary>
|
||||
/// The dw reserved0
|
||||
/// </summary>
|
||||
public int dwReserved0;
|
||||
/// <summary>
|
||||
/// The dw reserved1
|
||||
/// </summary>
|
||||
public int dwReserved1;
|
||||
|
||||
/// <summary>
|
||||
/// The c file name
|
||||
/// </summary>
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MAX_PATH)]
|
||||
public string cFileName;
|
||||
|
||||
/// <summary>
|
||||
/// This will always be null when FINDEX_INFO_LEVELS = basic
|
||||
/// </summary>
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MAX_ALTERNATE)]
|
||||
public string cAlternate;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path.
|
||||
/// </summary>
|
||||
/// <value>The path.</value>
|
||||
public string Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns a <see cref="System.String" /> that represents this instance.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
|
||||
public override string ToString()
|
||||
{
|
||||
return Path ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum SLGP_FLAGS
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum SLGP_FLAGS
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves the standard short (8.3 format) file name
|
||||
/// </summary>
|
||||
SLGP_SHORTPATH = 0x1,
|
||||
/// <summary>
|
||||
/// Retrieves the Universal Naming Convention (UNC) path name of the file
|
||||
/// </summary>
|
||||
SLGP_UNCPRIORITY = 0x2,
|
||||
/// <summary>
|
||||
/// Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded
|
||||
/// </summary>
|
||||
SLGP_RAWPATH = 0x4
|
||||
}
|
||||
/// <summary>
|
||||
/// Enum SLR_FLAGS
|
||||
/// </summary>
|
||||
[Flags]
|
||||
public enum SLR_FLAGS
|
||||
{
|
||||
/// <summary>
|
||||
/// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
|
||||
/// the high-order word of fFlags can be set to a time-out value that specifies the
|
||||
/// maximum amount of time to be spent resolving the link. The function returns if the
|
||||
/// link cannot be resolved within the time-out duration. If the high-order word is set
|
||||
/// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
|
||||
/// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
|
||||
/// duration, in milliseconds.
|
||||
/// </summary>
|
||||
SLR_NO_UI = 0x1,
|
||||
/// <summary>
|
||||
/// Obsolete and no longer used
|
||||
/// </summary>
|
||||
SLR_ANY_MATCH = 0x2,
|
||||
/// <summary>
|
||||
/// If the link object has changed, update its path and list of identifiers.
|
||||
/// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
|
||||
/// whether or not the link object has changed.
|
||||
/// </summary>
|
||||
SLR_UPDATE = 0x4,
|
||||
/// <summary>
|
||||
/// Do not update the link information
|
||||
/// </summary>
|
||||
SLR_NOUPDATE = 0x8,
|
||||
/// <summary>
|
||||
/// Do not execute the search heuristics
|
||||
/// </summary>
|
||||
SLR_NOSEARCH = 0x10,
|
||||
/// <summary>
|
||||
/// Do not use distributed link tracking
|
||||
/// </summary>
|
||||
SLR_NOTRACK = 0x20,
|
||||
/// <summary>
|
||||
/// Disable distributed link tracking. By default, distributed link tracking tracks
|
||||
/// removable media across multiple devices based on the volume name. It also uses the
|
||||
/// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
|
||||
/// has changed. Setting SLR_NOLINKINFO disables both types of tracking.
|
||||
/// </summary>
|
||||
SLR_NOLINKINFO = 0x40,
|
||||
/// <summary>
|
||||
/// Call the Microsoft Windows Installer
|
||||
/// </summary>
|
||||
SLR_INVOKE_MSI = 0x80
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The IShellLink interface allows Shell links to be created, modified, and resolved
|
||||
/// </summary>
|
||||
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
|
||||
public interface IShellLinkW
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieves the path and file name of a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszFile">The PSZ file.</param>
|
||||
/// <param name="cchMaxPath">The CCH max path.</param>
|
||||
/// <param name="pfd">The PFD.</param>
|
||||
/// <param name="fFlags">The f flags.</param>
|
||||
void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATA pfd, SLGP_FLAGS fFlags);
|
||||
/// <summary>
|
||||
/// Retrieves the list of item identifiers for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="ppidl">The ppidl.</param>
|
||||
void GetIDList(out IntPtr ppidl);
|
||||
/// <summary>
|
||||
/// Sets the pointer to an item identifier list (PIDL) for a Shell link object.
|
||||
/// </summary>
|
||||
/// <param name="pidl">The pidl.</param>
|
||||
void SetIDList(IntPtr pidl);
|
||||
/// <summary>
|
||||
/// Retrieves the description string for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszName">Name of the PSZ.</param>
|
||||
/// <param name="cchMaxName">Name of the CCH max.</param>
|
||||
void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
|
||||
/// <summary>
|
||||
/// Sets the description for a Shell link object. The description can be any application-defined string
|
||||
/// </summary>
|
||||
/// <param name="pszName">Name of the PSZ.</param>
|
||||
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
|
||||
/// <summary>
|
||||
/// Retrieves the name of the working directory for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszDir">The PSZ dir.</param>
|
||||
/// <param name="cchMaxPath">The CCH max path.</param>
|
||||
void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
|
||||
/// <summary>
|
||||
/// Sets the name of the working directory for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszDir">The PSZ dir.</param>
|
||||
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
|
||||
/// <summary>
|
||||
/// Retrieves the command-line arguments associated with a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszArgs">The PSZ args.</param>
|
||||
/// <param name="cchMaxPath">The CCH max path.</param>
|
||||
void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
|
||||
/// <summary>
|
||||
/// Sets the command-line arguments for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszArgs">The PSZ args.</param>
|
||||
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
|
||||
/// <summary>
|
||||
/// Retrieves the hot key for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pwHotkey">The pw hotkey.</param>
|
||||
void GetHotkey(out short pwHotkey);
|
||||
/// <summary>
|
||||
/// Sets a hot key for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="wHotkey">The w hotkey.</param>
|
||||
void SetHotkey(short wHotkey);
|
||||
/// <summary>
|
||||
/// Retrieves the show command for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="piShowCmd">The pi show CMD.</param>
|
||||
void GetShowCmd(out int piShowCmd);
|
||||
/// <summary>
|
||||
/// Sets the show command for a Shell link object. The show command sets the initial show state of the window.
|
||||
/// </summary>
|
||||
/// <param name="iShowCmd">The i show CMD.</param>
|
||||
void SetShowCmd(int iShowCmd);
|
||||
/// <summary>
|
||||
/// Retrieves the location (path and index) of the icon for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszIconPath">The PSZ icon path.</param>
|
||||
/// <param name="cchIconPath">The CCH icon path.</param>
|
||||
/// <param name="piIcon">The pi icon.</param>
|
||||
void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
|
||||
int cchIconPath, out int piIcon);
|
||||
/// <summary>
|
||||
/// Sets the location (path and index) of the icon for a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszIconPath">The PSZ icon path.</param>
|
||||
/// <param name="iIcon">The i icon.</param>
|
||||
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
|
||||
/// <summary>
|
||||
/// Sets the relative path to the Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszPathRel">The PSZ path rel.</param>
|
||||
/// <param name="dwReserved">The dw reserved.</param>
|
||||
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
|
||||
/// <summary>
|
||||
/// Attempts to find the target of a Shell link, even if it has been moved or renamed
|
||||
/// </summary>
|
||||
/// <param name="hwnd">The HWND.</param>
|
||||
/// <param name="fFlags">The f flags.</param>
|
||||
void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
|
||||
/// <summary>
|
||||
/// Sets the path and file name of a Shell link object
|
||||
/// </summary>
|
||||
/// <param name="pszFile">The PSZ file.</param>
|
||||
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
|
||||
|
||||
}
|
||||
|
||||
// CLSID_ShellLink from ShlGuid.h
|
||||
/// <summary>
|
||||
/// Class ShellLink
|
||||
/// </summary>
|
||||
[
|
||||
ComImport,
|
||||
Guid("00021401-0000-0000-C000-000000000046")
|
||||
]
|
||||
public class ShellLink
|
||||
{
|
||||
}
|
||||
}
|
||||
1057
Emby.Server.Implementations/IO/ManagedFileSystem.cs
Normal file
1057
Emby.Server.Implementations/IO/ManagedFileSystem.cs
Normal file
File diff suppressed because it is too large
Load Diff
240
Emby.Server.Implementations/IO/ProgressStream.cs
Normal file
240
Emby.Server.Implementations/IO/ProgressStream.cs
Normal file
@@ -0,0 +1,240 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Emby.Server.Implementations.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// Measures progress when reading from a stream or writing to one
|
||||
/// </summary>
|
||||
public class ProgressStream : Stream
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the base stream.
|
||||
/// </summary>
|
||||
/// <value>The base stream.</value>
|
||||
public Stream BaseStream { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bytes processed.
|
||||
/// </summary>
|
||||
/// <value>The bytes processed.</value>
|
||||
private long BytesProcessed { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the length of the write.
|
||||
/// </summary>
|
||||
/// <value>The length of the write.</value>
|
||||
private long WriteLength { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the length of the read.
|
||||
/// </summary>
|
||||
/// <value>The length of the read.</value>
|
||||
private long? ReadLength { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the progress action.
|
||||
/// </summary>
|
||||
/// <value>The progress action.</value>
|
||||
private Action<double> ProgressAction { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates the read progress stream.
|
||||
/// </summary>
|
||||
/// <param name="baseStream">The base stream.</param>
|
||||
/// <param name="progressAction">The progress action.</param>
|
||||
/// <param name="readLength">Length of the read.</param>
|
||||
/// <returns>ProgressStream.</returns>
|
||||
public static ProgressStream CreateReadProgressStream(Stream baseStream, Action<double> progressAction, long? readLength = null)
|
||||
{
|
||||
return new ProgressStream
|
||||
{
|
||||
BaseStream = baseStream,
|
||||
ProgressAction = progressAction,
|
||||
ReadLength = readLength
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the write progress stream.
|
||||
/// </summary>
|
||||
/// <param name="baseStream">The base stream.</param>
|
||||
/// <param name="progressAction">The progress action.</param>
|
||||
/// <param name="writeLength">Length of the write.</param>
|
||||
/// <returns>ProgressStream.</returns>
|
||||
public static ProgressStream CreateWriteProgressStream(Stream baseStream, Action<double> progressAction, long writeLength)
|
||||
{
|
||||
return new ProgressStream
|
||||
{
|
||||
BaseStream = baseStream,
|
||||
ProgressAction = progressAction,
|
||||
WriteLength = writeLength
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance can read; otherwise, <c>false</c>.</value>
|
||||
/// <returns>true if the stream supports reading; otherwise, false.</returns>
|
||||
public override bool CanRead
|
||||
{
|
||||
get { return BaseStream.CanRead; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance can seek; otherwise, <c>false</c>.</value>
|
||||
/// <returns>true if the stream supports seeking; otherwise, false.</returns>
|
||||
public override bool CanSeek
|
||||
{
|
||||
get { return BaseStream.CanSeek; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
|
||||
/// </summary>
|
||||
/// <value><c>true</c> if this instance can write; otherwise, <c>false</c>.</value>
|
||||
/// <returns>true if the stream supports writing; otherwise, false.</returns>
|
||||
public override bool CanWrite
|
||||
{
|
||||
get { return BaseStream.CanWrite; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
|
||||
/// </summary>
|
||||
public override void Flush()
|
||||
{
|
||||
BaseStream.Flush();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, gets the length in bytes of the stream.
|
||||
/// </summary>
|
||||
/// <value>The length.</value>
|
||||
/// <returns>A long value representing the length of the stream in bytes.</returns>
|
||||
public override long Length
|
||||
{
|
||||
get { return BaseStream.Length; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, gets or sets the position within the current stream.
|
||||
/// </summary>
|
||||
/// <value>The position.</value>
|
||||
/// <returns>The current position within the stream.</returns>
|
||||
public override long Position
|
||||
{
|
||||
get { return BaseStream.Position; }
|
||||
set
|
||||
{
|
||||
BaseStream.Position = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
|
||||
/// </summary>
|
||||
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.</param>
|
||||
/// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param>
|
||||
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
|
||||
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
var read = BaseStream.Read(buffer, offset, count);
|
||||
|
||||
BytesProcessed += read;
|
||||
|
||||
double percent = BytesProcessed;
|
||||
percent /= ReadLength ?? BaseStream.Length;
|
||||
percent *= 100;
|
||||
|
||||
ProgressAction(percent);
|
||||
|
||||
return read;
|
||||
}
|
||||
|
||||
public override int EndRead(IAsyncResult asyncResult)
|
||||
{
|
||||
var read = base.EndRead(asyncResult);
|
||||
|
||||
BytesProcessed += read;
|
||||
|
||||
double percent = BytesProcessed;
|
||||
percent /= ReadLength ?? BaseStream.Length;
|
||||
percent *= 100;
|
||||
|
||||
ProgressAction(percent);
|
||||
|
||||
return read;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, sets the position within the current stream.
|
||||
/// </summary>
|
||||
/// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param>
|
||||
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param>
|
||||
/// <returns>The new position within the current stream.</returns>
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
return BaseStream.Seek(offset, origin);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, sets the length of the current stream.
|
||||
/// </summary>
|
||||
/// <param name="value">The desired length of the current stream in bytes.</param>
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
BaseStream.SetLength(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
|
||||
/// </summary>
|
||||
/// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param>
|
||||
/// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param>
|
||||
/// <param name="count">The number of bytes to be written to the current stream.</param>
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
BaseStream.Write(buffer, offset, count);
|
||||
|
||||
BytesProcessed += count;
|
||||
|
||||
double percent = BytesProcessed;
|
||||
percent /= WriteLength;
|
||||
percent *= 100;
|
||||
|
||||
ProgressAction(percent);
|
||||
}
|
||||
|
||||
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
|
||||
{
|
||||
var result = base.BeginWrite(buffer, offset, count, callback, state);
|
||||
|
||||
BytesProcessed += count;
|
||||
|
||||
double percent = BytesProcessed;
|
||||
percent /= WriteLength;
|
||||
percent *= 100;
|
||||
|
||||
ProgressAction(percent);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.
|
||||
/// </summary>
|
||||
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
BaseStream.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
409
Emby.Server.Implementations/IO/SharpCifs/Config.cs
Normal file
409
Emby.Server.Implementations/IO/SharpCifs/Config.cs
Normal file
@@ -0,0 +1,409 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Security;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs
|
||||
{
|
||||
/// <summary>
|
||||
/// This class uses a static
|
||||
/// <see cref="Properties">Sharpen.Properties</see>
|
||||
/// to act
|
||||
/// as a cental repository for all jCIFS configuration properties. It cannot be
|
||||
/// instantiated. Similar to <code>System</code> properties the namespace
|
||||
/// is global therefore property names should be unique. Before use,
|
||||
/// the <code>load</code> method should be called with the name of a
|
||||
/// <code>Properties</code> file (or <code>null</code> indicating no
|
||||
/// file) to initialize the <code>Config</code>. The <code>System</code>
|
||||
/// properties will then populate the <code>Config</code> as well potentially
|
||||
/// overwriting properties from the file. Thus properties provided on the
|
||||
/// commandline with the <code>-Dproperty.name=value</code> VM parameter
|
||||
/// will override properties from the configuration file.
|
||||
///
|
||||
/// There are several ways to set jCIFS properties. See
|
||||
/// the <a href="../overview-summary.html#scp">overview page of the API
|
||||
/// documentation</a> for details.
|
||||
/// </summary>
|
||||
public class Config
|
||||
{
|
||||
|
||||
/// <summary>The static <code>Properties</code>.</summary>
|
||||
/// <remarks>The static <code>Properties</code>.</remarks>
|
||||
private static Properties _prp = new Properties();
|
||||
|
||||
private static LogStream _log;
|
||||
|
||||
public static string DefaultOemEncoding = "UTF-8"; //"Cp850";
|
||||
|
||||
static Config()
|
||||
{
|
||||
int level;
|
||||
FileInputStream fis = null;
|
||||
_log = LogStream.GetInstance();
|
||||
|
||||
try
|
||||
{
|
||||
string filename = Runtime.GetProperty("jcifs.properties");
|
||||
if (filename != null && filename.Length > 1)
|
||||
{
|
||||
fis = new FileInputStream(filename);
|
||||
}
|
||||
Load(fis);
|
||||
if (fis != null)
|
||||
{
|
||||
fis.Close();
|
||||
}
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
}
|
||||
|
||||
if ((level = GetInt("jcifs.util.loglevel", -1)) != -1)
|
||||
{
|
||||
_log.SetLevel(level);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Runtime.GetBytesForString(string.Empty, DefaultOemEncoding);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_log.Level >= 2)
|
||||
{
|
||||
_log.WriteLine("WARNING: The default OEM encoding " + DefaultOemEncoding + " does not appear to be supported by this JRE. The default encoding will be US-ASCII."
|
||||
);
|
||||
}
|
||||
|
||||
//DEFAULT_OEM_ENCODING = "US-ASCII";
|
||||
}
|
||||
|
||||
if (_log.Level >= 4)
|
||||
{
|
||||
try
|
||||
{
|
||||
_prp.Store(_log);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This static method registers the SMB URL protocol handler which is
|
||||
/// required to use SMB URLs with the <tt>java.net.URL</tt> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This static method registers the SMB URL protocol handler which is
|
||||
/// required to use SMB URLs with the <tt>java.net.URL</tt> class. If this
|
||||
/// method is not called before attempting to create an SMB URL with the
|
||||
/// URL class the following exception will occur:
|
||||
/// <blockquote><pre>
|
||||
/// Exception MalformedURLException: unknown protocol: smb
|
||||
/// at java.net.URL.<init>(URL.java:480)
|
||||
/// at java.net.URL.<init>(URL.java:376)
|
||||
/// at java.net.URL.<init>(URL.java:330)
|
||||
/// at jcifs.smb.SmbFile.<init>(SmbFile.java:355)
|
||||
/// ...
|
||||
/// </pre><blockquote>
|
||||
/// </remarks>
|
||||
public static void RegisterSmbURLHandler()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
// supress javadoc constructor summary by removing 'protected'
|
||||
/// <summary>Set the default properties of the static Properties used by <tt>Config</tt>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Set the default properties of the static Properties used by <tt>Config</tt>. This permits
|
||||
/// a different Properties object/file to be used as the source of properties for
|
||||
/// use by the jCIFS library. The Properties must be set <i>before jCIFS
|
||||
/// classes are accessed</i> as most jCIFS classes load properties statically once.
|
||||
/// Using this method will also override properties loaded
|
||||
/// using the <tt>-Djcifs.properties=</tt> commandline parameter.
|
||||
/// </remarks>
|
||||
public static void SetProperties(Properties prp)
|
||||
{
|
||||
Config._prp = new Properties(prp);
|
||||
try
|
||||
{
|
||||
Config._prp.PutAll(Runtime.GetProperties());
|
||||
}
|
||||
catch (SecurityException)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
_log.WriteLine("SecurityException: jcifs will ignore System properties");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Load the <code>Config</code> with properties from the stream
|
||||
/// <code>in</code> from a <code>Properties</code> file.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Load the <code>Config</code> with properties from the stream
|
||||
/// <code>in</code> from a <code>Properties</code> file.
|
||||
/// </remarks>
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public static void Load(InputStream input)
|
||||
{
|
||||
if (input != null)
|
||||
{
|
||||
_prp.Load(input);
|
||||
}
|
||||
try
|
||||
{
|
||||
_prp.PutAll(Runtime.GetProperties());
|
||||
}
|
||||
catch (SecurityException)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
_log.WriteLine("SecurityException: jcifs will ignore System properties");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public static void Store(OutputStream output, string header)
|
||||
{
|
||||
_prp.Store(output);
|
||||
}
|
||||
|
||||
/// <summary>Add a property.</summary>
|
||||
/// <remarks>Add a property.</remarks>
|
||||
public static void SetProperty(string key, string value)
|
||||
{
|
||||
_prp.SetProperty(key, value);
|
||||
}
|
||||
|
||||
/// <summary>Retrieve a property as an <code>Object</code>.</summary>
|
||||
/// <remarks>Retrieve a property as an <code>Object</code>.</remarks>
|
||||
public static object Get(string key)
|
||||
{
|
||||
return _prp.GetProperty(key);
|
||||
}
|
||||
|
||||
/// <summary>Retrieve a <code>String</code>.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve a <code>String</code>. If the key cannot be found,
|
||||
/// the provided <code>def</code> default parameter will be returned.
|
||||
/// </remarks>
|
||||
public static string GetProperty(string key, string def)
|
||||
{
|
||||
return (string)_prp.GetProperty(key, def);
|
||||
}
|
||||
|
||||
/// <summary>Retrieve a <code>String</code>.</summary>
|
||||
/// <remarks>Retrieve a <code>String</code>. If the property is not found, <code>null</code> is returned.
|
||||
/// </remarks>
|
||||
public static string GetProperty(string key)
|
||||
{
|
||||
return (string)_prp.GetProperty(key);
|
||||
}
|
||||
|
||||
/// <summary>Retrieve an <code>int</code>.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve an <code>int</code>. If the key does not exist or
|
||||
/// cannot be converted to an <code>int</code>, the provided default
|
||||
/// argument will be returned.
|
||||
/// </remarks>
|
||||
public static int GetInt(string key, int def)
|
||||
{
|
||||
string s = (string)_prp.GetProperty(key);
|
||||
if (s != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
def = Convert.ToInt32(s);
|
||||
}
|
||||
catch (FormatException nfe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(nfe, _log);
|
||||
}
|
||||
}
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
/// <summary>Retrieve an <code>int</code>.</summary>
|
||||
/// <remarks>Retrieve an <code>int</code>. If the property is not found, <code>-1</code> is returned.
|
||||
/// </remarks>
|
||||
public static int GetInt(string key)
|
||||
{
|
||||
string s = (string)_prp.GetProperty(key);
|
||||
int result = -1;
|
||||
if (s != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
result = Convert.ToInt32(s);
|
||||
}
|
||||
catch (FormatException nfe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(nfe, _log);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Retrieve a <code>long</code>.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve a <code>long</code>. If the key does not exist or
|
||||
/// cannot be converted to a <code>long</code>, the provided default
|
||||
/// argument will be returned.
|
||||
/// </remarks>
|
||||
public static long GetLong(string key, long def)
|
||||
{
|
||||
string s = (string)_prp.GetProperty(key);
|
||||
if (s != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
def = long.Parse(s);
|
||||
}
|
||||
catch (FormatException nfe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(nfe, _log);
|
||||
}
|
||||
}
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
/// <summary>Retrieve an <code>InetAddress</code>.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve an <code>InetAddress</code>. If the address is not
|
||||
/// an IP address and cannot be resolved <code>null</code> will
|
||||
/// be returned.
|
||||
/// </remarks>
|
||||
public static IPAddress GetInetAddress(string key, IPAddress def)
|
||||
{
|
||||
string addr = (string)_prp.GetProperty(key);
|
||||
if (addr != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
def = Extensions.GetAddressByName(addr);
|
||||
}
|
||||
catch (UnknownHostException uhe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
_log.WriteLine(addr);
|
||||
Runtime.PrintStackTrace(uhe, _log);
|
||||
}
|
||||
}
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
public static IPAddress GetLocalHost()
|
||||
{
|
||||
string addr = (string)_prp.GetProperty("jcifs.smb.client.laddr");
|
||||
if (addr != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Extensions.GetAddressByName(addr);
|
||||
}
|
||||
catch (UnknownHostException uhe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
_log.WriteLine("Ignoring jcifs.smb.client.laddr address: " + addr);
|
||||
Runtime.PrintStackTrace(uhe, _log);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Retrieve a boolean value.</summary>
|
||||
/// <remarks>Retrieve a boolean value. If the property is not found, the value of <code>def</code> is returned.
|
||||
/// </remarks>
|
||||
public static bool GetBoolean(string key, bool def)
|
||||
{
|
||||
string b = GetProperty(key);
|
||||
if (b != null)
|
||||
{
|
||||
def = b.ToLower().Equals("true");
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve an array of <tt>InetAddress</tt> created from a property
|
||||
/// value containting a <tt>delim</tt> separated list of hostnames and/or
|
||||
/// ipaddresses.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Retrieve an array of <tt>InetAddress</tt> created from a property
|
||||
/// value containting a <tt>delim</tt> separated list of hostnames and/or
|
||||
/// ipaddresses.
|
||||
/// </remarks>
|
||||
public static IPAddress[] GetInetAddressArray(string key, string delim, IPAddress
|
||||
[] def)
|
||||
{
|
||||
string p = GetProperty(key);
|
||||
if (p != null)
|
||||
{
|
||||
StringTokenizer tok = new StringTokenizer(p, delim);
|
||||
int len = tok.CountTokens();
|
||||
IPAddress[] arr = new IPAddress[len];
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
string addr = tok.NextToken();
|
||||
try
|
||||
{
|
||||
arr[i] = Extensions.GetAddressByName(addr);
|
||||
}
|
||||
catch (UnknownHostException uhe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
_log.WriteLine(addr);
|
||||
Runtime.PrintStackTrace(uhe, _log);
|
||||
}
|
||||
return def;
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
return def;
|
||||
}
|
||||
}
|
||||
}
|
||||
102
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs
Normal file
102
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBind.cs
Normal file
@@ -0,0 +1,102 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
using SharpCifs.Util;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public class DcerpcBind : DcerpcMessage
|
||||
{
|
||||
internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED"
|
||||
, "DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED", "DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
|
||||
};
|
||||
|
||||
internal static string GetResultMessage(int result)
|
||||
{
|
||||
return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4
|
||||
);
|
||||
}
|
||||
|
||||
public override DcerpcException GetResult()
|
||||
{
|
||||
if (Result != 0)
|
||||
{
|
||||
return new DcerpcException(GetResultMessage(Result));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal DcerpcBinding Binding;
|
||||
|
||||
internal int MaxXmit;
|
||||
|
||||
internal int MaxRecv;
|
||||
|
||||
public DcerpcBind()
|
||||
{
|
||||
}
|
||||
|
||||
internal DcerpcBind(DcerpcBinding binding, DcerpcHandle handle)
|
||||
{
|
||||
this.Binding = binding;
|
||||
MaxXmit = handle.MaxXmit;
|
||||
MaxRecv = handle.MaxRecv;
|
||||
Ptype = 11;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_short(MaxXmit);
|
||||
dst.Enc_ndr_short(MaxRecv);
|
||||
dst.Enc_ndr_long(0);
|
||||
dst.Enc_ndr_small(1);
|
||||
dst.Enc_ndr_small(0);
|
||||
dst.Enc_ndr_short(0);
|
||||
dst.Enc_ndr_short(0);
|
||||
dst.Enc_ndr_small(1);
|
||||
dst.Enc_ndr_small(0);
|
||||
Binding.Uuid.Encode(dst);
|
||||
dst.Enc_ndr_short(Binding.Major);
|
||||
dst.Enc_ndr_short(Binding.Minor);
|
||||
DcerpcConstants.DcerpcUuidSyntaxNdr.Encode(dst);
|
||||
dst.Enc_ndr_long(2);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
src.Dec_ndr_short();
|
||||
src.Dec_ndr_short();
|
||||
src.Dec_ndr_long();
|
||||
int n = src.Dec_ndr_short();
|
||||
src.Advance(n);
|
||||
src.Align(4);
|
||||
src.Dec_ndr_small();
|
||||
src.Align(4);
|
||||
Result = src.Dec_ndr_short();
|
||||
src.Dec_ndr_short();
|
||||
src.Advance(20);
|
||||
}
|
||||
}
|
||||
}
|
||||
122
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs
Normal file
122
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcBinding.cs
Normal file
@@ -0,0 +1,122 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Dcerpc.Msrpc;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public class DcerpcBinding
|
||||
{
|
||||
private static Hashtable _interfaces;
|
||||
|
||||
static DcerpcBinding()
|
||||
{
|
||||
_interfaces = new Hashtable();
|
||||
_interfaces.Put("srvsvc", Srvsvc.GetSyntax());
|
||||
_interfaces.Put("lsarpc", Lsarpc.GetSyntax());
|
||||
_interfaces.Put("samr", Samr.GetSyntax());
|
||||
_interfaces.Put("netdfs", Netdfs.GetSyntax());
|
||||
}
|
||||
|
||||
public static void AddInterface(string name, string syntax)
|
||||
{
|
||||
_interfaces.Put(name, syntax);
|
||||
}
|
||||
|
||||
internal string Proto;
|
||||
|
||||
internal string Server;
|
||||
|
||||
internal string Endpoint;
|
||||
|
||||
internal Hashtable Options;
|
||||
|
||||
internal Uuid Uuid;
|
||||
|
||||
internal int Major;
|
||||
|
||||
internal int Minor;
|
||||
|
||||
internal DcerpcBinding(string proto, string server)
|
||||
{
|
||||
this.Proto = proto;
|
||||
this.Server = server;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
internal virtual void SetOption(string key, object val)
|
||||
{
|
||||
if (key.Equals("endpoint"))
|
||||
{
|
||||
Endpoint = val.ToString().ToLower();
|
||||
if (Endpoint.StartsWith("\\pipe\\"))
|
||||
{
|
||||
string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6));
|
||||
if (iface != null)
|
||||
{
|
||||
int c;
|
||||
int p;
|
||||
c = iface.IndexOf(':');
|
||||
p = iface.IndexOf('.', c + 1);
|
||||
Uuid = new Uuid(Runtime.Substring(iface, 0, c));
|
||||
Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p));
|
||||
Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1));
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new DcerpcException("Bad endpoint: " + Endpoint);
|
||||
}
|
||||
if (Options == null)
|
||||
{
|
||||
Options = new Hashtable();
|
||||
}
|
||||
Options.Put(key, val);
|
||||
}
|
||||
|
||||
internal virtual object GetOption(string key)
|
||||
{
|
||||
if (key.Equals("endpoint"))
|
||||
{
|
||||
return Endpoint;
|
||||
}
|
||||
if (Options != null)
|
||||
{
|
||||
return Options.Get(key);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
/* string ret = proto + ":" + server + "[" + endpoint;
|
||||
if (options != null)
|
||||
{
|
||||
Iterator iter = (Iterator) options.Keys.GetEnumerator();
|
||||
while (iter.HasNext())
|
||||
{
|
||||
object key = iter.Next();
|
||||
object val = options.Get(key);
|
||||
ret += "," + key + "=" + val;
|
||||
}
|
||||
}
|
||||
ret += "]";
|
||||
return ret; */
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public static class DcerpcConstants
|
||||
{
|
||||
public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860"
|
||||
);
|
||||
|
||||
public static int DcerpcFirstFrag = unchecked(0x01);
|
||||
|
||||
public static int DcerpcLastFrag = unchecked(0x02);
|
||||
|
||||
public static int DcerpcPendingCancel = unchecked(0x04);
|
||||
|
||||
public static int DcerpcReserved1 = unchecked(0x08);
|
||||
|
||||
public static int DcerpcConcMpx = unchecked(0x10);
|
||||
|
||||
public static int DcerpcDidNotExecute = unchecked(0x20);
|
||||
|
||||
public static int DcerpcMaybe = unchecked(0x40);
|
||||
|
||||
public static int DcerpcObjectUuid = unchecked(0x80);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public static class DcerpcError
|
||||
{
|
||||
public static int DcerpcFaultOther = unchecked(0x00000001);
|
||||
|
||||
public static int DcerpcFaultAccessDenied = unchecked(0x00000005);
|
||||
|
||||
public static int DcerpcFaultCantPerform = unchecked(0x000006D8);
|
||||
|
||||
public static int DcerpcFaultNdr = unchecked(0x000006F7);
|
||||
|
||||
public static int DcerpcFaultInvalidTag = unchecked(0x1C000006);
|
||||
|
||||
public static int DcerpcFaultContextMismatch = unchecked(0x1C00001A);
|
||||
|
||||
public static int DcerpcFaultOpRngError = unchecked(0x1C010002);
|
||||
|
||||
public static int DcerpcFaultUnkIf = unchecked(0x1C010003);
|
||||
|
||||
public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
|
||||
|
||||
public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied
|
||||
, DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch
|
||||
, DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError };
|
||||
|
||||
public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER"
|
||||
, "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR",
|
||||
"DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR"
|
||||
, "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
|
||||
public class DcerpcException : IOException
|
||||
{
|
||||
internal static string GetMessageByDcerpcError(int errcode)
|
||||
{
|
||||
int min = 0;
|
||||
int max = DcerpcError.DcerpcFaultCodes.Length;
|
||||
while (max >= min)
|
||||
{
|
||||
int mid = (min + max) / 2;
|
||||
if (errcode > DcerpcError.DcerpcFaultCodes[mid])
|
||||
{
|
||||
min = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (errcode < DcerpcError.DcerpcFaultCodes[mid])
|
||||
{
|
||||
max = mid - 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
return DcerpcError.DcerpcFaultMessages[mid];
|
||||
}
|
||||
}
|
||||
}
|
||||
return "0x" + Hexdump.ToHexString(errcode, 8);
|
||||
}
|
||||
|
||||
private int _error;
|
||||
|
||||
private Exception _rootCause;
|
||||
|
||||
internal DcerpcException(int error) : base(GetMessageByDcerpcError(error))
|
||||
{
|
||||
this._error = error;
|
||||
}
|
||||
|
||||
public DcerpcException(string msg) : base(msg)
|
||||
{
|
||||
}
|
||||
|
||||
public DcerpcException(string msg, Exception rootCause) : base(msg)
|
||||
{
|
||||
this._rootCause = rootCause;
|
||||
}
|
||||
|
||||
public virtual int GetErrorCode()
|
||||
{
|
||||
return _error;
|
||||
}
|
||||
|
||||
public virtual Exception GetRootCause()
|
||||
{
|
||||
return _rootCause;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
if (_rootCause != null)
|
||||
{
|
||||
StringWriter sw = new StringWriter();
|
||||
PrintWriter pw = new PrintWriter(sw);
|
||||
Runtime.PrintStackTrace(_rootCause, pw);
|
||||
return base.ToString() + "\n" + sw;
|
||||
}
|
||||
return base.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
332
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs
Normal file
332
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcHandle.cs
Normal file
@@ -0,0 +1,332 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
using SharpCifs.Smb;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public abstract class DcerpcHandle
|
||||
{
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
protected internal static DcerpcBinding ParseBinding(string str)
|
||||
{
|
||||
int state;
|
||||
int mark;
|
||||
int si;
|
||||
char[] arr = str.ToCharArray();
|
||||
string proto = null;
|
||||
string key = null;
|
||||
DcerpcBinding binding = null;
|
||||
state = mark = si = 0;
|
||||
do
|
||||
{
|
||||
char ch = arr[si];
|
||||
switch (state)
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
if (ch == ':')
|
||||
{
|
||||
proto = Runtime.Substring(str, mark, si);
|
||||
mark = si + 1;
|
||||
state = 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 1:
|
||||
{
|
||||
if (ch == '\\')
|
||||
{
|
||||
mark = si + 1;
|
||||
break;
|
||||
}
|
||||
state = 2;
|
||||
goto case 2;
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
if (ch == '[')
|
||||
{
|
||||
string server = Runtime.Substring(str, mark, si).Trim();
|
||||
if (server.Length == 0)
|
||||
{
|
||||
server = "127.0.0.1";
|
||||
}
|
||||
binding = new DcerpcBinding(proto, Runtime.Substring(str, mark, si));
|
||||
mark = si + 1;
|
||||
state = 5;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 5:
|
||||
{
|
||||
if (ch == '=')
|
||||
{
|
||||
key = Runtime.Substring(str, mark, si).Trim();
|
||||
mark = si + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (ch == ',' || ch == ']')
|
||||
{
|
||||
string val = Runtime.Substring(str, mark, si).Trim();
|
||||
if (key == null)
|
||||
{
|
||||
key = "endpoint";
|
||||
}
|
||||
binding.SetOption(key, val);
|
||||
key = null;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
si = arr.Length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
si++;
|
||||
}
|
||||
while (si < arr.Length);
|
||||
if (binding == null || binding.Endpoint == null)
|
||||
{
|
||||
throw new DcerpcException("Invalid binding URL: " + str);
|
||||
}
|
||||
return binding;
|
||||
}
|
||||
|
||||
protected internal DcerpcBinding Binding;
|
||||
|
||||
protected internal int MaxXmit = 4280;
|
||||
|
||||
protected internal int MaxRecv;
|
||||
|
||||
protected internal int State;
|
||||
|
||||
protected internal IDcerpcSecurityProvider SecurityProvider;
|
||||
|
||||
private static int _callId = 1;
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
/// <exception cref="System.UriFormatException"></exception>
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
public static DcerpcHandle GetHandle(string url, NtlmPasswordAuthentication auth)
|
||||
{
|
||||
if (url.StartsWith("ncacn_np:"))
|
||||
{
|
||||
return new DcerpcPipeHandle(url, auth);
|
||||
}
|
||||
throw new DcerpcException("DCERPC transport not supported: " + url);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Bind()
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
try
|
||||
{
|
||||
State = 1;
|
||||
DcerpcMessage bind = new DcerpcBind(Binding, this);
|
||||
Sendrecv(bind);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
State = 0;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Sendrecv(DcerpcMessage msg)
|
||||
{
|
||||
byte[] stub;
|
||||
byte[] frag;
|
||||
NdrBuffer buf;
|
||||
NdrBuffer fbuf;
|
||||
bool isLast;
|
||||
bool isDirect;
|
||||
DcerpcException de;
|
||||
if (State == 0)
|
||||
{
|
||||
Bind();
|
||||
}
|
||||
isDirect = true;
|
||||
stub = BufferCache.GetBuffer();
|
||||
try
|
||||
{
|
||||
int off;
|
||||
int tot;
|
||||
int n;
|
||||
buf = new NdrBuffer(stub, 0);
|
||||
msg.Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
msg.CallId = _callId++;
|
||||
msg.Encode(buf);
|
||||
if (SecurityProvider != null)
|
||||
{
|
||||
buf.SetIndex(0);
|
||||
SecurityProvider.Wrap(buf);
|
||||
}
|
||||
tot = buf.GetLength() - 24;
|
||||
off = 0;
|
||||
while (off < tot)
|
||||
{
|
||||
n = tot - off;
|
||||
if ((24 + n) > MaxXmit)
|
||||
{
|
||||
msg.Flags &= ~DcerpcConstants.DcerpcLastFrag;
|
||||
n = MaxXmit - 24;
|
||||
}
|
||||
else
|
||||
{
|
||||
msg.Flags |= DcerpcConstants.DcerpcLastFrag;
|
||||
isDirect = false;
|
||||
msg.AllocHint = n;
|
||||
}
|
||||
msg.Length = 24 + n;
|
||||
if (off > 0)
|
||||
{
|
||||
msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag;
|
||||
}
|
||||
if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag |
|
||||
DcerpcConstants.DcerpcLastFrag))
|
||||
{
|
||||
buf.Start = off;
|
||||
buf.Reset();
|
||||
msg.Encode_header(buf);
|
||||
buf.Enc_ndr_long(msg.AllocHint);
|
||||
buf.Enc_ndr_short(0);
|
||||
buf.Enc_ndr_short(msg.GetOpnum());
|
||||
}
|
||||
DoSendFragment(stub, off, msg.Length, isDirect);
|
||||
off += n;
|
||||
}
|
||||
DoReceiveFragment(stub, isDirect);
|
||||
buf.Reset();
|
||||
buf.SetIndex(8);
|
||||
buf.SetLength(buf.Dec_ndr_short());
|
||||
if (SecurityProvider != null)
|
||||
{
|
||||
SecurityProvider.Unwrap(buf);
|
||||
}
|
||||
buf.SetIndex(0);
|
||||
msg.Decode_header(buf);
|
||||
off = 24;
|
||||
if (msg.Ptype == 2 && msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
|
||||
{
|
||||
off = msg.Length;
|
||||
}
|
||||
frag = null;
|
||||
fbuf = null;
|
||||
while (msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
|
||||
{
|
||||
int stubFragLen;
|
||||
if (frag == null)
|
||||
{
|
||||
frag = new byte[MaxRecv];
|
||||
fbuf = new NdrBuffer(frag, 0);
|
||||
}
|
||||
DoReceiveFragment(frag, isDirect);
|
||||
fbuf.Reset();
|
||||
fbuf.SetIndex(8);
|
||||
fbuf.SetLength(fbuf.Dec_ndr_short());
|
||||
if (SecurityProvider != null)
|
||||
{
|
||||
SecurityProvider.Unwrap(fbuf);
|
||||
}
|
||||
fbuf.Reset();
|
||||
msg.Decode_header(fbuf);
|
||||
stubFragLen = msg.Length - 24;
|
||||
if ((off + stubFragLen) > stub.Length)
|
||||
{
|
||||
// shouldn't happen if alloc_hint is correct or greater
|
||||
byte[] tmp = new byte[off + stubFragLen];
|
||||
Array.Copy(stub, 0, tmp, 0, off);
|
||||
stub = tmp;
|
||||
}
|
||||
Array.Copy(frag, 24, stub, off, stubFragLen);
|
||||
off += stubFragLen;
|
||||
}
|
||||
buf = new NdrBuffer(stub, 0);
|
||||
msg.Decode(buf);
|
||||
}
|
||||
finally
|
||||
{
|
||||
BufferCache.ReleaseBuffer(stub);
|
||||
}
|
||||
if ((de = msg.GetResult()) != null)
|
||||
{
|
||||
throw de;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void SetDcerpcSecurityProvider(IDcerpcSecurityProvider securityProvider
|
||||
)
|
||||
{
|
||||
this.SecurityProvider = securityProvider;
|
||||
}
|
||||
|
||||
public virtual string GetServer()
|
||||
{
|
||||
if (this is DcerpcPipeHandle)
|
||||
{
|
||||
return ((DcerpcPipeHandle)this).Pipe.GetServer();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public virtual Principal GetPrincipal()
|
||||
{
|
||||
if (this is DcerpcPipeHandle)
|
||||
{
|
||||
return ((DcerpcPipeHandle)this).Pipe.GetPrincipal();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Binding.ToString();
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
protected internal abstract void DoSendFragment(byte[] buf, int off, int length,
|
||||
bool isDirect);
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect);
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public abstract void Close();
|
||||
|
||||
public DcerpcHandle()
|
||||
{
|
||||
MaxRecv = MaxXmit;
|
||||
}
|
||||
}
|
||||
}
|
||||
150
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs
Normal file
150
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/DcerpcMessage.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public abstract class DcerpcMessage : NdrObject
|
||||
{
|
||||
protected internal int Ptype = -1;
|
||||
|
||||
protected internal int Flags;
|
||||
|
||||
protected internal int Length;
|
||||
|
||||
protected internal int CallId;
|
||||
|
||||
protected internal int AllocHint;
|
||||
|
||||
protected internal int Result;
|
||||
|
||||
public virtual bool IsFlagSet(int flag)
|
||||
{
|
||||
return (Flags & flag) == flag;
|
||||
}
|
||||
|
||||
public virtual void UnsetFlag(int flag)
|
||||
{
|
||||
Flags &= ~flag;
|
||||
}
|
||||
|
||||
public virtual void SetFlag(int flag)
|
||||
{
|
||||
Flags |= flag;
|
||||
}
|
||||
|
||||
public virtual DcerpcException GetResult()
|
||||
{
|
||||
if (Result != 0)
|
||||
{
|
||||
return new DcerpcException(Result);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal virtual void Encode_header(NdrBuffer buf)
|
||||
{
|
||||
buf.Enc_ndr_small(5);
|
||||
buf.Enc_ndr_small(0);
|
||||
buf.Enc_ndr_small(Ptype);
|
||||
buf.Enc_ndr_small(Flags);
|
||||
buf.Enc_ndr_long(unchecked(0x00000010));
|
||||
buf.Enc_ndr_short(Length);
|
||||
buf.Enc_ndr_short(0);
|
||||
buf.Enc_ndr_long(CallId);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
internal virtual void Decode_header(NdrBuffer buf)
|
||||
{
|
||||
if (buf.Dec_ndr_small() != 5 || buf.Dec_ndr_small() != 0)
|
||||
{
|
||||
throw new NdrException("DCERPC version not supported");
|
||||
}
|
||||
Ptype = buf.Dec_ndr_small();
|
||||
Flags = buf.Dec_ndr_small();
|
||||
if (buf.Dec_ndr_long() != unchecked(0x00000010))
|
||||
{
|
||||
throw new NdrException("Data representation not supported");
|
||||
}
|
||||
Length = buf.Dec_ndr_short();
|
||||
if (buf.Dec_ndr_short() != 0)
|
||||
{
|
||||
throw new NdrException("DCERPC authentication not supported");
|
||||
}
|
||||
CallId = buf.Dec_ndr_long();
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer buf)
|
||||
{
|
||||
int start = buf.GetIndex();
|
||||
int allocHintIndex = 0;
|
||||
buf.Advance(16);
|
||||
if (Ptype == 0)
|
||||
{
|
||||
allocHintIndex = buf.GetIndex();
|
||||
buf.Enc_ndr_long(0);
|
||||
buf.Enc_ndr_short(0);
|
||||
buf.Enc_ndr_short(GetOpnum());
|
||||
}
|
||||
Encode_in(buf);
|
||||
Length = buf.GetIndex() - start;
|
||||
if (Ptype == 0)
|
||||
{
|
||||
buf.SetIndex(allocHintIndex);
|
||||
AllocHint = Length - allocHintIndex;
|
||||
buf.Enc_ndr_long(AllocHint);
|
||||
}
|
||||
buf.SetIndex(start);
|
||||
Encode_header(buf);
|
||||
buf.SetIndex(start + Length);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer buf)
|
||||
{
|
||||
Decode_header(buf);
|
||||
if (Ptype != 12 && Ptype != 2 && Ptype != 3 && Ptype != 13)
|
||||
{
|
||||
throw new NdrException("Unexpected ptype: " + Ptype);
|
||||
}
|
||||
if (Ptype == 2 || Ptype == 3)
|
||||
{
|
||||
AllocHint = buf.Dec_ndr_long();
|
||||
buf.Dec_ndr_short();
|
||||
buf.Dec_ndr_short();
|
||||
}
|
||||
if (Ptype == 3 || Ptype == 13)
|
||||
{
|
||||
Result = buf.Dec_ndr_long();
|
||||
}
|
||||
else
|
||||
{
|
||||
Decode_out(buf);
|
||||
}
|
||||
}
|
||||
|
||||
public abstract int GetOpnum();
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public abstract void Encode_in(NdrBuffer dst);
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public abstract void Decode_out(NdrBuffer src);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpCifs.Smb;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public class DcerpcPipeHandle : DcerpcHandle
|
||||
{
|
||||
internal SmbNamedPipe Pipe;
|
||||
|
||||
internal SmbFileInputStream In;
|
||||
|
||||
internal SmbFileOutputStream Out;
|
||||
|
||||
internal bool IsStart = true;
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
/// <exception cref="System.UriFormatException"></exception>
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth)
|
||||
{
|
||||
Binding = ParseBinding(url);
|
||||
url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint
|
||||
, 6);
|
||||
string @params = string.Empty;
|
||||
string server;
|
||||
string address;
|
||||
server = (string)Binding.GetOption("server");
|
||||
if (server != null)
|
||||
{
|
||||
@params += "&server=" + server;
|
||||
}
|
||||
address = (string)Binding.GetOption("address");
|
||||
if (server != null)
|
||||
{
|
||||
@params += "&address=" + address;
|
||||
}
|
||||
if (@params.Length > 0)
|
||||
{
|
||||
url += "?" + Runtime.Substring(@params, 1);
|
||||
}
|
||||
Pipe = new SmbNamedPipe(url, (unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeRdwr
|
||||
| SmbNamedPipe.PipeTypeDceTransact, auth);
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
protected internal override void DoSendFragment(byte[] buf, int off, int length,
|
||||
bool isDirect)
|
||||
{
|
||||
if (Out != null && Out.IsOpen() == false)
|
||||
{
|
||||
throw new IOException("DCERPC pipe is no longer open");
|
||||
}
|
||||
if (In == null)
|
||||
{
|
||||
In = (SmbFileInputStream)Pipe.GetNamedPipeInputStream();
|
||||
}
|
||||
if (Out == null)
|
||||
{
|
||||
Out = (SmbFileOutputStream)Pipe.GetNamedPipeOutputStream();
|
||||
}
|
||||
if (isDirect)
|
||||
{
|
||||
Out.WriteDirect(buf, off, length, 1);
|
||||
return;
|
||||
}
|
||||
Out.Write(buf, off, length);
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
protected internal override void DoReceiveFragment(byte[] buf, bool isDirect)
|
||||
{
|
||||
int off;
|
||||
int flags;
|
||||
int length;
|
||||
if (buf.Length < MaxRecv)
|
||||
{
|
||||
throw new ArgumentException("buffer too small");
|
||||
}
|
||||
if (IsStart && !isDirect)
|
||||
{
|
||||
// start of new frag, do trans
|
||||
off = In.Read(buf, 0, 1024);
|
||||
}
|
||||
else
|
||||
{
|
||||
off = In.ReadDirect(buf, 0, buf.Length);
|
||||
}
|
||||
if (buf[0] != 5 && buf[1] != 0)
|
||||
{
|
||||
throw new IOException("Unexpected DCERPC PDU header");
|
||||
}
|
||||
flags = buf[3] & unchecked(0xFF);
|
||||
// next read is start of new frag
|
||||
IsStart = (flags & DcerpcConstants.DcerpcLastFrag) == DcerpcConstants.DcerpcLastFrag;
|
||||
length = Encdec.Dec_uint16le(buf, 8);
|
||||
if (length > MaxRecv)
|
||||
{
|
||||
throw new IOException("Unexpected fragment length: " + length);
|
||||
}
|
||||
while (off < length)
|
||||
{
|
||||
off += In.ReadDirect(buf, off, length - off);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public override void Close()
|
||||
{
|
||||
State = 0;
|
||||
if (Out != null)
|
||||
{
|
||||
Out.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public interface IDcerpcSecurityProvider
|
||||
{
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
void Wrap(NdrBuffer outgoing);
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
|
||||
void Unwrap(NdrBuffer incoming);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class LsaPolicyHandle : Rpc.PolicyHandle
|
||||
{
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public LsaPolicyHandle(DcerpcHandle handle, string server, int access)
|
||||
{
|
||||
if (server == null)
|
||||
{
|
||||
server = "\\\\";
|
||||
}
|
||||
MsrpcLsarOpenPolicy2 rpc = new MsrpcLsarOpenPolicy2(server, access, this);
|
||||
handle.Sendrecv(rpc);
|
||||
if (rpc.Retval != 0)
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Close()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
internal class LsarSidArrayX : Lsarpc.LsarSidArray
|
||||
{
|
||||
internal LsarSidArrayX(Sid[] sids)
|
||||
{
|
||||
NumSids = sids.Length;
|
||||
this.Sids = new Lsarpc.LsarSidPtr[sids.Length];
|
||||
for (int si = 0; si < sids.Length; si++)
|
||||
{
|
||||
this.Sids[si] = new Lsarpc.LsarSidPtr();
|
||||
this.Sids[si].Sid = sids[si];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1161
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs
Normal file
1161
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Lsarpc.cs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx
|
||||
{
|
||||
public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0))
|
||||
{
|
||||
Info.Level = Level;
|
||||
Info.E = new Netdfs.DfsEnumArray200();
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
|
||||
public virtual IFileEntry[] GetEntries()
|
||||
{
|
||||
Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E;
|
||||
SmbShareInfo[] entries = new SmbShareInfo[a200.Count];
|
||||
for (int i = 0; i < a200.Count; i++)
|
||||
{
|
||||
entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcEnumerateAliasesInDomain : Samr.SamrEnumerateAliasesInDomain
|
||||
{
|
||||
public MsrpcEnumerateAliasesInDomain(SamrDomainHandle domainHandle, int acctFlags
|
||||
, Samr.SamrSamArray sam) : base(domainHandle, 0, acctFlags, null, 0)
|
||||
{
|
||||
this.Sam = sam;
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcGetMembersInAlias : Samr.SamrGetMembersInAlias
|
||||
{
|
||||
public MsrpcGetMembersInAlias(SamrAliasHandle aliasHandle, Lsarpc.LsarSidArray sids
|
||||
) : base(aliasHandle, sids)
|
||||
{
|
||||
this.Sids = sids;
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcLookupSids : Lsarpc.LsarLookupSids
|
||||
{
|
||||
internal Sid[] sids;
|
||||
|
||||
public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) : base(policyHandle
|
||||
, new LsarSidArrayX(sids), new Lsarpc.LsarRefDomainList(), new Lsarpc.LsarTransNameArray
|
||||
(), 1, sids.Length)
|
||||
{
|
||||
this.sids = sids;
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2
|
||||
{
|
||||
public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle
|
||||
) : base(server, new Lsarpc.LsarObjectAttributes(), access, policyHandle)
|
||||
{
|
||||
ObjectAttributes.Length = 24;
|
||||
Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo();
|
||||
qos.Length = 12;
|
||||
qos.ImpersonationLevel = 2;
|
||||
qos.ContextMode = 1;
|
||||
qos.EffectiveOnly = 0;
|
||||
ObjectAttributes.SecurityQualityOfService = qos;
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcQueryInformationPolicy : Lsarpc.LsarQueryInformationPolicy
|
||||
{
|
||||
public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject
|
||||
info) : base(policyHandle, level, info)
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcSamrConnect2 : Samr.SamrConnect2
|
||||
{
|
||||
public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle
|
||||
) : base(server, access, policyHandle)
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcSamrConnect4 : Samr.SamrConnect4
|
||||
{
|
||||
public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle
|
||||
) : base(server, 2, access, policyHandle)
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
|
||||
{
|
||||
public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle
|
||||
aliasHandle) : base(handle, access, rid, aliasHandle)
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain
|
||||
{
|
||||
public MsrpcSamrOpenDomain(SamrPolicyHandle handle, int access, Rpc.SidT sid, SamrDomainHandle
|
||||
domainHandle) : base(handle, access, sid, domainHandle)
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcShareEnum : Srvsvc.ShareEnumAll
|
||||
{
|
||||
internal class MsrpcShareInfo1 : SmbShareInfo
|
||||
{
|
||||
internal MsrpcShareInfo1(MsrpcShareEnum enclosing, Srvsvc.ShareInfo1 info1)
|
||||
{
|
||||
this._enclosing = enclosing;
|
||||
NetName = info1.Netname;
|
||||
Type = info1.Type;
|
||||
Remark = info1.Remark;
|
||||
}
|
||||
|
||||
private readonly MsrpcShareEnum _enclosing;
|
||||
}
|
||||
|
||||
public MsrpcShareEnum(string server) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1
|
||||
(), -1, 0, 0)
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
|
||||
public virtual IFileEntry[] GetEntries()
|
||||
{
|
||||
Srvsvc.ShareInfoCtr1 ctr = (Srvsvc.ShareInfoCtr1)Info;
|
||||
MsrpcShareInfo1[] entries = new MsrpcShareInfo1[ctr
|
||||
.Count];
|
||||
for (int i = 0; i < ctr.Count; i++)
|
||||
{
|
||||
entries[i] = new MsrpcShareInfo1(this, ctr.Array[i]);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
|
||||
{
|
||||
public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename
|
||||
, 502, new Srvsvc.ShareInfo502())
|
||||
{
|
||||
Ptype = 0;
|
||||
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual Ace[] GetSecurity()
|
||||
{
|
||||
Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info;
|
||||
if (info502.SecurityDescriptor != null)
|
||||
{
|
||||
SecurityDescriptor sd;
|
||||
sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize);
|
||||
return sd.Aces;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
616
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs
Normal file
616
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Netdfs.cs
Normal file
@@ -0,0 +1,616 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class Netdfs
|
||||
{
|
||||
public static string GetSyntax()
|
||||
{
|
||||
return "4fc742e0-4a10-11cf-8273-00aa004ae673:3.0";
|
||||
}
|
||||
|
||||
public const int DfsVolumeFlavorStandalone = unchecked(0x100);
|
||||
|
||||
public const int DfsVolumeFlavorAdBlob = unchecked(0x200);
|
||||
|
||||
public const int DfsStorageStateOffline = unchecked(0x0001);
|
||||
|
||||
public const int DfsStorageStateOnline = unchecked(0x0002);
|
||||
|
||||
public const int DfsStorageStateActive = unchecked(0x0004);
|
||||
|
||||
public class DfsInfo1 : NdrObject
|
||||
{
|
||||
public string EntryPath;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_referent(EntryPath, 1);
|
||||
if (EntryPath != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(EntryPath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int entryPathp = src.Dec_ndr_long();
|
||||
if (entryPathp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
EntryPath = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsEnumArray1 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public DfsInfo1[] S;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(S, 1);
|
||||
if (S != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int ss = Count;
|
||||
dst.Enc_ndr_long(ss);
|
||||
int si = dst.Index;
|
||||
dst.Advance(4 * ss);
|
||||
dst = dst.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
S[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int sp = src.Dec_ndr_long();
|
||||
if (sp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int ss = src.Dec_ndr_long();
|
||||
int si = src.Index;
|
||||
src.Advance(4 * ss);
|
||||
if (S == null)
|
||||
{
|
||||
if (ss < 0 || ss > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
S = new DfsInfo1[ss];
|
||||
}
|
||||
src = src.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
if (S[i] == null)
|
||||
{
|
||||
S[i] = new DfsInfo1();
|
||||
}
|
||||
S[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsStorageInfo : NdrObject
|
||||
{
|
||||
public int State;
|
||||
|
||||
public string ServerName;
|
||||
|
||||
public string ShareName;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(State);
|
||||
dst.Enc_ndr_referent(ServerName, 1);
|
||||
dst.Enc_ndr_referent(ShareName, 1);
|
||||
if (ServerName != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(ServerName);
|
||||
}
|
||||
if (ShareName != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(ShareName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
State = src.Dec_ndr_long();
|
||||
int serverNamep = src.Dec_ndr_long();
|
||||
int shareNamep = src.Dec_ndr_long();
|
||||
if (serverNamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
ServerName = src.Dec_ndr_string();
|
||||
}
|
||||
if (shareNamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
ShareName = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsInfo3 : NdrObject
|
||||
{
|
||||
public string Path;
|
||||
|
||||
public string Comment;
|
||||
|
||||
public int State;
|
||||
|
||||
public int NumStores;
|
||||
|
||||
public DfsStorageInfo[] Stores;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_referent(Path, 1);
|
||||
dst.Enc_ndr_referent(Comment, 1);
|
||||
dst.Enc_ndr_long(State);
|
||||
dst.Enc_ndr_long(NumStores);
|
||||
dst.Enc_ndr_referent(Stores, 1);
|
||||
if (Path != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Path);
|
||||
}
|
||||
if (Comment != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Comment);
|
||||
}
|
||||
if (Stores != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int storess = NumStores;
|
||||
dst.Enc_ndr_long(storess);
|
||||
int storesi = dst.Index;
|
||||
dst.Advance(12 * storess);
|
||||
dst = dst.Derive(storesi);
|
||||
for (int i = 0; i < storess; i++)
|
||||
{
|
||||
Stores[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int pathp = src.Dec_ndr_long();
|
||||
int commentp = src.Dec_ndr_long();
|
||||
State = src.Dec_ndr_long();
|
||||
NumStores = src.Dec_ndr_long();
|
||||
int storesp = src.Dec_ndr_long();
|
||||
if (pathp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Path = src.Dec_ndr_string();
|
||||
}
|
||||
if (commentp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Comment = src.Dec_ndr_string();
|
||||
}
|
||||
if (storesp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int storess = src.Dec_ndr_long();
|
||||
int storesi = src.Index;
|
||||
src.Advance(12 * storess);
|
||||
if (Stores == null)
|
||||
{
|
||||
if (storess < 0 || storess > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Stores = new DfsStorageInfo[storess];
|
||||
}
|
||||
src = src.Derive(storesi);
|
||||
for (int i = 0; i < storess; i++)
|
||||
{
|
||||
if (Stores[i] == null)
|
||||
{
|
||||
Stores[i] = new DfsStorageInfo();
|
||||
}
|
||||
Stores[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsEnumArray3 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public DfsInfo3[] S;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(S, 1);
|
||||
if (S != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int ss = Count;
|
||||
dst.Enc_ndr_long(ss);
|
||||
int si = dst.Index;
|
||||
dst.Advance(20 * ss);
|
||||
dst = dst.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
S[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int sp = src.Dec_ndr_long();
|
||||
if (sp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int ss = src.Dec_ndr_long();
|
||||
int si = src.Index;
|
||||
src.Advance(20 * ss);
|
||||
if (S == null)
|
||||
{
|
||||
if (ss < 0 || ss > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
S = new DfsInfo3[ss];
|
||||
}
|
||||
src = src.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
if (S[i] == null)
|
||||
{
|
||||
S[i] = new DfsInfo3();
|
||||
}
|
||||
S[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsInfo200 : NdrObject
|
||||
{
|
||||
public string DfsName;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_referent(DfsName, 1);
|
||||
if (DfsName != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(DfsName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int dfsNamep = src.Dec_ndr_long();
|
||||
if (dfsNamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
DfsName = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsEnumArray200 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public DfsInfo200[] S;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(S, 1);
|
||||
if (S != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int ss = Count;
|
||||
dst.Enc_ndr_long(ss);
|
||||
int si = dst.Index;
|
||||
dst.Advance(4 * ss);
|
||||
dst = dst.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
S[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int sp = src.Dec_ndr_long();
|
||||
if (sp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int ss = src.Dec_ndr_long();
|
||||
int si = src.Index;
|
||||
src.Advance(4 * ss);
|
||||
if (S == null)
|
||||
{
|
||||
if (ss < 0 || ss > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
S = new DfsInfo200[ss];
|
||||
}
|
||||
src = src.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
if (S[i] == null)
|
||||
{
|
||||
S[i] = new DfsInfo200();
|
||||
}
|
||||
S[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsInfo300 : NdrObject
|
||||
{
|
||||
public int Flags;
|
||||
|
||||
public string DfsName;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Flags);
|
||||
dst.Enc_ndr_referent(DfsName, 1);
|
||||
if (DfsName != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(DfsName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Flags = src.Dec_ndr_long();
|
||||
int dfsNamep = src.Dec_ndr_long();
|
||||
if (dfsNamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
DfsName = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsEnumArray300 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public DfsInfo300[] S;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(S, 1);
|
||||
if (S != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int ss = Count;
|
||||
dst.Enc_ndr_long(ss);
|
||||
int si = dst.Index;
|
||||
dst.Advance(8 * ss);
|
||||
dst = dst.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
S[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int sp = src.Dec_ndr_long();
|
||||
if (sp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int ss = src.Dec_ndr_long();
|
||||
int si = src.Index;
|
||||
src.Advance(8 * ss);
|
||||
if (S == null)
|
||||
{
|
||||
if (ss < 0 || ss > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
S = new DfsInfo300[ss];
|
||||
}
|
||||
src = src.Derive(si);
|
||||
for (int i = 0; i < ss; i++)
|
||||
{
|
||||
if (S[i] == null)
|
||||
{
|
||||
S[i] = new DfsInfo300();
|
||||
}
|
||||
S[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class DfsEnumStruct : NdrObject
|
||||
{
|
||||
public int Level;
|
||||
|
||||
public NdrObject E;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Level);
|
||||
int descr = Level;
|
||||
dst.Enc_ndr_long(descr);
|
||||
dst.Enc_ndr_referent(E, 1);
|
||||
if (E != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
E.Encode(dst);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Level = src.Dec_ndr_long();
|
||||
src.Dec_ndr_long();
|
||||
int ep = src.Dec_ndr_long();
|
||||
if (ep != 0)
|
||||
{
|
||||
if (E == null)
|
||||
{
|
||||
E = new DfsEnumArray1();
|
||||
}
|
||||
src = src.Deferred;
|
||||
E.Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class NetrDfsEnumEx : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x15);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string DfsName;
|
||||
|
||||
public int Level;
|
||||
|
||||
public int Prefmaxlen;
|
||||
|
||||
public DfsEnumStruct Info;
|
||||
|
||||
public NdrLong Totalentries;
|
||||
|
||||
public NetrDfsEnumEx(string dfsName, int level, int prefmaxlen, DfsEnumStruct
|
||||
info, NdrLong totalentries)
|
||||
{
|
||||
this.DfsName = dfsName;
|
||||
this.Level = level;
|
||||
this.Prefmaxlen = prefmaxlen;
|
||||
this.Info = info;
|
||||
this.Totalentries = totalentries;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_string(DfsName);
|
||||
dst.Enc_ndr_long(Level);
|
||||
dst.Enc_ndr_long(Prefmaxlen);
|
||||
dst.Enc_ndr_referent(Info, 1);
|
||||
if (Info != null)
|
||||
{
|
||||
Info.Encode(dst);
|
||||
}
|
||||
dst.Enc_ndr_referent(Totalentries, 1);
|
||||
if (Totalentries != null)
|
||||
{
|
||||
Totalentries.Encode(dst);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
int infop = src.Dec_ndr_long();
|
||||
if (infop != 0)
|
||||
{
|
||||
if (Info == null)
|
||||
{
|
||||
Info = new DfsEnumStruct();
|
||||
}
|
||||
Info.Decode(src);
|
||||
}
|
||||
int totalentriesp = src.Dec_ndr_long();
|
||||
if (totalentriesp != 0)
|
||||
{
|
||||
Totalentries.Decode(src);
|
||||
}
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
579
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs
Normal file
579
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Samr.cs
Normal file
@@ -0,0 +1,579 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class Samr
|
||||
{
|
||||
public static string GetSyntax()
|
||||
{
|
||||
return "12345778-1234-abcd-ef00-0123456789ac:1.0";
|
||||
}
|
||||
|
||||
public const int AcbDisabled = 1;
|
||||
|
||||
public const int AcbHomdirreq = 2;
|
||||
|
||||
public const int AcbPwnotreq = 4;
|
||||
|
||||
public const int AcbTempdup = 8;
|
||||
|
||||
public const int AcbNormal = 16;
|
||||
|
||||
public const int AcbMns = 32;
|
||||
|
||||
public const int AcbDomtrust = 64;
|
||||
|
||||
public const int AcbWstrust = 128;
|
||||
|
||||
public const int AcbSvrtrust = 256;
|
||||
|
||||
public const int AcbPwnoexp = 512;
|
||||
|
||||
public const int AcbAutolock = 1024;
|
||||
|
||||
public const int AcbEncTxtPwdAllowed = 2048;
|
||||
|
||||
public const int AcbSmartcardRequired = 4096;
|
||||
|
||||
public const int AcbTrustedForDelegation = 8192;
|
||||
|
||||
public const int AcbNotDelegated = 16384;
|
||||
|
||||
public const int AcbUseDesKeyOnly = 32768;
|
||||
|
||||
public const int AcbDontRequirePreauth = 65536;
|
||||
|
||||
public class SamrCloseHandle : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x01);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public Rpc.PolicyHandle Handle;
|
||||
|
||||
public SamrCloseHandle(Rpc.PolicyHandle handle)
|
||||
{
|
||||
this.Handle = handle;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
Handle.Encode(dst);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrConnect2 : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x39);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string SystemName;
|
||||
|
||||
public int AccessMask;
|
||||
|
||||
public Rpc.PolicyHandle Handle;
|
||||
|
||||
public SamrConnect2(string systemName, int accessMask, Rpc.PolicyHandle handle
|
||||
)
|
||||
{
|
||||
this.SystemName = systemName;
|
||||
this.AccessMask = accessMask;
|
||||
this.Handle = handle;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_referent(SystemName, 1);
|
||||
if (SystemName != null)
|
||||
{
|
||||
dst.Enc_ndr_string(SystemName);
|
||||
}
|
||||
dst.Enc_ndr_long(AccessMask);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
Handle.Decode(src);
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrConnect4 : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x3e);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string SystemName;
|
||||
|
||||
public int Unknown;
|
||||
|
||||
public int AccessMask;
|
||||
|
||||
public Rpc.PolicyHandle Handle;
|
||||
|
||||
public SamrConnect4(string systemName, int unknown, int accessMask, Rpc.PolicyHandle
|
||||
handle)
|
||||
{
|
||||
this.SystemName = systemName;
|
||||
this.Unknown = unknown;
|
||||
this.AccessMask = accessMask;
|
||||
this.Handle = handle;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_referent(SystemName, 1);
|
||||
if (SystemName != null)
|
||||
{
|
||||
dst.Enc_ndr_string(SystemName);
|
||||
}
|
||||
dst.Enc_ndr_long(Unknown);
|
||||
dst.Enc_ndr_long(AccessMask);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
Handle.Decode(src);
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrOpenDomain : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x07);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public Rpc.PolicyHandle Handle;
|
||||
|
||||
public int AccessMask;
|
||||
|
||||
public Rpc.SidT Sid;
|
||||
|
||||
public Rpc.PolicyHandle DomainHandle;
|
||||
|
||||
public SamrOpenDomain(Rpc.PolicyHandle handle, int accessMask, Rpc.SidT sid, Rpc.PolicyHandle
|
||||
domainHandle)
|
||||
{
|
||||
this.Handle = handle;
|
||||
this.AccessMask = accessMask;
|
||||
this.Sid = sid;
|
||||
this.DomainHandle = domainHandle;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
Handle.Encode(dst);
|
||||
dst.Enc_ndr_long(AccessMask);
|
||||
Sid.Encode(dst);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
DomainHandle.Decode(src);
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrSamEntry : NdrObject
|
||||
{
|
||||
public int Idx;
|
||||
|
||||
public Rpc.Unicode_string Name;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Idx);
|
||||
dst.Enc_ndr_short(Name.Length);
|
||||
dst.Enc_ndr_short(Name.MaximumLength);
|
||||
dst.Enc_ndr_referent(Name.Buffer, 1);
|
||||
if (Name.Buffer != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int nameBufferl = Name.Length / 2;
|
||||
int nameBuffers = Name.MaximumLength / 2;
|
||||
dst.Enc_ndr_long(nameBuffers);
|
||||
dst.Enc_ndr_long(0);
|
||||
dst.Enc_ndr_long(nameBufferl);
|
||||
int nameBufferi = dst.Index;
|
||||
dst.Advance(2 * nameBufferl);
|
||||
dst = dst.Derive(nameBufferi);
|
||||
for (int i = 0; i < nameBufferl; i++)
|
||||
{
|
||||
dst.Enc_ndr_short(Name.Buffer[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Idx = src.Dec_ndr_long();
|
||||
src.Align(4);
|
||||
if (Name == null)
|
||||
{
|
||||
Name = new Rpc.Unicode_string();
|
||||
}
|
||||
Name.Length = (short)src.Dec_ndr_short();
|
||||
Name.MaximumLength = (short)src.Dec_ndr_short();
|
||||
int nameBufferp = src.Dec_ndr_long();
|
||||
if (nameBufferp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int nameBuffers = src.Dec_ndr_long();
|
||||
src.Dec_ndr_long();
|
||||
int nameBufferl = src.Dec_ndr_long();
|
||||
int nameBufferi = src.Index;
|
||||
src.Advance(2 * nameBufferl);
|
||||
if (Name.Buffer == null)
|
||||
{
|
||||
if (nameBuffers < 0 || nameBuffers > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Name.Buffer = new short[nameBuffers];
|
||||
}
|
||||
src = src.Derive(nameBufferi);
|
||||
for (int i = 0; i < nameBufferl; i++)
|
||||
{
|
||||
Name.Buffer[i] = (short)src.Dec_ndr_short();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrSamArray : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public SamrSamEntry[] Entries;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(Entries, 1);
|
||||
if (Entries != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int entriess = Count;
|
||||
dst.Enc_ndr_long(entriess);
|
||||
int entriesi = dst.Index;
|
||||
dst.Advance(12 * entriess);
|
||||
dst = dst.Derive(entriesi);
|
||||
for (int i = 0; i < entriess; i++)
|
||||
{
|
||||
Entries[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int entriesp = src.Dec_ndr_long();
|
||||
if (entriesp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int entriess = src.Dec_ndr_long();
|
||||
int entriesi = src.Index;
|
||||
src.Advance(12 * entriess);
|
||||
if (Entries == null)
|
||||
{
|
||||
if (entriess < 0 || entriess > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Entries = new SamrSamEntry[entriess];
|
||||
}
|
||||
src = src.Derive(entriesi);
|
||||
for (int i = 0; i < entriess; i++)
|
||||
{
|
||||
if (Entries[i] == null)
|
||||
{
|
||||
Entries[i] = new SamrSamEntry();
|
||||
}
|
||||
Entries[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrEnumerateAliasesInDomain : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x0f);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public Rpc.PolicyHandle DomainHandle;
|
||||
|
||||
public int ResumeHandle;
|
||||
|
||||
public int AcctFlags;
|
||||
|
||||
public SamrSamArray Sam;
|
||||
|
||||
public int NumEntries;
|
||||
|
||||
public SamrEnumerateAliasesInDomain(Rpc.PolicyHandle domainHandle, int resumeHandle
|
||||
, int acctFlags, SamrSamArray sam, int numEntries)
|
||||
{
|
||||
this.DomainHandle = domainHandle;
|
||||
this.ResumeHandle = resumeHandle;
|
||||
this.AcctFlags = acctFlags;
|
||||
this.Sam = sam;
|
||||
this.NumEntries = numEntries;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
DomainHandle.Encode(dst);
|
||||
dst.Enc_ndr_long(ResumeHandle);
|
||||
dst.Enc_ndr_long(AcctFlags);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
ResumeHandle = src.Dec_ndr_long();
|
||||
int samp = src.Dec_ndr_long();
|
||||
if (samp != 0)
|
||||
{
|
||||
if (Sam == null)
|
||||
{
|
||||
Sam = new SamrSamArray();
|
||||
}
|
||||
Sam.Decode(src);
|
||||
}
|
||||
NumEntries = src.Dec_ndr_long();
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrOpenAlias : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x1b);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public Rpc.PolicyHandle DomainHandle;
|
||||
|
||||
public int AccessMask;
|
||||
|
||||
public int Rid;
|
||||
|
||||
public Rpc.PolicyHandle AliasHandle;
|
||||
|
||||
public SamrOpenAlias(Rpc.PolicyHandle domainHandle, int accessMask, int rid, Rpc.PolicyHandle
|
||||
aliasHandle)
|
||||
{
|
||||
this.DomainHandle = domainHandle;
|
||||
this.AccessMask = accessMask;
|
||||
this.Rid = rid;
|
||||
this.AliasHandle = aliasHandle;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
DomainHandle.Encode(dst);
|
||||
dst.Enc_ndr_long(AccessMask);
|
||||
dst.Enc_ndr_long(Rid);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
AliasHandle.Decode(src);
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrGetMembersInAlias : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x21);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public Rpc.PolicyHandle AliasHandle;
|
||||
|
||||
public Lsarpc.LsarSidArray Sids;
|
||||
|
||||
public SamrGetMembersInAlias(Rpc.PolicyHandle aliasHandle, Lsarpc.LsarSidArray
|
||||
sids)
|
||||
{
|
||||
this.AliasHandle = aliasHandle;
|
||||
this.Sids = sids;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
AliasHandle.Encode(dst);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
Sids.Decode(src);
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public const int SeGroupMandatory = 1;
|
||||
|
||||
public const int SeGroupEnabledByDefault = 2;
|
||||
|
||||
public const int SeGroupEnabled = 4;
|
||||
|
||||
public const int SeGroupOwner = 8;
|
||||
|
||||
public const int SeGroupUseForDenyOnly = 16;
|
||||
|
||||
public const int SeGroupResource = 536870912;
|
||||
|
||||
public const int SeGroupLogonId = -1073741824;
|
||||
|
||||
public class SamrRidWithAttribute : NdrObject
|
||||
{
|
||||
public int Rid;
|
||||
|
||||
public int Attributes;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Rid);
|
||||
dst.Enc_ndr_long(Attributes);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Rid = src.Dec_ndr_long();
|
||||
Attributes = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class SamrRidWithAttributeArray : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public SamrRidWithAttribute[] Rids;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(Rids, 1);
|
||||
if (Rids != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int ridss = Count;
|
||||
dst.Enc_ndr_long(ridss);
|
||||
int ridsi = dst.Index;
|
||||
dst.Advance(8 * ridss);
|
||||
dst = dst.Derive(ridsi);
|
||||
for (int i = 0; i < ridss; i++)
|
||||
{
|
||||
Rids[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int ridsp = src.Dec_ndr_long();
|
||||
if (ridsp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int ridss = src.Dec_ndr_long();
|
||||
int ridsi = src.Index;
|
||||
src.Advance(8 * ridss);
|
||||
if (Rids == null)
|
||||
{
|
||||
if (ridss < 0 || ridss > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Rids = new SamrRidWithAttribute[ridss];
|
||||
}
|
||||
src = src.Derive(ridsi);
|
||||
for (int i = 0; i < ridss; i++)
|
||||
{
|
||||
if (Rids[i] == null)
|
||||
{
|
||||
Rids[i] = new SamrRidWithAttribute();
|
||||
}
|
||||
Rids[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class SamrAliasHandle : Rpc.PolicyHandle
|
||||
{
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access
|
||||
, int rid)
|
||||
{
|
||||
MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
|
||||
handle.Sendrecv(rpc);
|
||||
if (rpc.Retval != 0)
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Close()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Smb;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class SamrDomainHandle : Rpc.PolicyHandle
|
||||
{
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public SamrDomainHandle(DcerpcHandle handle, SamrPolicyHandle policyHandle, int access
|
||||
, Rpc.SidT sid)
|
||||
{
|
||||
MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this
|
||||
);
|
||||
handle.Sendrecv(rpc);
|
||||
if (rpc.Retval != 0)
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Close()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class SamrPolicyHandle : Rpc.PolicyHandle
|
||||
{
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public SamrPolicyHandle(DcerpcHandle handle, string server, int access)
|
||||
{
|
||||
if (server == null)
|
||||
{
|
||||
server = "\\\\";
|
||||
}
|
||||
MsrpcSamrConnect4 rpc = new MsrpcSamrConnect4(server, access, this);
|
||||
try
|
||||
{
|
||||
handle.Sendrecv(rpc);
|
||||
}
|
||||
catch (DcerpcException de)
|
||||
{
|
||||
if (de.GetErrorCode() != DcerpcError.DcerpcFaultOpRngError)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
MsrpcSamrConnect2 rpc2 = new MsrpcSamrConnect2(server, access, this);
|
||||
handle.Sendrecv(rpc2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Close()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
734
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs
Normal file
734
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Msrpc/Srvsvc.cs
Normal file
@@ -0,0 +1,734 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Msrpc
|
||||
{
|
||||
public class Srvsvc
|
||||
{
|
||||
public static string GetSyntax()
|
||||
{
|
||||
return "4b324fc8-1670-01d3-1278-5a47bf6ee188:3.0";
|
||||
}
|
||||
|
||||
public class ShareInfo0 : NdrObject
|
||||
{
|
||||
public string Netname;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_referent(Netname, 1);
|
||||
if (Netname != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Netname);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int netnamep = src.Dec_ndr_long();
|
||||
if (netnamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Netname = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareInfoCtr0 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public ShareInfo0[] Array;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(Array, 1);
|
||||
if (Array != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int arrays = Count;
|
||||
dst.Enc_ndr_long(arrays);
|
||||
int arrayi = dst.Index;
|
||||
dst.Advance(4 * arrays);
|
||||
dst = dst.Derive(arrayi);
|
||||
for (int i = 0; i < arrays; i++)
|
||||
{
|
||||
Array[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int arrayp = src.Dec_ndr_long();
|
||||
if (arrayp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int arrays = src.Dec_ndr_long();
|
||||
int arrayi = src.Index;
|
||||
src.Advance(4 * arrays);
|
||||
if (Array == null)
|
||||
{
|
||||
if (arrays < 0 || arrays > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Array = new ShareInfo0[arrays];
|
||||
}
|
||||
src = src.Derive(arrayi);
|
||||
for (int i = 0; i < arrays; i++)
|
||||
{
|
||||
if (Array[i] == null)
|
||||
{
|
||||
Array[i] = new ShareInfo0();
|
||||
}
|
||||
Array[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareInfo1 : NdrObject
|
||||
{
|
||||
public string Netname;
|
||||
|
||||
public int Type;
|
||||
|
||||
public string Remark;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_referent(Netname, 1);
|
||||
dst.Enc_ndr_long(Type);
|
||||
dst.Enc_ndr_referent(Remark, 1);
|
||||
if (Netname != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Netname);
|
||||
}
|
||||
if (Remark != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Remark);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int netnamep = src.Dec_ndr_long();
|
||||
Type = src.Dec_ndr_long();
|
||||
int remarkp = src.Dec_ndr_long();
|
||||
if (netnamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Netname = src.Dec_ndr_string();
|
||||
}
|
||||
if (remarkp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Remark = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareInfoCtr1 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public ShareInfo1[] Array;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(Array, 1);
|
||||
if (Array != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int arrays = Count;
|
||||
dst.Enc_ndr_long(arrays);
|
||||
int arrayi = dst.Index;
|
||||
dst.Advance(12 * arrays);
|
||||
dst = dst.Derive(arrayi);
|
||||
for (int i = 0; i < arrays; i++)
|
||||
{
|
||||
Array[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int arrayp = src.Dec_ndr_long();
|
||||
if (arrayp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int arrays = src.Dec_ndr_long();
|
||||
int arrayi = src.Index;
|
||||
src.Advance(12 * arrays);
|
||||
if (Array == null)
|
||||
{
|
||||
if (arrays < 0 || arrays > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Array = new ShareInfo1[arrays];
|
||||
}
|
||||
src = src.Derive(arrayi);
|
||||
for (int i = 0; i < arrays; i++)
|
||||
{
|
||||
if (Array[i] == null)
|
||||
{
|
||||
Array[i] = new ShareInfo1();
|
||||
}
|
||||
Array[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareInfo502 : NdrObject
|
||||
{
|
||||
public string Netname;
|
||||
|
||||
public int Type;
|
||||
|
||||
public string Remark;
|
||||
|
||||
public int Permissions;
|
||||
|
||||
public int MaxUses;
|
||||
|
||||
public int CurrentUses;
|
||||
|
||||
public string Path;
|
||||
|
||||
public string Password;
|
||||
|
||||
public int SdSize;
|
||||
|
||||
public byte[] SecurityDescriptor;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_referent(Netname, 1);
|
||||
dst.Enc_ndr_long(Type);
|
||||
dst.Enc_ndr_referent(Remark, 1);
|
||||
dst.Enc_ndr_long(Permissions);
|
||||
dst.Enc_ndr_long(MaxUses);
|
||||
dst.Enc_ndr_long(CurrentUses);
|
||||
dst.Enc_ndr_referent(Path, 1);
|
||||
dst.Enc_ndr_referent(Password, 1);
|
||||
dst.Enc_ndr_long(SdSize);
|
||||
dst.Enc_ndr_referent(SecurityDescriptor, 1);
|
||||
if (Netname != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Netname);
|
||||
}
|
||||
if (Remark != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Remark);
|
||||
}
|
||||
if (Path != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Path);
|
||||
}
|
||||
if (Password != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Password);
|
||||
}
|
||||
if (SecurityDescriptor != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int securityDescriptors = SdSize;
|
||||
dst.Enc_ndr_long(securityDescriptors);
|
||||
int securityDescriptori = dst.Index;
|
||||
dst.Advance(1 * securityDescriptors);
|
||||
dst = dst.Derive(securityDescriptori);
|
||||
for (int i = 0; i < securityDescriptors; i++)
|
||||
{
|
||||
dst.Enc_ndr_small(SecurityDescriptor[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int netnamep = src.Dec_ndr_long();
|
||||
Type = src.Dec_ndr_long();
|
||||
int remarkp = src.Dec_ndr_long();
|
||||
Permissions = src.Dec_ndr_long();
|
||||
MaxUses = src.Dec_ndr_long();
|
||||
CurrentUses = src.Dec_ndr_long();
|
||||
int pathp = src.Dec_ndr_long();
|
||||
int passwordp = src.Dec_ndr_long();
|
||||
SdSize = src.Dec_ndr_long();
|
||||
int securityDescriptorp = src.Dec_ndr_long();
|
||||
if (netnamep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Netname = src.Dec_ndr_string();
|
||||
}
|
||||
if (remarkp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Remark = src.Dec_ndr_string();
|
||||
}
|
||||
if (pathp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Path = src.Dec_ndr_string();
|
||||
}
|
||||
if (passwordp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Password = src.Dec_ndr_string();
|
||||
}
|
||||
if (securityDescriptorp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int securityDescriptors = src.Dec_ndr_long();
|
||||
int securityDescriptori = src.Index;
|
||||
src.Advance(1 * securityDescriptors);
|
||||
if (SecurityDescriptor == null)
|
||||
{
|
||||
if (securityDescriptors < 0 || securityDescriptors > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
SecurityDescriptor = new byte[securityDescriptors];
|
||||
}
|
||||
src = src.Derive(securityDescriptori);
|
||||
for (int i = 0; i < securityDescriptors; i++)
|
||||
{
|
||||
SecurityDescriptor[i] = unchecked((byte)src.Dec_ndr_small());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareInfoCtr502 : NdrObject
|
||||
{
|
||||
public int Count;
|
||||
|
||||
public ShareInfo502[] Array;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Count);
|
||||
dst.Enc_ndr_referent(Array, 1);
|
||||
if (Array != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int arrays = Count;
|
||||
dst.Enc_ndr_long(arrays);
|
||||
int arrayi = dst.Index;
|
||||
dst.Advance(40 * arrays);
|
||||
dst = dst.Derive(arrayi);
|
||||
for (int i = 0; i < arrays; i++)
|
||||
{
|
||||
Array[i].Encode(dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Count = src.Dec_ndr_long();
|
||||
int arrayp = src.Dec_ndr_long();
|
||||
if (arrayp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int arrays = src.Dec_ndr_long();
|
||||
int arrayi = src.Index;
|
||||
src.Advance(40 * arrays);
|
||||
if (Array == null)
|
||||
{
|
||||
if (arrays < 0 || arrays > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Array = new ShareInfo502[arrays];
|
||||
}
|
||||
src = src.Derive(arrayi);
|
||||
for (int i = 0; i < arrays; i++)
|
||||
{
|
||||
if (Array[i] == null)
|
||||
{
|
||||
Array[i] = new ShareInfo502();
|
||||
}
|
||||
Array[i].Decode(src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareEnumAll : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x0f);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string Servername;
|
||||
|
||||
public int Level;
|
||||
|
||||
public NdrObject Info;
|
||||
|
||||
public int Prefmaxlen;
|
||||
|
||||
public int Totalentries;
|
||||
|
||||
public int ResumeHandle;
|
||||
|
||||
public ShareEnumAll(string servername, int level, NdrObject info, int prefmaxlen,
|
||||
int totalentries, int resumeHandle)
|
||||
{
|
||||
this.Servername = servername;
|
||||
this.Level = level;
|
||||
this.Info = info;
|
||||
this.Prefmaxlen = prefmaxlen;
|
||||
this.Totalentries = totalentries;
|
||||
this.ResumeHandle = resumeHandle;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_referent(Servername, 1);
|
||||
if (Servername != null)
|
||||
{
|
||||
dst.Enc_ndr_string(Servername);
|
||||
}
|
||||
dst.Enc_ndr_long(Level);
|
||||
int descr = Level;
|
||||
dst.Enc_ndr_long(descr);
|
||||
dst.Enc_ndr_referent(Info, 1);
|
||||
if (Info != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
Info.Encode(dst);
|
||||
}
|
||||
dst.Enc_ndr_long(Prefmaxlen);
|
||||
dst.Enc_ndr_long(ResumeHandle);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
Level = src.Dec_ndr_long();
|
||||
src.Dec_ndr_long();
|
||||
int infop = src.Dec_ndr_long();
|
||||
if (infop != 0)
|
||||
{
|
||||
if (Info == null)
|
||||
{
|
||||
Info = new ShareInfoCtr0();
|
||||
}
|
||||
src = src.Deferred;
|
||||
Info.Decode(src);
|
||||
}
|
||||
Totalentries = src.Dec_ndr_long();
|
||||
ResumeHandle = src.Dec_ndr_long();
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class ShareGetInfo : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x10);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string Servername;
|
||||
|
||||
public string Sharename;
|
||||
|
||||
public int Level;
|
||||
|
||||
public NdrObject Info;
|
||||
|
||||
public ShareGetInfo(string servername, string sharename, int level, NdrObject info
|
||||
)
|
||||
{
|
||||
this.Servername = servername;
|
||||
this.Sharename = sharename;
|
||||
this.Level = level;
|
||||
this.Info = info;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_referent(Servername, 1);
|
||||
if (Servername != null)
|
||||
{
|
||||
dst.Enc_ndr_string(Servername);
|
||||
}
|
||||
dst.Enc_ndr_string(Sharename);
|
||||
dst.Enc_ndr_long(Level);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
src.Dec_ndr_long();
|
||||
int infop = src.Dec_ndr_long();
|
||||
if (infop != 0)
|
||||
{
|
||||
if (Info == null)
|
||||
{
|
||||
Info = new ShareInfo0();
|
||||
}
|
||||
src = src.Deferred;
|
||||
Info.Decode(src);
|
||||
}
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class ServerInfo100 : NdrObject
|
||||
{
|
||||
public int PlatformId;
|
||||
|
||||
public string Name;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(PlatformId);
|
||||
dst.Enc_ndr_referent(Name, 1);
|
||||
if (Name != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
dst.Enc_ndr_string(Name);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
PlatformId = src.Dec_ndr_long();
|
||||
int namep = src.Dec_ndr_long();
|
||||
if (namep != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
Name = src.Dec_ndr_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class ServerGetInfo : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x15);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string Servername;
|
||||
|
||||
public int Level;
|
||||
|
||||
public NdrObject Info;
|
||||
|
||||
public ServerGetInfo(string servername, int level, NdrObject info)
|
||||
{
|
||||
this.Servername = servername;
|
||||
this.Level = level;
|
||||
this.Info = info;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_referent(Servername, 1);
|
||||
if (Servername != null)
|
||||
{
|
||||
dst.Enc_ndr_string(Servername);
|
||||
}
|
||||
dst.Enc_ndr_long(Level);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
src.Dec_ndr_long();
|
||||
int infop = src.Dec_ndr_long();
|
||||
if (infop != 0)
|
||||
{
|
||||
if (Info == null)
|
||||
{
|
||||
Info = new ServerInfo100();
|
||||
}
|
||||
src = src.Deferred;
|
||||
Info.Decode(src);
|
||||
}
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class TimeOfDayInfo : NdrObject
|
||||
{
|
||||
public int Elapsedt;
|
||||
|
||||
public int Msecs;
|
||||
|
||||
public int Hours;
|
||||
|
||||
public int Mins;
|
||||
|
||||
public int Secs;
|
||||
|
||||
public int Hunds;
|
||||
|
||||
public int Timezone;
|
||||
|
||||
public int Tinterval;
|
||||
|
||||
public int Day;
|
||||
|
||||
public int Month;
|
||||
|
||||
public int Year;
|
||||
|
||||
public int Weekday;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Elapsedt);
|
||||
dst.Enc_ndr_long(Msecs);
|
||||
dst.Enc_ndr_long(Hours);
|
||||
dst.Enc_ndr_long(Mins);
|
||||
dst.Enc_ndr_long(Secs);
|
||||
dst.Enc_ndr_long(Hunds);
|
||||
dst.Enc_ndr_long(Timezone);
|
||||
dst.Enc_ndr_long(Tinterval);
|
||||
dst.Enc_ndr_long(Day);
|
||||
dst.Enc_ndr_long(Month);
|
||||
dst.Enc_ndr_long(Year);
|
||||
dst.Enc_ndr_long(Weekday);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Elapsedt = src.Dec_ndr_long();
|
||||
Msecs = src.Dec_ndr_long();
|
||||
Hours = src.Dec_ndr_long();
|
||||
Mins = src.Dec_ndr_long();
|
||||
Secs = src.Dec_ndr_long();
|
||||
Hunds = src.Dec_ndr_long();
|
||||
Timezone = src.Dec_ndr_long();
|
||||
Tinterval = src.Dec_ndr_long();
|
||||
Day = src.Dec_ndr_long();
|
||||
Month = src.Dec_ndr_long();
|
||||
Year = src.Dec_ndr_long();
|
||||
Weekday = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
|
||||
public class RemoteTod : DcerpcMessage
|
||||
{
|
||||
public override int GetOpnum()
|
||||
{
|
||||
return unchecked(0x1c);
|
||||
}
|
||||
|
||||
public int Retval;
|
||||
|
||||
public string Servername;
|
||||
|
||||
public TimeOfDayInfo Info;
|
||||
|
||||
public RemoteTod(string servername, TimeOfDayInfo info)
|
||||
{
|
||||
this.Servername = servername;
|
||||
this.Info = info;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode_in(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_referent(Servername, 1);
|
||||
if (Servername != null)
|
||||
{
|
||||
dst.Enc_ndr_string(Servername);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode_out(NdrBuffer src)
|
||||
{
|
||||
int infop = src.Dec_ndr_long();
|
||||
if (infop != 0)
|
||||
{
|
||||
if (Info == null)
|
||||
{
|
||||
Info = new TimeOfDayInfo();
|
||||
}
|
||||
Info.Decode(src);
|
||||
}
|
||||
Retval = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
305
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs
Normal file
305
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Ndr/NdrBuffer.cs
Normal file
@@ -0,0 +1,305 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
public class NdrBuffer
|
||||
{
|
||||
internal int Referent;
|
||||
|
||||
internal Hashtable Referents;
|
||||
|
||||
internal class Entry
|
||||
{
|
||||
internal int Referent;
|
||||
|
||||
internal object Obj;
|
||||
}
|
||||
|
||||
public byte[] Buf;
|
||||
|
||||
public int Start;
|
||||
|
||||
public int Index;
|
||||
|
||||
public int Length;
|
||||
|
||||
public NdrBuffer Deferred;
|
||||
|
||||
public NdrBuffer(byte[] buf, int start)
|
||||
{
|
||||
this.Buf = buf;
|
||||
this.Start = Index = start;
|
||||
Length = 0;
|
||||
Deferred = this;
|
||||
}
|
||||
|
||||
public virtual NdrBuffer Derive(int idx)
|
||||
{
|
||||
NdrBuffer nb = new NdrBuffer(Buf, Start);
|
||||
nb.Index = idx;
|
||||
nb.Deferred = Deferred;
|
||||
return nb;
|
||||
}
|
||||
|
||||
public virtual void Reset()
|
||||
{
|
||||
Index = Start;
|
||||
Length = 0;
|
||||
Deferred = this;
|
||||
}
|
||||
|
||||
public virtual int GetIndex()
|
||||
{
|
||||
return Index;
|
||||
}
|
||||
|
||||
public virtual void SetIndex(int index)
|
||||
{
|
||||
this.Index = index;
|
||||
}
|
||||
|
||||
public virtual int GetCapacity()
|
||||
{
|
||||
return Buf.Length - Start;
|
||||
}
|
||||
|
||||
public virtual int GetTailSpace()
|
||||
{
|
||||
return Buf.Length - Index;
|
||||
}
|
||||
|
||||
public virtual byte[] GetBuffer()
|
||||
{
|
||||
return Buf;
|
||||
}
|
||||
|
||||
public virtual int Align(int boundary, byte value)
|
||||
{
|
||||
int n = Align(boundary);
|
||||
int i = n;
|
||||
while (i > 0)
|
||||
{
|
||||
Buf[Index - i] = value;
|
||||
i--;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
public virtual void WriteOctetArray(byte[] b, int i, int l)
|
||||
{
|
||||
Array.Copy(b, i, Buf, Index, l);
|
||||
Advance(l);
|
||||
}
|
||||
|
||||
public virtual void ReadOctetArray(byte[] b, int i, int l)
|
||||
{
|
||||
Array.Copy(Buf, Index, b, i, l);
|
||||
Advance(l);
|
||||
}
|
||||
|
||||
public virtual int GetLength()
|
||||
{
|
||||
return Deferred.Length;
|
||||
}
|
||||
|
||||
public virtual void SetLength(int length)
|
||||
{
|
||||
Deferred.Length = length;
|
||||
}
|
||||
|
||||
public virtual void Advance(int n)
|
||||
{
|
||||
Index += n;
|
||||
if ((Index - Start) > Deferred.Length)
|
||||
{
|
||||
Deferred.Length = Index - Start;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual int Align(int boundary)
|
||||
{
|
||||
int m = boundary - 1;
|
||||
int i = Index - Start;
|
||||
int n = ((i + m) & ~m) - i;
|
||||
Advance(n);
|
||||
return n;
|
||||
}
|
||||
|
||||
public virtual void Enc_ndr_small(int s)
|
||||
{
|
||||
Buf[Index] = unchecked((byte)(s & unchecked(0xFF)));
|
||||
Advance(1);
|
||||
}
|
||||
|
||||
public virtual int Dec_ndr_small()
|
||||
{
|
||||
int val = Buf[Index] & unchecked(0xFF);
|
||||
Advance(1);
|
||||
return val;
|
||||
}
|
||||
|
||||
public virtual void Enc_ndr_short(int s)
|
||||
{
|
||||
Align(2);
|
||||
Encdec.Enc_uint16le((short)s, Buf, Index);
|
||||
Advance(2);
|
||||
}
|
||||
|
||||
public virtual int Dec_ndr_short()
|
||||
{
|
||||
Align(2);
|
||||
int val = Encdec.Dec_uint16le(Buf, Index);
|
||||
Advance(2);
|
||||
return val;
|
||||
}
|
||||
|
||||
public virtual void Enc_ndr_long(int l)
|
||||
{
|
||||
Align(4);
|
||||
Encdec.Enc_uint32le(l, Buf, Index);
|
||||
Advance(4);
|
||||
}
|
||||
|
||||
public virtual int Dec_ndr_long()
|
||||
{
|
||||
Align(4);
|
||||
int val = Encdec.Dec_uint32le(Buf, Index);
|
||||
Advance(4);
|
||||
return val;
|
||||
}
|
||||
|
||||
public virtual void Enc_ndr_hyper(long h)
|
||||
{
|
||||
Align(8);
|
||||
Encdec.Enc_uint64le(h, Buf, Index);
|
||||
Advance(8);
|
||||
}
|
||||
|
||||
public virtual long Dec_ndr_hyper()
|
||||
{
|
||||
Align(8);
|
||||
long val = Encdec.Dec_uint64le(Buf, Index);
|
||||
Advance(8);
|
||||
return val;
|
||||
}
|
||||
|
||||
public virtual void Enc_ndr_string(string s)
|
||||
{
|
||||
Align(4);
|
||||
int i = Index;
|
||||
int len = s.Length;
|
||||
Encdec.Enc_uint32le(len + 1, Buf, i);
|
||||
i += 4;
|
||||
Encdec.Enc_uint32le(0, Buf, i);
|
||||
i += 4;
|
||||
Encdec.Enc_uint32le(len + 1, Buf, i);
|
||||
i += 4;
|
||||
try
|
||||
{
|
||||
Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len
|
||||
* 2);
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
i += len * 2;
|
||||
Buf[i++] = unchecked((byte)('\0'));
|
||||
Buf[i++] = unchecked((byte)('\0'));
|
||||
Advance(i - Index);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public virtual string Dec_ndr_string()
|
||||
{
|
||||
Align(4);
|
||||
int i = Index;
|
||||
string val = null;
|
||||
int len = Encdec.Dec_uint32le(Buf, i);
|
||||
i += 12;
|
||||
if (len != 0)
|
||||
{
|
||||
len--;
|
||||
int size = len * 2;
|
||||
try
|
||||
{
|
||||
if (size < 0 || size > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
val = Runtime.GetStringForBytes(Buf, i, size, "UTF-16LE");
|
||||
i += size + 2;
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
}
|
||||
Advance(i - Index);
|
||||
return val;
|
||||
}
|
||||
|
||||
private int GetDceReferent(object obj)
|
||||
{
|
||||
Entry e;
|
||||
if (Referents == null)
|
||||
{
|
||||
Referents = new Hashtable();
|
||||
Referent = 1;
|
||||
}
|
||||
if ((e = (Entry)Referents.Get(obj)) == null)
|
||||
{
|
||||
e = new Entry();
|
||||
e.Referent = Referent++;
|
||||
e.Obj = obj;
|
||||
Referents.Put(obj, e);
|
||||
}
|
||||
return e.Referent;
|
||||
}
|
||||
|
||||
public virtual void Enc_ndr_referent(object obj, int type)
|
||||
{
|
||||
if (obj == null)
|
||||
{
|
||||
Enc_ndr_long(0);
|
||||
return;
|
||||
}
|
||||
switch (type)
|
||||
{
|
||||
case 1:
|
||||
case 3:
|
||||
{
|
||||
Enc_ndr_long(Runtime.IdentityHashCode(obj));
|
||||
return;
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
Enc_ndr_long(GetDceReferent(obj));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "start=" + Start + ",index=" + Index + ",length=" + GetLength();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
|
||||
public class NdrException : IOException
|
||||
{
|
||||
public static readonly string NoNullRef = "ref pointer cannot be null";
|
||||
|
||||
public static readonly string InvalidConformance = "invalid array conformance";
|
||||
|
||||
public NdrException(string msg) : base(msg)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
public class NdrHyper : NdrObject
|
||||
{
|
||||
public long Value;
|
||||
|
||||
public NdrHyper(long value)
|
||||
{
|
||||
this.Value = value;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_hyper(Value);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
Value = src.Dec_ndr_hyper();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
public class NdrLong : NdrObject
|
||||
{
|
||||
public int Value;
|
||||
|
||||
public NdrLong(int value)
|
||||
{
|
||||
this.Value = value;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_long(Value);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
Value = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
public abstract class NdrObject
|
||||
{
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public abstract void Encode(NdrBuffer dst);
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public abstract void Decode(NdrBuffer src);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
public class NdrShort : NdrObject
|
||||
{
|
||||
public int Value;
|
||||
|
||||
public NdrShort(int value)
|
||||
{
|
||||
this.Value = value & unchecked(0xFF);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_short(Value);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
Value = src.Dec_ndr_short();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc.Ndr
|
||||
{
|
||||
public class NdrSmall : NdrObject
|
||||
{
|
||||
public int Value;
|
||||
|
||||
public NdrSmall(int value)
|
||||
{
|
||||
this.Value = value & unchecked(0xFF);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Enc_ndr_small(Value);
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
Value = src.Dec_ndr_small();
|
||||
}
|
||||
}
|
||||
}
|
||||
285
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs
Normal file
285
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/Rpc.cs
Normal file
@@ -0,0 +1,285 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Dcerpc.Ndr;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public class Rpc
|
||||
{
|
||||
public class UuidT : NdrObject
|
||||
{
|
||||
public int TimeLow;
|
||||
|
||||
public short TimeMid;
|
||||
|
||||
public short TimeHiAndVersion;
|
||||
|
||||
public byte ClockSeqHiAndReserved;
|
||||
|
||||
public byte ClockSeqLow;
|
||||
|
||||
public byte[] Node;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(TimeLow);
|
||||
dst.Enc_ndr_short(TimeMid);
|
||||
dst.Enc_ndr_short(TimeHiAndVersion);
|
||||
dst.Enc_ndr_small(ClockSeqHiAndReserved);
|
||||
dst.Enc_ndr_small(ClockSeqLow);
|
||||
int nodes = 6;
|
||||
int nodei = dst.Index;
|
||||
dst.Advance(1 * nodes);
|
||||
dst = dst.Derive(nodei);
|
||||
for (int i = 0; i < nodes; i++)
|
||||
{
|
||||
dst.Enc_ndr_small(Node[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
TimeLow = src.Dec_ndr_long();
|
||||
TimeMid = (short)src.Dec_ndr_short();
|
||||
TimeHiAndVersion = (short)src.Dec_ndr_short();
|
||||
ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
|
||||
ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
|
||||
int nodes = 6;
|
||||
int nodei = src.Index;
|
||||
src.Advance(1 * nodes);
|
||||
if (Node == null)
|
||||
{
|
||||
if (nodes < 0 || nodes > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Node = new byte[nodes];
|
||||
}
|
||||
src = src.Derive(nodei);
|
||||
for (int i = 0; i < nodes; i++)
|
||||
{
|
||||
Node[i] = unchecked((byte)src.Dec_ndr_small());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class PolicyHandle : NdrObject
|
||||
{
|
||||
public int Type;
|
||||
|
||||
public UuidT Uuid;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_long(Type);
|
||||
dst.Enc_ndr_long(Uuid.TimeLow);
|
||||
dst.Enc_ndr_short(Uuid.TimeMid);
|
||||
dst.Enc_ndr_short(Uuid.TimeHiAndVersion);
|
||||
dst.Enc_ndr_small(Uuid.ClockSeqHiAndReserved);
|
||||
dst.Enc_ndr_small(Uuid.ClockSeqLow);
|
||||
int uuidNodes = 6;
|
||||
int uuidNodei = dst.Index;
|
||||
dst.Advance(1 * uuidNodes);
|
||||
dst = dst.Derive(uuidNodei);
|
||||
for (int i = 0; i < uuidNodes; i++)
|
||||
{
|
||||
dst.Enc_ndr_small(Uuid.Node[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Type = src.Dec_ndr_long();
|
||||
src.Align(4);
|
||||
if (Uuid == null)
|
||||
{
|
||||
Uuid = new UuidT();
|
||||
}
|
||||
Uuid.TimeLow = src.Dec_ndr_long();
|
||||
Uuid.TimeMid = (short)src.Dec_ndr_short();
|
||||
Uuid.TimeHiAndVersion = (short)src.Dec_ndr_short();
|
||||
Uuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
|
||||
Uuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
|
||||
int uuidNodes = 6;
|
||||
int uuidNodei = src.Index;
|
||||
src.Advance(1 * uuidNodes);
|
||||
if (Uuid.Node == null)
|
||||
{
|
||||
if (uuidNodes < 0 || uuidNodes > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Uuid.Node = new byte[uuidNodes];
|
||||
}
|
||||
src = src.Derive(uuidNodei);
|
||||
for (int i = 0; i < uuidNodes; i++)
|
||||
{
|
||||
Uuid.Node[i] = unchecked((byte)src.Dec_ndr_small());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Unicode_string : NdrObject
|
||||
{
|
||||
public short Length;
|
||||
|
||||
public short MaximumLength;
|
||||
|
||||
public short[] Buffer;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
dst.Enc_ndr_short(Length);
|
||||
dst.Enc_ndr_short(MaximumLength);
|
||||
dst.Enc_ndr_referent(Buffer, 1);
|
||||
if (Buffer != null)
|
||||
{
|
||||
dst = dst.Deferred;
|
||||
int bufferl = Length / 2;
|
||||
int buffers = MaximumLength / 2;
|
||||
dst.Enc_ndr_long(buffers);
|
||||
dst.Enc_ndr_long(0);
|
||||
dst.Enc_ndr_long(bufferl);
|
||||
int bufferi = dst.Index;
|
||||
dst.Advance(2 * bufferl);
|
||||
dst = dst.Derive(bufferi);
|
||||
for (int i = 0; i < bufferl; i++)
|
||||
{
|
||||
dst.Enc_ndr_short(Buffer[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
Length = (short)src.Dec_ndr_short();
|
||||
MaximumLength = (short)src.Dec_ndr_short();
|
||||
int bufferp = src.Dec_ndr_long();
|
||||
if (bufferp != 0)
|
||||
{
|
||||
src = src.Deferred;
|
||||
int buffers = src.Dec_ndr_long();
|
||||
src.Dec_ndr_long();
|
||||
int bufferl = src.Dec_ndr_long();
|
||||
int bufferi = src.Index;
|
||||
src.Advance(2 * bufferl);
|
||||
if (Buffer == null)
|
||||
{
|
||||
if (buffers < 0 || buffers > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
Buffer = new short[buffers];
|
||||
}
|
||||
src = src.Derive(bufferi);
|
||||
for (int i = 0; i < bufferl; i++)
|
||||
{
|
||||
Buffer[i] = (short)src.Dec_ndr_short();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SidT : NdrObject
|
||||
{
|
||||
public byte Revision;
|
||||
|
||||
public byte SubAuthorityCount;
|
||||
|
||||
public byte[] IdentifierAuthority;
|
||||
|
||||
public int[] SubAuthority;
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Encode(NdrBuffer dst)
|
||||
{
|
||||
dst.Align(4);
|
||||
int subAuthoritys = SubAuthorityCount;
|
||||
dst.Enc_ndr_long(subAuthoritys);
|
||||
dst.Enc_ndr_small(Revision);
|
||||
dst.Enc_ndr_small(SubAuthorityCount);
|
||||
int identifierAuthoritys = 6;
|
||||
int identifierAuthorityi = dst.Index;
|
||||
dst.Advance(1 * identifierAuthoritys);
|
||||
int subAuthorityi = dst.Index;
|
||||
dst.Advance(4 * subAuthoritys);
|
||||
dst = dst.Derive(identifierAuthorityi);
|
||||
for (int i = 0; i < identifierAuthoritys; i++)
|
||||
{
|
||||
dst.Enc_ndr_small(IdentifierAuthority[i]);
|
||||
}
|
||||
dst = dst.Derive(subAuthorityi);
|
||||
for (int i1 = 0; i1 < subAuthoritys; i1++)
|
||||
{
|
||||
dst.Enc_ndr_long(SubAuthority[i1]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
|
||||
public override void Decode(NdrBuffer src)
|
||||
{
|
||||
src.Align(4);
|
||||
int subAuthoritys = src.Dec_ndr_long();
|
||||
Revision = unchecked((byte)src.Dec_ndr_small());
|
||||
SubAuthorityCount = unchecked((byte)src.Dec_ndr_small());
|
||||
int identifierAuthoritys = 6;
|
||||
int identifierAuthorityi = src.Index;
|
||||
src.Advance(1 * identifierAuthoritys);
|
||||
int subAuthorityi = src.Index;
|
||||
src.Advance(4 * subAuthoritys);
|
||||
if (IdentifierAuthority == null)
|
||||
{
|
||||
if (identifierAuthoritys < 0 || identifierAuthoritys > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
IdentifierAuthority = new byte[identifierAuthoritys];
|
||||
}
|
||||
src = src.Derive(identifierAuthorityi);
|
||||
for (int i = 0; i < identifierAuthoritys; i++)
|
||||
{
|
||||
IdentifierAuthority[i] = unchecked((byte)src.Dec_ndr_small());
|
||||
}
|
||||
if (SubAuthority == null)
|
||||
{
|
||||
if (subAuthoritys < 0 || subAuthoritys > unchecked(0xFFFF))
|
||||
{
|
||||
throw new NdrException(NdrException.InvalidConformance);
|
||||
}
|
||||
SubAuthority = new int[subAuthoritys];
|
||||
}
|
||||
src = src.Derive(subAuthorityi);
|
||||
for (int i1 = 0; i1 < subAuthoritys; i1++)
|
||||
{
|
||||
SubAuthority[i1] = src.Dec_ndr_long();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
148
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs
Normal file
148
Emby.Server.Implementations/IO/SharpCifs/Dcerpc/UUID.cs
Normal file
@@ -0,0 +1,148 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public class Uuid : Rpc.UuidT
|
||||
{
|
||||
public static int Hex_to_bin(char[] arr, int offset, int length)
|
||||
{
|
||||
int value = 0;
|
||||
int ai;
|
||||
int count;
|
||||
count = 0;
|
||||
for (ai = offset; ai < arr.Length && count < length; ai++)
|
||||
{
|
||||
value <<= 4;
|
||||
switch (arr[ai])
|
||||
{
|
||||
case '0':
|
||||
case '1':
|
||||
case '2':
|
||||
case '3':
|
||||
case '4':
|
||||
case '5':
|
||||
case '6':
|
||||
case '7':
|
||||
case '8':
|
||||
case '9':
|
||||
{
|
||||
value += arr[ai] - '0';
|
||||
break;
|
||||
}
|
||||
|
||||
case 'A':
|
||||
case 'B':
|
||||
case 'C':
|
||||
case 'D':
|
||||
case 'E':
|
||||
case 'F':
|
||||
{
|
||||
value += 10 + (arr[ai] - 'A');
|
||||
break;
|
||||
}
|
||||
|
||||
case 'a':
|
||||
case 'b':
|
||||
case 'c':
|
||||
case 'd':
|
||||
case 'e':
|
||||
case 'f':
|
||||
{
|
||||
value += 10 + (arr[ai] - 'a');
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
throw new ArgumentException(new string(arr, offset, length));
|
||||
}
|
||||
}
|
||||
count++;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
internal static readonly char[] Hexchars = { '0', '1', '2', '3', '4',
|
||||
'5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
|
||||
|
||||
public static string Bin_to_hex(int value, int length)
|
||||
{
|
||||
char[] arr = new char[length];
|
||||
int ai = arr.Length;
|
||||
while (ai-- > 0)
|
||||
{
|
||||
arr[ai] = Hexchars[value & unchecked(0xF)];
|
||||
value = (int)(((uint)value) >> 4);
|
||||
}
|
||||
return new string(arr);
|
||||
}
|
||||
|
||||
private static byte B(int i)
|
||||
{
|
||||
return unchecked((byte)(i & unchecked(0xFF)));
|
||||
}
|
||||
|
||||
private static short S(int i)
|
||||
{
|
||||
return (short)(i & unchecked(0xFFFF));
|
||||
}
|
||||
|
||||
public Uuid(Rpc.UuidT uuid)
|
||||
{
|
||||
TimeLow = uuid.TimeLow;
|
||||
TimeMid = uuid.TimeMid;
|
||||
TimeHiAndVersion = uuid.TimeHiAndVersion;
|
||||
ClockSeqHiAndReserved = uuid.ClockSeqHiAndReserved;
|
||||
ClockSeqLow = uuid.ClockSeqLow;
|
||||
Node = new byte[6];
|
||||
Node[0] = uuid.Node[0];
|
||||
Node[1] = uuid.Node[1];
|
||||
Node[2] = uuid.Node[2];
|
||||
Node[3] = uuid.Node[3];
|
||||
Node[4] = uuid.Node[4];
|
||||
Node[5] = uuid.Node[5];
|
||||
}
|
||||
|
||||
public Uuid(string str)
|
||||
{
|
||||
char[] arr = str.ToCharArray();
|
||||
TimeLow = Hex_to_bin(arr, 0, 8);
|
||||
TimeMid = S(Hex_to_bin(arr, 9, 4));
|
||||
TimeHiAndVersion = S(Hex_to_bin(arr, 14, 4));
|
||||
ClockSeqHiAndReserved = B(Hex_to_bin(arr, 19, 2));
|
||||
ClockSeqLow = B(Hex_to_bin(arr, 21, 2));
|
||||
Node = new byte[6];
|
||||
Node[0] = B(Hex_to_bin(arr, 24, 2));
|
||||
Node[1] = B(Hex_to_bin(arr, 26, 2));
|
||||
Node[2] = B(Hex_to_bin(arr, 28, 2));
|
||||
Node[3] = B(Hex_to_bin(arr, 30, 2));
|
||||
Node[4] = B(Hex_to_bin(arr, 32, 2));
|
||||
Node[5] = B(Hex_to_bin(arr, 34, 2));
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Bin_to_hex(TimeLow, 8) + '-' + Bin_to_hex(TimeMid, 4) + '-' + Bin_to_hex
|
||||
(TimeHiAndVersion, 4) + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) + Bin_to_hex
|
||||
(ClockSeqLow, 2) + '-' + Bin_to_hex(Node[0], 2) + Bin_to_hex(Node[1], 2) + Bin_to_hex
|
||||
(Node[2], 2) + Bin_to_hex(Node[3], 2) + Bin_to_hex(Node[4], 2) + Bin_to_hex(Node
|
||||
[5], 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Dcerpc
|
||||
{
|
||||
public class UnicodeString : Rpc.Unicode_string
|
||||
{
|
||||
internal bool Zterm;
|
||||
|
||||
public UnicodeString(bool zterm)
|
||||
{
|
||||
this.Zterm = zterm;
|
||||
}
|
||||
|
||||
public UnicodeString(Rpc.Unicode_string rus, bool zterm)
|
||||
{
|
||||
Length = rus.Length;
|
||||
MaximumLength = rus.MaximumLength;
|
||||
Buffer = rus.Buffer;
|
||||
this.Zterm = zterm;
|
||||
}
|
||||
|
||||
public UnicodeString(string str, bool zterm)
|
||||
{
|
||||
this.Zterm = zterm;
|
||||
int len = str.Length;
|
||||
int zt = zterm ? 1 : 0;
|
||||
Length = MaximumLength = (short)((len + zt) * 2);
|
||||
Buffer = new short[len + zt];
|
||||
int i;
|
||||
for (i = 0; i < len; i++)
|
||||
{
|
||||
Buffer[i] = (short)str[i];
|
||||
}
|
||||
if (zterm)
|
||||
{
|
||||
Buffer[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
int len = Length / 2 - (Zterm ? 1 : 0);
|
||||
char[] ca = new char[len];
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
ca[i] = (char)Buffer[i];
|
||||
}
|
||||
return new string(ca, 0, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
202
Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs
Normal file
202
Emby.Server.Implementations/IO/SharpCifs/Netbios/Lmhosts.cs
Normal file
@@ -0,0 +1,202 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
using SharpCifs.Smb;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
public class Lmhosts
|
||||
{
|
||||
private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts"
|
||||
);
|
||||
|
||||
private static readonly Hashtable Tab = new Hashtable();
|
||||
|
||||
private static long _lastModified = 1L;
|
||||
|
||||
private static int _alt;
|
||||
|
||||
private static LogStream _log = LogStream.GetInstance();
|
||||
|
||||
/// <summary>
|
||||
/// This is really just for
|
||||
/// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
|
||||
/// . It does
|
||||
/// not throw an
|
||||
/// <see cref="UnknownHostException">Sharpen.UnknownHostException</see>
|
||||
/// because this
|
||||
/// is queried frequently and exceptions would be rather costly to
|
||||
/// throw on a regular basis here.
|
||||
/// </summary>
|
||||
public static NbtAddress GetByName(string host)
|
||||
{
|
||||
lock (typeof(Lmhosts))
|
||||
{
|
||||
return GetByName(new Name(host, 0x20, null));
|
||||
}
|
||||
}
|
||||
|
||||
internal static NbtAddress GetByName(Name name)
|
||||
{
|
||||
lock (typeof(Lmhosts))
|
||||
{
|
||||
NbtAddress result = null;
|
||||
try
|
||||
{
|
||||
if (Filename != null)
|
||||
{
|
||||
FilePath f = new FilePath(Filename);
|
||||
long lm;
|
||||
if ((lm = f.LastModified()) > _lastModified)
|
||||
{
|
||||
_lastModified = lm;
|
||||
Tab.Clear();
|
||||
_alt = 0;
|
||||
|
||||
//path -> fileStream
|
||||
//Populate(new FileReader(f));
|
||||
Populate(new FileReader(new FileStream(f, FileMode.Open)));
|
||||
}
|
||||
result = (NbtAddress)Tab[name];
|
||||
}
|
||||
}
|
||||
catch (FileNotFoundException fnfe)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
_log.WriteLine("lmhosts file: " + Filename);
|
||||
Runtime.PrintStackTrace(fnfe, _log);
|
||||
}
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static void Populate(StreamReader r)
|
||||
{
|
||||
string line;
|
||||
BufferedReader br = new BufferedReader((InputStreamReader)r);
|
||||
while ((line = br.ReadLine()) != null)
|
||||
{
|
||||
line = line.ToUpper().Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
}
|
||||
else
|
||||
{
|
||||
if (line[0] == '#')
|
||||
{
|
||||
if (line.StartsWith("#INCLUDE "))
|
||||
{
|
||||
line = Runtime.Substring(line, line.IndexOf('\\'));
|
||||
string url = "smb:" + line.Replace('\\', '/');
|
||||
if (_alt > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
Populate(new InputStreamReader(new SmbFileInputStream(url)));
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
_log.WriteLine("lmhosts URL: " + url);
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
continue;
|
||||
}
|
||||
_alt--;
|
||||
while ((line = br.ReadLine()) != null)
|
||||
{
|
||||
line = line.ToUpper().Trim();
|
||||
if (line.StartsWith("#END_ALTERNATE"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Populate(new InputStreamReader(new SmbFileInputStream(url)));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (line.StartsWith("#BEGIN_ALTERNATE"))
|
||||
{
|
||||
_alt++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
|
||||
{
|
||||
_alt--;
|
||||
throw new IOException("no lmhosts alternate includes loaded");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (char.IsDigit(line[0]))
|
||||
{
|
||||
char[] data = line.ToCharArray();
|
||||
int ip;
|
||||
int i;
|
||||
int j;
|
||||
Name name;
|
||||
NbtAddress addr;
|
||||
char c;
|
||||
c = '.';
|
||||
ip = i = 0;
|
||||
for (; i < data.Length && c == '.'; i++)
|
||||
{
|
||||
int b = unchecked(0x00);
|
||||
for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
|
||||
{
|
||||
b = b * 10 + c - '0';
|
||||
}
|
||||
ip = (ip << 8) + b;
|
||||
}
|
||||
while (i < data.Length && char.IsWhiteSpace(data[i]))
|
||||
{
|
||||
i++;
|
||||
}
|
||||
j = i;
|
||||
while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
|
||||
{
|
||||
j++;
|
||||
}
|
||||
name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null
|
||||
);
|
||||
addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
|
||||
, NbtAddress.UnknownMacAddress);
|
||||
Tab.Put(name, addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
269
Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs
Normal file
269
Emby.Server.Implementations/IO/SharpCifs/Netbios/Name.cs
Normal file
@@ -0,0 +1,269 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.Text;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
public class Name
|
||||
{
|
||||
private const int TypeOffset = 31;
|
||||
|
||||
private const int ScopeOffset = 33;
|
||||
|
||||
private static readonly string DefaultScope = Config.GetProperty("jcifs.netbios.scope"
|
||||
);
|
||||
|
||||
internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding"
|
||||
, Runtime.GetProperty("file.encoding"));
|
||||
|
||||
public string name;
|
||||
|
||||
public string Scope;
|
||||
|
||||
public int HexCode;
|
||||
|
||||
internal int SrcHashCode;
|
||||
|
||||
public Name()
|
||||
{
|
||||
}
|
||||
|
||||
public Name(string name, int hexCode, string scope)
|
||||
{
|
||||
if (name.Length > 15)
|
||||
{
|
||||
name = Runtime.Substring(name, 0, 15);
|
||||
}
|
||||
this.name = name.ToUpper();
|
||||
this.HexCode = hexCode;
|
||||
this.Scope = !string.IsNullOrEmpty(scope) ? scope : DefaultScope;
|
||||
SrcHashCode = 0;
|
||||
}
|
||||
|
||||
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
// write 0x20 in first byte
|
||||
dst[dstIndex] = unchecked(0x20);
|
||||
// write name
|
||||
try
|
||||
{
|
||||
byte[] tmp = Runtime.GetBytesForString(name, OemEncoding
|
||||
);
|
||||
int i;
|
||||
for (i = 0; i < tmp.Length; i++)
|
||||
{
|
||||
dst[dstIndex + (2 * i + 1)] = unchecked((byte)(((tmp[i] & unchecked(0xF0))
|
||||
>> 4) + unchecked(0x41)));
|
||||
dst[dstIndex + (2 * i + 2)] = unchecked((byte)((tmp[i] & unchecked(0x0F))
|
||||
+ unchecked(0x41)));
|
||||
}
|
||||
for (; i < 15; i++)
|
||||
{
|
||||
dst[dstIndex + (2 * i + 1)] = unchecked(unchecked(0x43));
|
||||
dst[dstIndex + (2 * i + 2)] = unchecked(unchecked(0x41));
|
||||
}
|
||||
dst[dstIndex + TypeOffset] = unchecked((byte)(((HexCode & unchecked(0xF0)
|
||||
) >> 4) + unchecked(0x41)));
|
||||
dst[dstIndex + TypeOffset + 1] = unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41)));
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
return ScopeOffset + WriteScopeWireFormat(dst, dstIndex + ScopeOffset);
|
||||
}
|
||||
|
||||
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
byte[] tmp = new byte[ScopeOffset];
|
||||
int length = 15;
|
||||
for (int i = 0; i < 15; i++)
|
||||
{
|
||||
tmp[i] = unchecked((byte)(((src[srcIndex + (2 * i + 1)] & unchecked(0xFF))
|
||||
- unchecked(0x41)) << 4));
|
||||
tmp[i] |= unchecked((byte)(((src[srcIndex + (2 * i + 2)] & unchecked(0xFF)
|
||||
) - unchecked(0x41)) & unchecked(0x0F)));
|
||||
if (tmp[i] != unchecked((byte)' '))
|
||||
{
|
||||
length = i + 1;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
name = Runtime.GetStringForBytes(tmp, 0, length, OemEncoding
|
||||
);
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4;
|
||||
HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(
|
||||
0x41)) & unchecked(0x0F);
|
||||
return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
|
||||
}
|
||||
|
||||
internal int ReadWireFormatDos(byte[] src, int srcIndex)
|
||||
{
|
||||
|
||||
int length = 15;
|
||||
byte[] tmp = new byte[length];
|
||||
|
||||
Array.Copy(src, srcIndex, tmp, 0, length);
|
||||
|
||||
try
|
||||
{
|
||||
name = Runtime.GetStringForBytes(tmp, 0, length).Trim();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
HexCode = src[srcIndex + length];
|
||||
|
||||
return length + 1;
|
||||
}
|
||||
|
||||
|
||||
internal virtual int WriteScopeWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
if (Scope == null)
|
||||
{
|
||||
dst[dstIndex] = unchecked(unchecked(0x00));
|
||||
return 1;
|
||||
}
|
||||
// copy new scope in
|
||||
dst[dstIndex++] = unchecked((byte)('.'));
|
||||
try
|
||||
{
|
||||
Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding
|
||||
), 0, dst, dstIndex, Scope.Length);
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
dstIndex += Scope.Length;
|
||||
dst[dstIndex++] = unchecked(unchecked(0x00));
|
||||
// now go over scope backwards converting '.' to label length
|
||||
int i = dstIndex - 2;
|
||||
int e = i - Scope.Length;
|
||||
int c = 0;
|
||||
do
|
||||
{
|
||||
if (dst[i] == '.')
|
||||
{
|
||||
dst[i] = unchecked((byte)c);
|
||||
c = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
c++;
|
||||
}
|
||||
}
|
||||
while (i-- > e);
|
||||
return Scope.Length + 2;
|
||||
}
|
||||
|
||||
internal virtual int ReadScopeWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
int start = srcIndex;
|
||||
int n;
|
||||
StringBuilder sb;
|
||||
if ((n = src[srcIndex++] & unchecked(0xFF)) == 0)
|
||||
{
|
||||
Scope = null;
|
||||
return 1;
|
||||
}
|
||||
try
|
||||
{
|
||||
sb = new StringBuilder(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
|
||||
srcIndex += n;
|
||||
while ((n = src[srcIndex++] & unchecked(0xFF)) != 0)
|
||||
{
|
||||
sb.Append('.').Append(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
|
||||
srcIndex += n;
|
||||
}
|
||||
Scope = sb.ToString();
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
return srcIndex - start;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
int result;
|
||||
result = name.GetHashCode();
|
||||
result += 65599 * HexCode;
|
||||
result += 65599 * SrcHashCode;
|
||||
if (Scope != null && Scope.Length != 0)
|
||||
{
|
||||
result += Scope.GetHashCode();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
Name n;
|
||||
if (!(obj is Name))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
n = (Name)obj;
|
||||
if (Scope == null && n.Scope == null)
|
||||
{
|
||||
return name.Equals(n.name) && HexCode == n.HexCode;
|
||||
}
|
||||
return name.Equals(n.name) && HexCode == n.HexCode && Scope.Equals(n.Scope);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
//return "";
|
||||
|
||||
string n = name;
|
||||
// fix MSBROWSE name
|
||||
if (n == null)
|
||||
{
|
||||
n = "null";
|
||||
}
|
||||
else
|
||||
{
|
||||
if (n[0] == unchecked(0x01))
|
||||
{
|
||||
char[] c = n.ToCharArray();
|
||||
c[0] = '.';
|
||||
c[1] = '.';
|
||||
c[14] = '.';
|
||||
n = new string(c);
|
||||
}
|
||||
}
|
||||
sb.Append(n).Append("<").Append(Hexdump.ToHexString(HexCode, 2)).Append(">");
|
||||
if (Scope != null)
|
||||
{
|
||||
sb.Append(".").Append(Scope);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal class NameQueryRequest : NameServicePacket
|
||||
{
|
||||
internal NameQueryRequest(Name name)
|
||||
{
|
||||
QuestionName = name;
|
||||
QuestionType = Nb;
|
||||
}
|
||||
|
||||
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return WriteQuestionSectionWireFormat(dst, dstIndex);
|
||||
}
|
||||
|
||||
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
return ReadQuestionSectionWireFormat(src, srcIndex);
|
||||
}
|
||||
|
||||
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NameQueryRequest[" + base.ToString() + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal class NameQueryResponse : NameServicePacket
|
||||
{
|
||||
public NameQueryResponse()
|
||||
{
|
||||
RecordName = new Name();
|
||||
}
|
||||
|
||||
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
return ReadResourceRecordWireFormat(src, srcIndex);
|
||||
}
|
||||
|
||||
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
if (ResultCode != 0 || OpCode != Query)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
bool groupName = ((src[srcIndex] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
|
||||
int nodeType = (src[srcIndex] & unchecked(0x60)) >> 5;
|
||||
srcIndex += 2;
|
||||
int address = ReadInt4(src, srcIndex);
|
||||
if (address != 0)
|
||||
{
|
||||
AddrEntry[AddrIndex] = new NbtAddress(RecordName, address, groupName, nodeType);
|
||||
}
|
||||
else
|
||||
{
|
||||
AddrEntry[AddrIndex] = null;
|
||||
}
|
||||
return 6;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry
|
||||
+ "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
using Thread = SharpCifs.Util.Sharpen.Thread;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal class NameServiceClient : IRunnable
|
||||
{
|
||||
internal const int DefaultSoTimeout = 5000;
|
||||
|
||||
internal const int DefaultRcvBufSize = 576;
|
||||
|
||||
internal const int DefaultSndBufSize = 576;
|
||||
|
||||
internal const int NameServiceUdpPort = 137;
|
||||
|
||||
internal const int DefaultRetryCount = 2;
|
||||
|
||||
internal const int DefaultRetryTimeout = 3000;
|
||||
|
||||
internal const int ResolverLmhosts = 1;
|
||||
|
||||
internal const int ResolverBcast = 2;
|
||||
|
||||
internal const int ResolverWins = 3;
|
||||
|
||||
private static readonly int SndBufSize = Config.GetInt("jcifs.netbios.snd_buf_size"
|
||||
, DefaultSndBufSize);
|
||||
|
||||
private static readonly int RcvBufSize = Config.GetInt("jcifs.netbios.rcv_buf_size"
|
||||
, DefaultRcvBufSize);
|
||||
|
||||
private static readonly int SoTimeout = Config.GetInt("jcifs.netbios.soTimeout",
|
||||
DefaultSoTimeout);
|
||||
|
||||
private static readonly int RetryCount = Config.GetInt("jcifs.netbios.retryCount"
|
||||
, DefaultRetryCount);
|
||||
|
||||
private static readonly int RetryTimeout = Config.GetInt("jcifs.netbios.retryTimeout"
|
||||
, DefaultRetryTimeout);
|
||||
|
||||
private static readonly int Lport = Config.GetInt("jcifs.netbios.lport", 137);
|
||||
|
||||
private static readonly IPAddress Laddr = Config.GetInetAddress("jcifs.netbios.laddr"
|
||||
, null);
|
||||
|
||||
private static readonly string Ro = Config.GetProperty("jcifs.resolveOrder");
|
||||
|
||||
private static LogStream _log = LogStream.GetInstance();
|
||||
|
||||
private readonly object _lock = new object();
|
||||
|
||||
private int _lport;
|
||||
|
||||
private int _closeTimeout;
|
||||
|
||||
private byte[] _sndBuf;
|
||||
|
||||
private byte[] _rcvBuf;
|
||||
|
||||
private SocketEx _socket;
|
||||
|
||||
private Hashtable _responseTable = new Hashtable();
|
||||
|
||||
private Thread _thread;
|
||||
|
||||
private int _nextNameTrnId;
|
||||
|
||||
private int[] _resolveOrder;
|
||||
|
||||
private bool _waitResponse = true;
|
||||
|
||||
private AutoResetEvent _autoResetWaitReceive;
|
||||
|
||||
internal IPAddress laddr;
|
||||
|
||||
internal IPAddress Baddr;
|
||||
|
||||
public NameServiceClient()
|
||||
: this(Lport, Laddr)
|
||||
{
|
||||
}
|
||||
|
||||
internal NameServiceClient(int lport, IPAddress laddr)
|
||||
{
|
||||
this._lport = lport;
|
||||
|
||||
this.laddr = laddr
|
||||
?? Config.GetLocalHost()
|
||||
?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault();
|
||||
|
||||
try
|
||||
{
|
||||
Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
}
|
||||
|
||||
_sndBuf = new byte[SndBufSize];
|
||||
_rcvBuf = new byte[RcvBufSize];
|
||||
|
||||
|
||||
if (string.IsNullOrEmpty(Ro))
|
||||
{
|
||||
if (NbtAddress.GetWinsAddress() == null)
|
||||
{
|
||||
_resolveOrder = new int[2];
|
||||
_resolveOrder[0] = ResolverLmhosts;
|
||||
_resolveOrder[1] = ResolverBcast;
|
||||
}
|
||||
else
|
||||
{
|
||||
_resolveOrder = new int[3];
|
||||
_resolveOrder[0] = ResolverLmhosts;
|
||||
_resolveOrder[1] = ResolverWins;
|
||||
_resolveOrder[2] = ResolverBcast;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int[] tmp = new int[3];
|
||||
StringTokenizer st = new StringTokenizer(Ro, ",");
|
||||
int i = 0;
|
||||
while (st.HasMoreTokens())
|
||||
{
|
||||
string s = st.NextToken().Trim();
|
||||
if (Runtime.EqualsIgnoreCase(s, "LMHOSTS"))
|
||||
{
|
||||
tmp[i++] = ResolverLmhosts;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Runtime.EqualsIgnoreCase(s, "WINS"))
|
||||
{
|
||||
if (NbtAddress.GetWinsAddress() == null)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
_log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
tmp[i++] = ResolverWins;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Runtime.EqualsIgnoreCase(s, "BCAST"))
|
||||
{
|
||||
tmp[i++] = ResolverBcast;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Runtime.EqualsIgnoreCase(s, "DNS"))
|
||||
{
|
||||
}
|
||||
else
|
||||
{
|
||||
// skip
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
_log.WriteLine("unknown resolver method: " + s);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_resolveOrder = new int[i];
|
||||
Array.Copy(tmp, 0, _resolveOrder, 0, i);
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual int GetNextNameTrnId()
|
||||
{
|
||||
if ((++_nextNameTrnId & unchecked(0xFFFF)) == 0)
|
||||
{
|
||||
_nextNameTrnId = 1;
|
||||
}
|
||||
return _nextNameTrnId;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal virtual void EnsureOpen(int timeout)
|
||||
{
|
||||
_closeTimeout = 0;
|
||||
if (SoTimeout != 0)
|
||||
{
|
||||
_closeTimeout = Math.Max(SoTimeout, timeout);
|
||||
}
|
||||
// If socket is still good, the new closeTimeout will
|
||||
// be ignored; see tryClose comment.
|
||||
if (_socket == null)
|
||||
{
|
||||
_socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
|
||||
//IPAddress.`Address` property deleted
|
||||
//_socket.Bind(new IPEndPoint(laddr.Address, _lport));
|
||||
_socket.Bind(new IPEndPoint(laddr, _lport));
|
||||
|
||||
if (_waitResponse)
|
||||
{
|
||||
_thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient");
|
||||
_thread.SetDaemon(true);
|
||||
_thread.Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual void TryClose()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_socket != null)
|
||||
{
|
||||
//Socket.`Close` method deleted
|
||||
//_socket.Close();
|
||||
_socket.Dispose();
|
||||
_socket = null;
|
||||
}
|
||||
_thread = null;
|
||||
|
||||
if (_waitResponse)
|
||||
{
|
||||
_responseTable.Clear();
|
||||
} else
|
||||
{
|
||||
_autoResetWaitReceive.Set();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Run()
|
||||
{
|
||||
int nameTrnId;
|
||||
NameServicePacket response;
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
while (_thread == Thread.CurrentThread())
|
||||
{
|
||||
_socket.SoTimeOut = _closeTimeout;
|
||||
|
||||
int len = _socket.Receive(_rcvBuf, 0, RcvBufSize);
|
||||
|
||||
if (_log.Level > 3)
|
||||
{
|
||||
_log.WriteLine("NetBIOS: new data read from socket");
|
||||
}
|
||||
nameTrnId = NameServicePacket.ReadNameTrnId(_rcvBuf, 0);
|
||||
response = (NameServicePacket)_responseTable.Get(nameTrnId);
|
||||
|
||||
|
||||
if (response == null || response.Received)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
lock (response)
|
||||
{
|
||||
response.ReadWireFormat(_rcvBuf, 0);
|
||||
|
||||
if (_log.Level > 3)
|
||||
{
|
||||
_log.WriteLine(response);
|
||||
Hexdump.ToHexdump(_log, _rcvBuf, 0, len);
|
||||
}
|
||||
|
||||
if (response.IsResponse)
|
||||
{
|
||||
response.Received = true;
|
||||
|
||||
Runtime.Notify(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (TimeoutException) { }
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_log.Level > 2)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, _log);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryClose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal virtual void Send(NameServicePacket request, NameServicePacket response,
|
||||
int timeout)
|
||||
{
|
||||
int nid = 0;
|
||||
int max = NbtAddress.Nbns.Length;
|
||||
if (max == 0)
|
||||
{
|
||||
max = 1;
|
||||
}
|
||||
|
||||
lock (response)
|
||||
{
|
||||
|
||||
while (max-- > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
request.NameTrnId = GetNextNameTrnId();
|
||||
nid = request.NameTrnId;
|
||||
response.Received = false;
|
||||
_responseTable.Put(nid, response);
|
||||
EnsureOpen(timeout + 1000);
|
||||
int requestLenght = request.WriteWireFormat(_sndBuf, 0);
|
||||
_socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
|
||||
if (_log.Level > 3)
|
||||
{
|
||||
_log.WriteLine(request);
|
||||
Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
|
||||
}
|
||||
|
||||
}
|
||||
if (_waitResponse)
|
||||
{
|
||||
long start = Runtime.CurrentTimeMillis();
|
||||
while (timeout > 0)
|
||||
{
|
||||
Runtime.Wait(response, timeout);
|
||||
if (response.Received && request.QuestionType == response.RecordType)
|
||||
{
|
||||
return;
|
||||
}
|
||||
response.Received = false;
|
||||
timeout -= (int)(Runtime.CurrentTimeMillis() - start);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ie)
|
||||
{
|
||||
throw new IOException(ie.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
//Sharpen.Collections.Remove(responseTable, nid);
|
||||
if (_waitResponse)
|
||||
{
|
||||
_responseTable.Remove(nid);
|
||||
}
|
||||
}
|
||||
if (_waitResponse)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (NbtAddress.IsWins(request.Addr) == false)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (request.Addr == NbtAddress.GetWinsAddress())
|
||||
{
|
||||
NbtAddress.SwitchWins();
|
||||
}
|
||||
request.Addr = NbtAddress.GetWinsAddress();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr)
|
||||
{
|
||||
int n;
|
||||
NameQueryRequest request = new NameQueryRequest(name);
|
||||
NameQueryResponse response = new NameQueryResponse();
|
||||
request.Addr = addr ?? NbtAddress.GetWinsAddress();
|
||||
request.IsBroadcast = request.Addr == null;
|
||||
if (request.IsBroadcast)
|
||||
{
|
||||
request.Addr = Baddr;
|
||||
n = RetryCount;
|
||||
}
|
||||
else
|
||||
{
|
||||
request.IsBroadcast = false;
|
||||
n = 1;
|
||||
}
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
Send(request, response, RetryTimeout);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
throw new UnknownHostException(ioe);
|
||||
}
|
||||
if (response.Received && response.ResultCode == 0)
|
||||
{
|
||||
return response.AddrEntry;
|
||||
}
|
||||
}
|
||||
while (--n > 0 && request.IsBroadcast);
|
||||
throw new UnknownHostException();
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
internal virtual NbtAddress GetByName(Name name, IPAddress addr)
|
||||
{
|
||||
int n;
|
||||
|
||||
NameQueryRequest request = new NameQueryRequest(name);
|
||||
NameQueryResponse response = new NameQueryResponse();
|
||||
if (addr != null)
|
||||
{
|
||||
request.Addr = addr;
|
||||
request.IsBroadcast = (addr.GetAddressBytes()[3] == unchecked(unchecked(0xFF)));
|
||||
n = RetryCount;
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
Send(request, response, RetryTimeout);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
throw new UnknownHostException(ioe);
|
||||
}
|
||||
if (response.Received && response.ResultCode == 0
|
||||
&& response.IsResponse)
|
||||
{
|
||||
int last = response.AddrEntry.Length - 1;
|
||||
response.AddrEntry[last].HostName.SrcHashCode = addr.GetHashCode();
|
||||
return response.AddrEntry[last];
|
||||
}
|
||||
}
|
||||
while (--n > 0 && request.IsBroadcast);
|
||||
throw new UnknownHostException();
|
||||
}
|
||||
for (int i = 0; i < _resolveOrder.Length; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (_resolveOrder[i])
|
||||
{
|
||||
case ResolverLmhosts:
|
||||
{
|
||||
NbtAddress ans = Lmhosts.GetByName(name);
|
||||
if (ans != null)
|
||||
{
|
||||
ans.HostName.SrcHashCode = 0;
|
||||
// just has to be different
|
||||
// from other methods
|
||||
return ans;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case ResolverWins:
|
||||
case ResolverBcast:
|
||||
{
|
||||
if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName
|
||||
&& name.HexCode != unchecked(0x1d))
|
||||
{
|
||||
request.Addr = NbtAddress.GetWinsAddress();
|
||||
request.IsBroadcast = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
request.Addr = Baddr;
|
||||
request.IsBroadcast = true;
|
||||
}
|
||||
n = RetryCount;
|
||||
while (n-- > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
Send(request, response, RetryTimeout);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
throw new UnknownHostException(ioe);
|
||||
}
|
||||
if (response.Received && response.ResultCode == 0
|
||||
&& response.IsResponse)
|
||||
{
|
||||
|
||||
response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode();
|
||||
return response.AddrEntry[0];
|
||||
}
|
||||
if (_resolveOrder[i] == ResolverWins)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
throw new UnknownHostException();
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
|
||||
{
|
||||
int n;
|
||||
int srcHashCode;
|
||||
NodeStatusRequest request;
|
||||
NodeStatusResponse response;
|
||||
response = new NodeStatusResponse(addr);
|
||||
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null));
|
||||
request.Addr = addr.GetInetAddress();
|
||||
n = RetryCount;
|
||||
while (n-- > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
Send(request, response, RetryTimeout);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
throw new UnknownHostException(ioe);
|
||||
}
|
||||
if (response.Received && response.ResultCode == 0)
|
||||
{
|
||||
srcHashCode = request.Addr.GetHashCode();
|
||||
for (int i = 0; i < response.AddressArray.Length; i++)
|
||||
{
|
||||
response.AddressArray[i].HostName.SrcHashCode = srcHashCode;
|
||||
}
|
||||
return response.AddressArray;
|
||||
}
|
||||
}
|
||||
throw new UnknownHostException();
|
||||
}
|
||||
|
||||
internal virtual NbtAddress[] GetHosts()
|
||||
{
|
||||
try
|
||||
{
|
||||
_waitResponse = false;
|
||||
|
||||
byte[] bAddrBytes = laddr.GetAddressBytes();
|
||||
|
||||
for (int i = 1; i <= 254; i++)
|
||||
{
|
||||
NodeStatusRequest request;
|
||||
NodeStatusResponse response;
|
||||
|
||||
byte[] addrBytes = {
|
||||
bAddrBytes[0],
|
||||
bAddrBytes[1],
|
||||
bAddrBytes[2],
|
||||
(byte)i
|
||||
};
|
||||
|
||||
IPAddress addr = new IPAddress(addrBytes);
|
||||
|
||||
//response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
|
||||
// (int)addr.Address, false, 0x20));
|
||||
response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
|
||||
BitConverter.ToInt32(addr.GetAddressBytes(), 0) , false, 0x20));
|
||||
|
||||
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x20), null));
|
||||
request.Addr = addr;
|
||||
Send(request, response, 0);
|
||||
}
|
||||
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (_log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, _log);
|
||||
}
|
||||
throw new UnknownHostException(ioe);
|
||||
}
|
||||
|
||||
_autoResetWaitReceive = new AutoResetEvent(false);
|
||||
_thread = new Thread(this);
|
||||
_thread.SetDaemon(true);
|
||||
_thread.Start();
|
||||
|
||||
_autoResetWaitReceive.WaitOne();
|
||||
|
||||
List<NbtAddress> result = new List<NbtAddress>();
|
||||
|
||||
foreach (var key in _responseTable.Keys)
|
||||
{
|
||||
NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key];
|
||||
|
||||
if (resp.Received && resp.ResultCode == 0)
|
||||
{
|
||||
foreach (var entry in resp.AddressArray)
|
||||
{
|
||||
if (entry.HostName.HexCode == 0x20)
|
||||
{
|
||||
result.Add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_responseTable.Clear();
|
||||
|
||||
_waitResponse = true;
|
||||
|
||||
return result.Count > 0 ? result.ToArray() : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.Net;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal abstract class NameServicePacket
|
||||
{
|
||||
internal const int Query = 0;
|
||||
|
||||
internal const int Wack = 7;
|
||||
|
||||
internal const int FmtErr = 0x1;
|
||||
|
||||
internal const int SrvErr = 0x2;
|
||||
|
||||
internal const int ImpErr = 0x4;
|
||||
|
||||
internal const int RfsErr = 0x5;
|
||||
|
||||
internal const int ActErr = 0x6;
|
||||
|
||||
internal const int CftErr = 0x7;
|
||||
|
||||
internal const int NbIn = 0x00200001;
|
||||
|
||||
internal const int NbstatIn = 0x00210001;
|
||||
|
||||
internal const int Nb = 0x0020;
|
||||
|
||||
internal const int Nbstat = 0x0021;
|
||||
|
||||
internal const int In = 0x0001;
|
||||
|
||||
internal const int A = 0x0001;
|
||||
|
||||
internal const int Ns = 0x0002;
|
||||
|
||||
internal const int Null = 0x000a;
|
||||
|
||||
internal const int HeaderLength = 12;
|
||||
|
||||
internal const int OpcodeOffset = 2;
|
||||
|
||||
internal const int QuestionOffset = 4;
|
||||
|
||||
internal const int AnswerOffset = 6;
|
||||
|
||||
internal const int AuthorityOffset = 8;
|
||||
|
||||
internal const int AdditionalOffset = 10;
|
||||
|
||||
// opcode
|
||||
// rcode
|
||||
// type/class
|
||||
// header field offsets
|
||||
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
|
||||
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
|
||||
}
|
||||
|
||||
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
|
||||
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
|
||||
}
|
||||
|
||||
internal static int ReadInt2(byte[] src, int srcIndex)
|
||||
{
|
||||
return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
|
||||
0xFF));
|
||||
}
|
||||
|
||||
internal static int ReadInt4(byte[] src, int srcIndex)
|
||||
{
|
||||
return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
|
||||
0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
|
||||
[srcIndex + 3] & unchecked(0xFF));
|
||||
}
|
||||
|
||||
internal static int ReadNameTrnId(byte[] src, int srcIndex)
|
||||
{
|
||||
return ReadInt2(src, srcIndex);
|
||||
}
|
||||
|
||||
internal int AddrIndex;
|
||||
|
||||
internal NbtAddress[] AddrEntry;
|
||||
|
||||
internal int NameTrnId;
|
||||
|
||||
internal int OpCode;
|
||||
|
||||
internal int ResultCode;
|
||||
|
||||
internal int QuestionCount;
|
||||
|
||||
internal int AnswerCount;
|
||||
|
||||
internal int AuthorityCount;
|
||||
|
||||
internal int AdditionalCount;
|
||||
|
||||
internal bool Received;
|
||||
|
||||
internal bool IsResponse;
|
||||
|
||||
internal bool IsAuthAnswer;
|
||||
|
||||
internal bool IsTruncated;
|
||||
|
||||
internal bool IsRecurDesired;
|
||||
|
||||
internal bool IsRecurAvailable;
|
||||
|
||||
internal bool IsBroadcast;
|
||||
|
||||
internal Name QuestionName;
|
||||
|
||||
internal Name RecordName;
|
||||
|
||||
internal int QuestionType;
|
||||
|
||||
internal int QuestionClass;
|
||||
|
||||
internal int RecordType;
|
||||
|
||||
internal int RecordClass;
|
||||
|
||||
internal int Ttl;
|
||||
|
||||
internal int RDataLength;
|
||||
|
||||
internal IPAddress Addr;
|
||||
|
||||
public NameServicePacket()
|
||||
{
|
||||
IsRecurDesired = true;
|
||||
IsBroadcast = true;
|
||||
QuestionCount = 1;
|
||||
QuestionClass = In;
|
||||
}
|
||||
|
||||
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
|
||||
dstIndex += WriteBodyWireFormat(dst, dstIndex);
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
int start = srcIndex;
|
||||
srcIndex += ReadHeaderWireFormat(src, srcIndex);
|
||||
srcIndex += ReadBodyWireFormat(src, srcIndex);
|
||||
return srcIndex - start;
|
||||
}
|
||||
|
||||
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
WriteInt2(NameTrnId, dst, dstIndex);
|
||||
dst[dstIndex + OpcodeOffset] = unchecked((byte)((IsResponse ? unchecked(0x80) : unchecked(0x00)) + ((OpCode << 3) & unchecked(0x78)) + (IsAuthAnswer
|
||||
? unchecked(0x04) : unchecked(0x00)) + (IsTruncated ? unchecked(0x02) : unchecked(0x00)) + (IsRecurDesired ? unchecked(0x01)
|
||||
: unchecked(0x00))));
|
||||
dst[dstIndex + OpcodeOffset + 1] = unchecked((byte)((IsRecurAvailable ? unchecked(
|
||||
0x80) : unchecked(0x00)) + (IsBroadcast ? unchecked(0x10) :
|
||||
unchecked(0x00)) + (ResultCode & unchecked(0x0F))));
|
||||
WriteInt2(QuestionCount, dst, start + QuestionOffset);
|
||||
WriteInt2(AnswerCount, dst, start + AnswerOffset);
|
||||
WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
|
||||
WriteInt2(AdditionalCount, dst, start + AdditionalOffset);
|
||||
return HeaderLength;
|
||||
}
|
||||
|
||||
internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
NameTrnId = ReadInt2(src, srcIndex);
|
||||
IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0) ? false
|
||||
: true;
|
||||
OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3;
|
||||
IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) ?
|
||||
false : true;
|
||||
IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0) ? false
|
||||
: true;
|
||||
IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0) ?
|
||||
false : true;
|
||||
IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80))
|
||||
== 0) ? false : true;
|
||||
IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0)
|
||||
? false : true;
|
||||
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
|
||||
QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
|
||||
AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
|
||||
AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset);
|
||||
AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset);
|
||||
return HeaderLength;
|
||||
}
|
||||
|
||||
internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
dstIndex += QuestionName.WriteWireFormat(dst, dstIndex);
|
||||
WriteInt2(QuestionType, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
WriteInt2(QuestionClass, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
int start = srcIndex;
|
||||
srcIndex += QuestionName.ReadWireFormat(src, srcIndex);
|
||||
QuestionType = ReadInt2(src, srcIndex);
|
||||
srcIndex += 2;
|
||||
QuestionClass = ReadInt2(src, srcIndex);
|
||||
srcIndex += 2;
|
||||
return srcIndex - start;
|
||||
}
|
||||
|
||||
internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
if (RecordName == QuestionName)
|
||||
{
|
||||
dst[dstIndex++] = unchecked(unchecked(0xC0));
|
||||
// label string pointer to
|
||||
dst[dstIndex++] = unchecked(unchecked(0x0C));
|
||||
}
|
||||
else
|
||||
{
|
||||
// questionName (offset 12)
|
||||
dstIndex += RecordName.WriteWireFormat(dst, dstIndex);
|
||||
}
|
||||
WriteInt2(RecordType, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
WriteInt2(RecordClass, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
WriteInt4(Ttl, dst, dstIndex);
|
||||
dstIndex += 4;
|
||||
RDataLength = WriteRDataWireFormat(dst, dstIndex + 2);
|
||||
WriteInt2(RDataLength, dst, dstIndex);
|
||||
dstIndex += 2 + RDataLength;
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
int start = srcIndex;
|
||||
int end;
|
||||
if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0))
|
||||
{
|
||||
RecordName = QuestionName;
|
||||
// label string pointer to questionName
|
||||
srcIndex += 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
srcIndex += RecordName.ReadWireFormat(src, srcIndex);
|
||||
}
|
||||
RecordType = ReadInt2(src, srcIndex);
|
||||
srcIndex += 2;
|
||||
RecordClass = ReadInt2(src, srcIndex);
|
||||
srcIndex += 2;
|
||||
Ttl = ReadInt4(src, srcIndex);
|
||||
srcIndex += 4;
|
||||
RDataLength = ReadInt2(src, srcIndex);
|
||||
srcIndex += 2;
|
||||
AddrEntry = new NbtAddress[RDataLength / 6];
|
||||
end = srcIndex + RDataLength;
|
||||
for (AddrIndex = 0; srcIndex < end; AddrIndex++)
|
||||
{
|
||||
srcIndex += ReadRDataWireFormat(src, srcIndex);
|
||||
}
|
||||
return srcIndex - start;
|
||||
}
|
||||
|
||||
internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex);
|
||||
|
||||
internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex);
|
||||
|
||||
internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex);
|
||||
|
||||
internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex);
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string opCodeString;
|
||||
string resultCodeString;
|
||||
string questionTypeString;
|
||||
string recordTypeString;
|
||||
|
||||
switch (OpCode)
|
||||
{
|
||||
case Query:
|
||||
{
|
||||
opCodeString = "QUERY";
|
||||
break;
|
||||
}
|
||||
|
||||
case Wack:
|
||||
{
|
||||
opCodeString = "WACK";
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
opCodeString = Extensions.ToString(OpCode);
|
||||
break;
|
||||
}
|
||||
}
|
||||
switch (ResultCode)
|
||||
{
|
||||
case FmtErr:
|
||||
{
|
||||
resultCodeString = "FMT_ERR";
|
||||
break;
|
||||
}
|
||||
|
||||
case SrvErr:
|
||||
{
|
||||
resultCodeString = "SRV_ERR";
|
||||
break;
|
||||
}
|
||||
|
||||
case ImpErr:
|
||||
{
|
||||
resultCodeString = "IMP_ERR";
|
||||
break;
|
||||
}
|
||||
|
||||
case RfsErr:
|
||||
{
|
||||
resultCodeString = "RFS_ERR";
|
||||
break;
|
||||
}
|
||||
|
||||
case ActErr:
|
||||
{
|
||||
resultCodeString = "ACT_ERR";
|
||||
break;
|
||||
}
|
||||
|
||||
case CftErr:
|
||||
{
|
||||
resultCodeString = "CFT_ERR";
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
switch (QuestionType)
|
||||
{
|
||||
case Nb:
|
||||
{
|
||||
questionTypeString = "NB";
|
||||
break;
|
||||
}
|
||||
|
||||
case Nbstat:
|
||||
{
|
||||
questionTypeString = "NBSTAT";
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
|
||||
break;
|
||||
}
|
||||
}
|
||||
switch (RecordType)
|
||||
{
|
||||
case A:
|
||||
{
|
||||
recordTypeString = "A";
|
||||
break;
|
||||
}
|
||||
|
||||
case Ns:
|
||||
{
|
||||
recordTypeString = "NS";
|
||||
break;
|
||||
}
|
||||
|
||||
case Null:
|
||||
{
|
||||
recordTypeString = "NULL";
|
||||
break;
|
||||
}
|
||||
|
||||
case Nb:
|
||||
{
|
||||
recordTypeString = "NB";
|
||||
break;
|
||||
}
|
||||
|
||||
case Nbstat:
|
||||
{
|
||||
recordTypeString = "NBSTAT";
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return "nameTrnId=" + NameTrnId + ",isResponse=" + IsResponse + ",opCode="
|
||||
+ opCodeString + ",isAuthAnswer=" + IsAuthAnswer + ",isTruncated=" + IsTruncated
|
||||
+ ",isRecurAvailable=" + IsRecurAvailable + ",isRecurDesired=" + IsRecurDesired
|
||||
+ ",isBroadcast=" + IsBroadcast + ",resultCode=" + ResultCode + ",questionCount="
|
||||
+ QuestionCount + ",answerCount=" + AnswerCount + ",authorityCount=" + AuthorityCount
|
||||
+ ",additionalCount=" + AdditionalCount + ",questionName=" + QuestionName + ",questionType="
|
||||
+ questionTypeString + ",questionClass=" + (QuestionClass == In ? "IN" : "0x" +
|
||||
Hexdump.ToHexString(QuestionClass, 4)) + ",recordName=" + RecordName + ",recordType="
|
||||
+ recordTypeString + ",recordClass=" + (RecordClass == In ? "IN" : "0x" + Hexdump
|
||||
.ToHexString(RecordClass, 4)) + ",ttl=" + Ttl + ",rDataLength=" + RDataLength;
|
||||
}
|
||||
}
|
||||
}
|
||||
920
Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs
Normal file
920
Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtAddress.cs
Normal file
@@ -0,0 +1,920 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
using Extensions = SharpCifs.Util.Sharpen.Extensions;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
/// <summary>This class represents a NetBIOS over TCP/IP address.</summary>
|
||||
/// <remarks>
|
||||
/// This class represents a NetBIOS over TCP/IP address. Under normal
|
||||
/// conditions, users of jCIFS need not be concerned with this class as
|
||||
/// name resolution and session services are handled internally by the smb package.
|
||||
/// <p> Applications can use the methods <code>getLocalHost</code>,
|
||||
/// <code>getByName</code>, and
|
||||
/// <code>getAllByAddress</code> to create a new NbtAddress instance. This
|
||||
/// class is symmetric with
|
||||
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
|
||||
/// .
|
||||
/// <p><b>About NetBIOS:</b> The NetBIOS name
|
||||
/// service is a dynamic distributed service that allows hosts to resolve
|
||||
/// names by broadcasting a query, directing queries to a server such as
|
||||
/// Samba or WINS. NetBIOS is currently the primary networking layer for
|
||||
/// providing name service, datagram service, and session service to the
|
||||
/// Microsoft Windows platform. A NetBIOS name can be 15 characters long
|
||||
/// and hosts usually registers several names on the network. From a
|
||||
/// Windows command prompt you can see
|
||||
/// what names a host registers with the nbtstat command.
|
||||
/// <p><blockquote><pre>
|
||||
/// C:\>nbtstat -a 192.168.1.15
|
||||
/// NetBIOS Remote Machine Name Table
|
||||
/// Name Type Status
|
||||
/// ---------------------------------------------
|
||||
/// JMORRIS2 <00> UNIQUE Registered
|
||||
/// BILLING-NY <00> GROUP Registered
|
||||
/// JMORRIS2 <03> UNIQUE Registered
|
||||
/// JMORRIS2 <20> UNIQUE Registered
|
||||
/// BILLING-NY <1E> GROUP Registered
|
||||
/// JMORRIS <03> UNIQUE Registered
|
||||
/// MAC Address = 00-B0-34-21-FA-3B
|
||||
/// </blockquote></pre>
|
||||
/// <p> The hostname of this machine is <code>JMORRIS2</code>. It is
|
||||
/// a member of the group(a.k.a workgroup and domain) <code>BILLING-NY</code>. To
|
||||
/// obtain an
|
||||
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
|
||||
/// for a host one might do:
|
||||
/// <pre>
|
||||
/// InetAddress addr = NbtAddress.getByName( "jmorris2" ).getInetAddress();
|
||||
/// </pre>
|
||||
/// <p>From a UNIX platform with Samba installed you can perform similar
|
||||
/// diagnostics using the <code>nmblookup</code> utility.
|
||||
/// </remarks>
|
||||
/// <author>Michael B. Allen</author>
|
||||
/// <seealso cref="System.Net.IPAddress">System.Net.IPAddress</seealso>
|
||||
/// <since>jcifs-0.1</since>
|
||||
public sealed class NbtAddress
|
||||
{
|
||||
internal static readonly string AnyHostsName = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
|
||||
|
||||
/// <summary>
|
||||
/// This is a special name for querying the master browser that serves the
|
||||
/// list of hosts found in "Network Neighborhood".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is a special name for querying the master browser that serves the
|
||||
/// list of hosts found in "Network Neighborhood".
|
||||
/// </remarks>
|
||||
public static readonly string MasterBrowserName = "\u0001\u0002__MSBROWSE__\u0002";
|
||||
|
||||
/// <summary>
|
||||
/// A special generic name specified when connecting to a host for which
|
||||
/// a name is not known.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A special generic name specified when connecting to a host for which
|
||||
/// a name is not known. Not all servers respond to this name.
|
||||
/// </remarks>
|
||||
public static readonly string SmbserverName = "*SMBSERVER ";
|
||||
|
||||
/// <summary>A B node only broadcasts name queries.</summary>
|
||||
/// <remarks>
|
||||
/// A B node only broadcasts name queries. This is the default if a
|
||||
/// nameserver such as WINS or Samba is not specified.
|
||||
/// </remarks>
|
||||
public const int BNode = 0;
|
||||
|
||||
/// <summary>
|
||||
/// A Point-to-Point node, or P node, unicasts queries to a nameserver
|
||||
/// only.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A Point-to-Point node, or P node, unicasts queries to a nameserver
|
||||
/// only. Natrually the <code>jcifs.netbios.nameserver</code> property must
|
||||
/// be set.
|
||||
/// </remarks>
|
||||
public const int PNode = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Try Broadcast queries first, then try to resolve the name using the
|
||||
/// nameserver.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Try Broadcast queries first, then try to resolve the name using the
|
||||
/// nameserver.
|
||||
/// </remarks>
|
||||
public const int MNode = 2;
|
||||
|
||||
/// <summary>A Hybrid node tries to resolve a name using the nameserver first.</summary>
|
||||
/// <remarks>
|
||||
/// A Hybrid node tries to resolve a name using the nameserver first. If
|
||||
/// that fails use the broadcast address. This is the default if a nameserver
|
||||
/// is provided. This is the behavior of Microsoft Windows machines.
|
||||
/// </remarks>
|
||||
public const int HNode = 3;
|
||||
|
||||
internal static readonly IPAddress[] Nbns = Config.GetInetAddressArray("jcifs.netbios.wins"
|
||||
, ",", new IPAddress[0]);
|
||||
|
||||
private static readonly NameServiceClient Client = new NameServiceClient();
|
||||
|
||||
private const int DefaultCachePolicy = 30;
|
||||
|
||||
private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy"
|
||||
, DefaultCachePolicy);
|
||||
|
||||
private const int Forever = -1;
|
||||
|
||||
private static int _nbnsIndex;
|
||||
|
||||
private static readonly Hashtable AddressCache = new Hashtable();
|
||||
|
||||
private static readonly Hashtable LookupTable = new Hashtable();
|
||||
|
||||
internal static readonly Name UnknownName = new Name("0.0.0.0", unchecked(0x00), null);
|
||||
|
||||
internal static readonly NbtAddress UnknownAddress = new NbtAddress
|
||||
(UnknownName, 0, false, BNode);
|
||||
|
||||
internal static readonly byte[] UnknownMacAddress = { unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)) };
|
||||
|
||||
internal sealed class CacheEntry
|
||||
{
|
||||
internal Name HostName;
|
||||
|
||||
internal NbtAddress Address;
|
||||
|
||||
internal long Expiration;
|
||||
|
||||
internal CacheEntry(Name hostName, NbtAddress address, long expiration)
|
||||
{
|
||||
this.HostName = hostName;
|
||||
this.Address = address;
|
||||
this.Expiration = expiration;
|
||||
}
|
||||
}
|
||||
|
||||
internal static NbtAddress Localhost;
|
||||
|
||||
static NbtAddress()
|
||||
{
|
||||
IPAddress localInetAddress;
|
||||
string localHostname;
|
||||
Name localName;
|
||||
AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
|
||||
, Forever));
|
||||
localInetAddress = Client.laddr;
|
||||
if (localInetAddress == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
localInetAddress = Extensions.GetAddressByName("127.0.0.1");
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
|
||||
if (string.IsNullOrEmpty(localHostname))
|
||||
{
|
||||
byte[] addr = localInetAddress.GetAddressBytes();
|
||||
|
||||
/*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
|
||||
(int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
|
||||
(int)(0xFF))), 2);*/
|
||||
localHostname = "JCIFS_127_0_0_1";
|
||||
}
|
||||
localName = new Name(localHostname, unchecked(0x00), Config.GetProperty("jcifs.netbios.scope"
|
||||
, null));
|
||||
Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
|
||||
, false, false, true, false, UnknownMacAddress);
|
||||
CacheAddress(localName, Localhost, Forever);
|
||||
}
|
||||
|
||||
internal static void CacheAddress(Name hostName, NbtAddress addr)
|
||||
{
|
||||
if (CachePolicy == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
long expiration = -1;
|
||||
if (CachePolicy != Forever)
|
||||
{
|
||||
expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
|
||||
}
|
||||
CacheAddress(hostName, addr, expiration);
|
||||
}
|
||||
|
||||
internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration
|
||||
)
|
||||
{
|
||||
if (CachePolicy == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
lock (AddressCache)
|
||||
{
|
||||
CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
|
||||
if (entry == null)
|
||||
{
|
||||
entry = new CacheEntry(hostName, addr, expiration);
|
||||
AddressCache.Put(hostName, entry);
|
||||
}
|
||||
else
|
||||
{
|
||||
entry.Address = addr;
|
||||
entry.Expiration = expiration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void CacheAddressArray(NbtAddress[] addrs)
|
||||
{
|
||||
if (CachePolicy == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
long expiration = -1;
|
||||
if (CachePolicy != Forever)
|
||||
{
|
||||
expiration = Runtime.CurrentTimeMillis() + CachePolicy * 1000;
|
||||
}
|
||||
lock (AddressCache)
|
||||
{
|
||||
for (int i = 0; i < addrs.Length; i++)
|
||||
{
|
||||
CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName
|
||||
);
|
||||
if (entry == null)
|
||||
{
|
||||
entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration);
|
||||
AddressCache.Put(addrs[i].HostName, entry);
|
||||
}
|
||||
else
|
||||
{
|
||||
entry.Address = addrs[i];
|
||||
entry.Expiration = expiration;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static NbtAddress GetCachedAddress(Name hostName)
|
||||
{
|
||||
if (CachePolicy == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
lock (AddressCache)
|
||||
{
|
||||
CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
|
||||
if (entry != null && entry.Expiration < Runtime.CurrentTimeMillis() && entry.Expiration
|
||||
>= 0)
|
||||
{
|
||||
entry = null;
|
||||
}
|
||||
return entry != null ? entry.Address : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
internal static NbtAddress DoNameQuery(Name name, IPAddress svr)
|
||||
{
|
||||
NbtAddress addr;
|
||||
if (name.HexCode == unchecked(0x1d) && svr == null)
|
||||
{
|
||||
svr = Client.Baddr;
|
||||
}
|
||||
// bit of a hack but saves a lookup
|
||||
name.SrcHashCode = svr != null ? svr.GetHashCode() : 0;
|
||||
addr = GetCachedAddress(name);
|
||||
if (addr == null)
|
||||
{
|
||||
if ((addr = (NbtAddress)CheckLookupTable(name)) == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
addr = Client.GetByName(name, svr);
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
addr = UnknownAddress;
|
||||
}
|
||||
finally
|
||||
{
|
||||
CacheAddress(name, addr);
|
||||
UpdateLookupTable(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (addr == UnknownAddress)
|
||||
{
|
||||
throw new UnknownHostException(name.ToString());
|
||||
}
|
||||
return addr;
|
||||
}
|
||||
|
||||
private static object CheckLookupTable(Name name)
|
||||
{
|
||||
object obj;
|
||||
lock (LookupTable)
|
||||
{
|
||||
if (LookupTable.ContainsKey(name) == false)
|
||||
{
|
||||
LookupTable.Put(name, name);
|
||||
return null;
|
||||
}
|
||||
while (LookupTable.ContainsKey(name))
|
||||
{
|
||||
try
|
||||
{
|
||||
Runtime.Wait(LookupTable);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
obj = GetCachedAddress(name);
|
||||
if (obj == null)
|
||||
{
|
||||
lock (LookupTable)
|
||||
{
|
||||
LookupTable.Put(name, name);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
private static void UpdateLookupTable(Name name)
|
||||
{
|
||||
lock (LookupTable)
|
||||
{
|
||||
//Sharpen.Collections.Remove(LOOKUP_TABLE, name);
|
||||
LookupTable.Remove(name);
|
||||
Runtime.NotifyAll(LookupTable);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Retrieves the local host address.</summary>
|
||||
/// <remarks>Retrieves the local host address.</remarks>
|
||||
/// <exception cref="UnknownHostException">
|
||||
/// This is not likely as the IP returned
|
||||
/// by <code>InetAddress</code> should be available
|
||||
/// </exception>
|
||||
public static NbtAddress GetLocalHost()
|
||||
{
|
||||
return Localhost;
|
||||
}
|
||||
|
||||
public static NbtAddress[] GetHosts()
|
||||
{
|
||||
return new NameServiceClient().GetHosts();
|
||||
}
|
||||
|
||||
public static Name GetLocalName()
|
||||
{
|
||||
return Localhost.HostName;
|
||||
}
|
||||
|
||||
/// <summary>Determines the address of a host given it's host name.</summary>
|
||||
/// <remarks>
|
||||
/// Determines the address of a host given it's host name. The name can be a NetBIOS name like
|
||||
/// "freto" or an IP address like "192.168.1.15". It cannot be a DNS name;
|
||||
/// the analygous
|
||||
/// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
|
||||
/// or
|
||||
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
|
||||
/// <code>getByName</code> methods can be used for that.
|
||||
/// </remarks>
|
||||
/// <param name="host">hostname to resolve</param>
|
||||
/// <exception cref="UnknownHostException">if there is an error resolving the name
|
||||
/// </exception>
|
||||
public static NbtAddress GetByName(string host)
|
||||
{
|
||||
return GetByName(host, unchecked(0x00), null);
|
||||
}
|
||||
|
||||
/// <summary>Determines the address of a host given it's host name.</summary>
|
||||
/// <remarks>
|
||||
/// Determines the address of a host given it's host name. NetBIOS
|
||||
/// names also have a <code>type</code>. Types(aka Hex Codes)
|
||||
/// are used to distiquish the various services on a host. <a
|
||||
/// href="../../../nbtcodes.html">Here</a> is
|
||||
/// a fairly complete list of NetBIOS hex codes. Scope is not used but is
|
||||
/// still functional in other NetBIOS products and so for completeness it has been
|
||||
/// implemented. A <code>scope</code> of <code>null</code> or <code>""</code>
|
||||
/// signifies no scope.
|
||||
/// </remarks>
|
||||
/// <param name="host">the name to resolve</param>
|
||||
/// <param name="type">the hex code of the name</param>
|
||||
/// <param name="scope">the scope of the name</param>
|
||||
/// <exception cref="UnknownHostException">if there is an error resolving the name
|
||||
/// </exception>
|
||||
public static NbtAddress GetByName(string host, int type, string scope)
|
||||
{
|
||||
return GetByName(host, type, scope, null);
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
public static NbtAddress GetByName(string host, int type, string scope, IPAddress
|
||||
svr)
|
||||
{
|
||||
if (string.IsNullOrEmpty(host))
|
||||
{
|
||||
return GetLocalHost();
|
||||
}
|
||||
if (!char.IsDigit(host[0]))
|
||||
{
|
||||
return DoNameQuery(new Name(host, type, scope), svr);
|
||||
}
|
||||
int ip = unchecked(0x00);
|
||||
int hitDots = 0;
|
||||
char[] data = host.ToCharArray();
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
char c = data[i];
|
||||
if (c < 48 || c > 57)
|
||||
{
|
||||
return DoNameQuery(new Name(host, type, scope), svr);
|
||||
}
|
||||
int b = unchecked(0x00);
|
||||
while (c != '.')
|
||||
{
|
||||
if (c < 48 || c > 57)
|
||||
{
|
||||
return DoNameQuery(new Name(host, type, scope), svr);
|
||||
}
|
||||
b = b * 10 + c - '0';
|
||||
if (++i >= data.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
c = data[i];
|
||||
}
|
||||
if (b > unchecked(0xFF))
|
||||
{
|
||||
return DoNameQuery(new Name(host, type, scope), svr);
|
||||
}
|
||||
ip = (ip << 8) + b;
|
||||
hitDots++;
|
||||
}
|
||||
if (hitDots != 4 || host.EndsWith("."))
|
||||
{
|
||||
return DoNameQuery(new Name(host, type, scope), svr);
|
||||
}
|
||||
return new NbtAddress(UnknownName, ip, false, BNode);
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
public static NbtAddress[] GetAllByName(string host, int type, string scope, IPAddress
|
||||
svr)
|
||||
{
|
||||
return Client.GetAllByName(new Name(host, type, scope), svr);
|
||||
}
|
||||
|
||||
/// <summary>Retrieve all addresses of a host by it's address.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
|
||||
/// have many names for a given IP address. The name and IP address make the
|
||||
/// NetBIOS address. This provides a way to retrieve the other names for a
|
||||
/// host with the same IP address.
|
||||
/// </remarks>
|
||||
/// <param name="host">hostname to lookup all addresses for</param>
|
||||
/// <exception cref="UnknownHostException">if there is an error resolving the name
|
||||
/// </exception>
|
||||
public static NbtAddress[] GetAllByAddress(string host)
|
||||
{
|
||||
return GetAllByAddress(GetByName(host, unchecked(0x00), null));
|
||||
}
|
||||
|
||||
/// <summary>Retrieve all addresses of a host by it's address.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
|
||||
/// have many names for a given IP address. The name and IP address make
|
||||
/// the NetBIOS address. This provides a way to retrieve the other names
|
||||
/// for a host with the same IP address. See
|
||||
/// <see cref="GetByName(string)">GetByName(string)</see>
|
||||
/// for a description of <code>type</code>
|
||||
/// and <code>scope</code>.
|
||||
/// </remarks>
|
||||
/// <param name="host">hostname to lookup all addresses for</param>
|
||||
/// <param name="type">the hexcode of the name</param>
|
||||
/// <param name="scope">the scope of the name</param>
|
||||
/// <exception cref="UnknownHostException">if there is an error resolving the name
|
||||
/// </exception>
|
||||
public static NbtAddress[] GetAllByAddress(string host, int type, string scope)
|
||||
{
|
||||
return GetAllByAddress(GetByName(host, type, scope));
|
||||
}
|
||||
|
||||
/// <summary>Retrieve all addresses of a host by it's address.</summary>
|
||||
/// <remarks>
|
||||
/// Retrieve all addresses of a host by it's address. NetBIOS hosts can
|
||||
/// have many names for a given IP address. The name and IP address make the
|
||||
/// NetBIOS address. This provides a way to retrieve the other names for a
|
||||
/// host with the same IP address.
|
||||
/// </remarks>
|
||||
/// <param name="addr">the address to query</param>
|
||||
/// <exception cref="UnknownHostException">if address cannot be resolved</exception>
|
||||
public static NbtAddress[] GetAllByAddress(NbtAddress addr)
|
||||
{
|
||||
try
|
||||
{
|
||||
NbtAddress[] addrs = Client.GetNodeStatus(addr);
|
||||
CacheAddressArray(addrs);
|
||||
return addrs;
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
|
||||
HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
|
||||
== 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
|
||||
+ addr.GetHostAddress());
|
||||
}
|
||||
}
|
||||
|
||||
public static IPAddress GetWinsAddress()
|
||||
{
|
||||
return Nbns.Length == 0 ? null : Nbns[_nbnsIndex];
|
||||
}
|
||||
|
||||
public static bool IsWins(IPAddress svr)
|
||||
{
|
||||
for (int i = 0; svr != null && i < Nbns.Length; i++)
|
||||
{
|
||||
if (svr.GetHashCode() == Nbns[i].GetHashCode())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static IPAddress SwitchWins()
|
||||
{
|
||||
_nbnsIndex = (_nbnsIndex + 1) < Nbns.Length ? _nbnsIndex + 1 : 0;
|
||||
return Nbns.Length == 0 ? null : Nbns[_nbnsIndex];
|
||||
}
|
||||
|
||||
internal Name HostName;
|
||||
|
||||
internal int Address;
|
||||
|
||||
internal int NodeType;
|
||||
|
||||
internal bool GroupName;
|
||||
|
||||
internal bool isBeingDeleted;
|
||||
|
||||
internal bool isInConflict;
|
||||
|
||||
internal bool isActive;
|
||||
|
||||
internal bool isPermanent;
|
||||
|
||||
internal bool IsDataFromNodeStatus;
|
||||
|
||||
internal byte[] MacAddress;
|
||||
|
||||
internal string CalledName;
|
||||
|
||||
internal NbtAddress(Name hostName, int address, bool groupName, int nodeType)
|
||||
{
|
||||
this.HostName = hostName;
|
||||
this.Address = address;
|
||||
this.GroupName = groupName;
|
||||
this.NodeType = nodeType;
|
||||
}
|
||||
|
||||
internal NbtAddress(Name hostName, int address, bool groupName, int nodeType, bool
|
||||
isBeingDeleted, bool isInConflict, bool isActive, bool isPermanent, byte[] macAddress
|
||||
)
|
||||
{
|
||||
this.HostName = hostName;
|
||||
this.Address = address;
|
||||
this.GroupName = groupName;
|
||||
this.NodeType = nodeType;
|
||||
this.isBeingDeleted = isBeingDeleted;
|
||||
this.isInConflict = isInConflict;
|
||||
this.isActive = isActive;
|
||||
this.isPermanent = isPermanent;
|
||||
this.MacAddress = macAddress;
|
||||
IsDataFromNodeStatus = true;
|
||||
}
|
||||
|
||||
public string FirstCalledName()
|
||||
{
|
||||
CalledName = HostName.name;
|
||||
if (char.IsDigit(CalledName[0]))
|
||||
{
|
||||
int i;
|
||||
int len;
|
||||
int dots;
|
||||
char[] data;
|
||||
i = dots = 0;
|
||||
len = CalledName.Length;
|
||||
data = CalledName.ToCharArray();
|
||||
while (i < len && char.IsDigit(data[i++]))
|
||||
{
|
||||
if (i == len && dots == 3)
|
||||
{
|
||||
// probably an IP address
|
||||
CalledName = SmbserverName;
|
||||
break;
|
||||
}
|
||||
if (i < len && data[i] == '.')
|
||||
{
|
||||
dots++;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (HostName.HexCode)
|
||||
{
|
||||
case unchecked(0x1B):
|
||||
case unchecked(0x1C):
|
||||
case unchecked(0x1D):
|
||||
{
|
||||
CalledName = SmbserverName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return CalledName;
|
||||
}
|
||||
|
||||
public string NextCalledName()
|
||||
{
|
||||
if (CalledName == HostName.name)
|
||||
{
|
||||
CalledName = SmbserverName;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (CalledName == SmbserverName)
|
||||
{
|
||||
NbtAddress[] addrs;
|
||||
try
|
||||
{
|
||||
addrs = Client.GetNodeStatus(this);
|
||||
if (HostName.HexCode == unchecked(0x1D))
|
||||
{
|
||||
for (int i = 0; i < addrs.Length; i++)
|
||||
{
|
||||
if (addrs[i].HostName.HexCode == unchecked(0x20))
|
||||
{
|
||||
return addrs[i].HostName.name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (IsDataFromNodeStatus)
|
||||
{
|
||||
CalledName = null;
|
||||
return HostName.name;
|
||||
}
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
CalledName = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CalledName = null;
|
||||
}
|
||||
}
|
||||
return CalledName;
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
internal void CheckData()
|
||||
{
|
||||
if (HostName == UnknownName)
|
||||
{
|
||||
GetAllByAddress(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
internal void CheckNodeStatusData()
|
||||
{
|
||||
if (IsDataFromNodeStatus == false)
|
||||
{
|
||||
GetAllByAddress(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Determines if the address is a group address.</summary>
|
||||
/// <remarks>
|
||||
/// Determines if the address is a group address. This is also
|
||||
/// known as a workgroup name or group name.
|
||||
/// </remarks>
|
||||
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
|
||||
/// </exception>
|
||||
public bool IsGroupAddress()
|
||||
{
|
||||
CheckData();
|
||||
return GroupName;
|
||||
}
|
||||
|
||||
/// <summary>Checks the node type of this address.</summary>
|
||||
/// <remarks>Checks the node type of this address.</remarks>
|
||||
/// <returns>
|
||||
///
|
||||
/// <see cref="BNode">B_NODE</see>
|
||||
/// ,
|
||||
/// <see cref="PNode">P_NODE</see>
|
||||
/// ,
|
||||
/// <see cref="MNode">M_NODE</see>
|
||||
/// ,
|
||||
/// <see cref="HNode">H_NODE</see>
|
||||
/// </returns>
|
||||
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
|
||||
/// </exception>
|
||||
public int GetNodeType()
|
||||
{
|
||||
CheckData();
|
||||
return NodeType;
|
||||
}
|
||||
|
||||
/// <summary>Determines if this address in the process of being deleted.</summary>
|
||||
/// <remarks>Determines if this address in the process of being deleted.</remarks>
|
||||
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
|
||||
/// </exception>
|
||||
public bool IsBeingDeleted()
|
||||
{
|
||||
CheckNodeStatusData();
|
||||
return isBeingDeleted;
|
||||
}
|
||||
|
||||
/// <summary>Determines if this address in conflict with another address.</summary>
|
||||
/// <remarks>Determines if this address in conflict with another address.</remarks>
|
||||
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
|
||||
/// </exception>
|
||||
public bool IsInConflict()
|
||||
{
|
||||
CheckNodeStatusData();
|
||||
return isInConflict;
|
||||
}
|
||||
|
||||
/// <summary>Determines if this address is active.</summary>
|
||||
/// <remarks>Determines if this address is active.</remarks>
|
||||
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
|
||||
/// </exception>
|
||||
public bool IsActive()
|
||||
{
|
||||
CheckNodeStatusData();
|
||||
return isActive;
|
||||
}
|
||||
|
||||
/// <summary>Determines if this address is set to be permanent.</summary>
|
||||
/// <remarks>Determines if this address is set to be permanent.</remarks>
|
||||
/// <exception cref="UnknownHostException">if the host cannot be resolved to find out.
|
||||
/// </exception>
|
||||
public bool IsPermanent()
|
||||
{
|
||||
CheckNodeStatusData();
|
||||
return isPermanent;
|
||||
}
|
||||
|
||||
/// <summary>Retrieves the MAC address of the remote network interface.</summary>
|
||||
/// <remarks>Retrieves the MAC address of the remote network interface. Samba returns all zeros.
|
||||
/// </remarks>
|
||||
/// <returns>the MAC address as an array of six bytes</returns>
|
||||
/// <exception cref="UnknownHostException">
|
||||
/// if the host cannot be resolved to
|
||||
/// determine the MAC address.
|
||||
/// </exception>
|
||||
public byte[] GetMacAddress()
|
||||
{
|
||||
CheckNodeStatusData();
|
||||
return MacAddress;
|
||||
}
|
||||
|
||||
/// <summary>The hostname of this address.</summary>
|
||||
/// <remarks>
|
||||
/// The hostname of this address. If the hostname is null the local machines
|
||||
/// IP address is returned.
|
||||
/// </remarks>
|
||||
/// <returns>the text representation of the hostname associated with this address</returns>
|
||||
public string GetHostName()
|
||||
{
|
||||
if (HostName == UnknownName)
|
||||
{
|
||||
return GetHostAddress();
|
||||
}
|
||||
return HostName.name;
|
||||
}
|
||||
|
||||
/// <summary>Returns the raw IP address of this NbtAddress.</summary>
|
||||
/// <remarks>
|
||||
/// Returns the raw IP address of this NbtAddress. The result is in network
|
||||
/// byte order: the highest order byte of the address is in getAddress()[0].
|
||||
/// </remarks>
|
||||
/// <returns>a four byte array</returns>
|
||||
public byte[] GetAddress()
|
||||
{
|
||||
byte[] addr = new byte[4];
|
||||
addr[0] = unchecked((byte)(((int)(((uint)Address) >> 24)) & unchecked(0xFF
|
||||
)));
|
||||
addr[1] = unchecked((byte)(((int)(((uint)Address) >> 16)) & unchecked(0xFF
|
||||
)));
|
||||
addr[2] = unchecked((byte)(((int)(((uint)Address) >> 8)) & unchecked(0xFF)
|
||||
));
|
||||
addr[3] = unchecked((byte)(Address & unchecked(0xFF)));
|
||||
return addr;
|
||||
}
|
||||
|
||||
/// <summary>To convert this address to an <code>InetAddress</code>.</summary>
|
||||
/// <remarks>To convert this address to an <code>InetAddress</code>.</remarks>
|
||||
/// <returns>
|
||||
/// the
|
||||
/// <see cref="System.Net.IPAddress">System.Net.IPAddress</see>
|
||||
/// representation of this address.
|
||||
/// </returns>
|
||||
/// <exception cref="UnknownHostException"></exception>
|
||||
public IPAddress GetInetAddress()
|
||||
{
|
||||
return Extensions.GetAddressByName(GetHostAddress());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns this IP adress as a
|
||||
/// <see cref="string">string</see>
|
||||
/// in the form "%d.%d.%d.%d".
|
||||
/// </summary>
|
||||
public string GetHostAddress()
|
||||
{
|
||||
return (((int)(((uint)Address) >> 24)) & unchecked(0xFF)) + "." + (((int)(
|
||||
((uint)Address) >> 16)) & unchecked(0xFF)) + "." + (((int)(((uint)Address
|
||||
) >> 8)) & unchecked(0xFF)) + "." + (((int)(((uint)Address) >> 0)) & unchecked(
|
||||
0xFF));
|
||||
}
|
||||
|
||||
/// <summary>Returned the hex code associated with this name(e.g.</summary>
|
||||
/// <remarks>Returned the hex code associated with this name(e.g. 0x20 is for the file service)
|
||||
/// </remarks>
|
||||
public int GetNameType()
|
||||
{
|
||||
return HostName.HexCode;
|
||||
}
|
||||
|
||||
/// <summary>Returns a hashcode for this IP address.</summary>
|
||||
/// <remarks>
|
||||
/// Returns a hashcode for this IP address. The hashcode comes from the IP address
|
||||
/// and is not generated from the string representation. So because NetBIOS nodes
|
||||
/// can have many names, all names associated with an IP will have the same
|
||||
/// hashcode.
|
||||
/// </remarks>
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Address;
|
||||
}
|
||||
|
||||
/// <summary>Determines if this address is equal two another.</summary>
|
||||
/// <remarks>
|
||||
/// Determines if this address is equal two another. Only the IP Addresses
|
||||
/// are compared. Similar to the
|
||||
/// <see cref="GetHashCode()">GetHashCode()</see>
|
||||
/// method, the comparison
|
||||
/// is based on the integer IP address and not the string representation.
|
||||
/// </remarks>
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return (obj != null) && (obj is NbtAddress) && (((NbtAddress)obj).Address == Address
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the
|
||||
/// <see cref="string">string</see>
|
||||
/// representaion of this address.
|
||||
/// </summary>
|
||||
public override string ToString()
|
||||
{
|
||||
return HostName + "/" + GetHostAddress();
|
||||
}
|
||||
}
|
||||
}
|
||||
164
Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs
Normal file
164
Emby.Server.Implementations/IO/SharpCifs/Netbios/NbtException.cs
Normal file
@@ -0,0 +1,164 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
|
||||
public class NbtException : IOException
|
||||
{
|
||||
public const int Success = 0;
|
||||
|
||||
public const int ErrNamSrvc = unchecked(0x01);
|
||||
|
||||
public const int ErrSsnSrvc = unchecked(0x02);
|
||||
|
||||
public const int FmtErr = unchecked(0x1);
|
||||
|
||||
public const int SrvErr = unchecked(0x2);
|
||||
|
||||
public const int ImpErr = unchecked(0x4);
|
||||
|
||||
public const int RfsErr = unchecked(0x5);
|
||||
|
||||
public const int ActErr = unchecked(0x6);
|
||||
|
||||
public const int CftErr = unchecked(0x7);
|
||||
|
||||
public const int ConnectionRefused = -1;
|
||||
|
||||
public const int NotListeningCalled = unchecked(0x80);
|
||||
|
||||
public const int NotListeningCalling = unchecked(0x81);
|
||||
|
||||
public const int CalledNotPresent = unchecked(0x82);
|
||||
|
||||
public const int NoResources = unchecked(0x83);
|
||||
|
||||
public const int Unspecified = unchecked(0x8F);
|
||||
|
||||
public int ErrorClass;
|
||||
|
||||
public int ErrorCode;
|
||||
|
||||
// error classes
|
||||
// name service error codes
|
||||
// session service error codes
|
||||
public static string GetErrorString(int errorClass, int errorCode)
|
||||
{
|
||||
string result = string.Empty;
|
||||
switch (errorClass)
|
||||
{
|
||||
case Success:
|
||||
{
|
||||
result += "SUCCESS";
|
||||
break;
|
||||
}
|
||||
|
||||
case ErrNamSrvc:
|
||||
{
|
||||
result += "ERR_NAM_SRVC/";
|
||||
switch (errorCode)
|
||||
{
|
||||
case FmtErr:
|
||||
{
|
||||
result += "FMT_ERR: Format Error";
|
||||
goto default;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
result += "Unknown error code: " + errorCode;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case ErrSsnSrvc:
|
||||
{
|
||||
result += "ERR_SSN_SRVC/";
|
||||
switch (errorCode)
|
||||
{
|
||||
case ConnectionRefused:
|
||||
{
|
||||
result += "Connection refused";
|
||||
break;
|
||||
}
|
||||
|
||||
case NotListeningCalled:
|
||||
{
|
||||
result += "Not listening on called name";
|
||||
break;
|
||||
}
|
||||
|
||||
case NotListeningCalling:
|
||||
{
|
||||
result += "Not listening for calling name";
|
||||
break;
|
||||
}
|
||||
|
||||
case CalledNotPresent:
|
||||
{
|
||||
result += "Called name not present";
|
||||
break;
|
||||
}
|
||||
|
||||
case NoResources:
|
||||
{
|
||||
result += "Called name present, but insufficient resources";
|
||||
break;
|
||||
}
|
||||
|
||||
case Unspecified:
|
||||
{
|
||||
result += "Unspecified error";
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
result += "Unknown error code: " + errorCode;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
result += "unknown error class: " + errorClass;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass
|
||||
, errorCode))
|
||||
{
|
||||
this.ErrorClass = errorClass;
|
||||
this.ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString="
|
||||
+ GetErrorString(ErrorClass, ErrorCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal class NodeStatusRequest : NameServicePacket
|
||||
{
|
||||
internal NodeStatusRequest(Name name)
|
||||
{
|
||||
QuestionName = name;
|
||||
QuestionType = Nbstat;
|
||||
IsRecurDesired = false;
|
||||
IsBroadcast = false;
|
||||
}
|
||||
|
||||
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int tmp = QuestionName.HexCode;
|
||||
QuestionName.HexCode = unchecked(0x00);
|
||||
// type has to be 0x00 for node status
|
||||
int result = WriteQuestionSectionWireFormat(dst, dstIndex);
|
||||
QuestionName.HexCode = tmp;
|
||||
return result;
|
||||
}
|
||||
|
||||
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NodeStatusRequest[" + base.ToString() + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal class NodeStatusResponse : NameServicePacket
|
||||
{
|
||||
private NbtAddress _queryAddress;
|
||||
|
||||
private int _numberOfNames;
|
||||
|
||||
private byte[] _macAddress;
|
||||
|
||||
private byte[] _stats;
|
||||
|
||||
internal NbtAddress[] AddressArray;
|
||||
|
||||
internal NodeStatusResponse(NbtAddress queryAddress)
|
||||
{
|
||||
this._queryAddress = queryAddress;
|
||||
RecordName = new Name();
|
||||
_macAddress = new byte[6];
|
||||
}
|
||||
|
||||
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
return ReadResourceRecordWireFormat(src, srcIndex);
|
||||
}
|
||||
|
||||
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
|
||||
{
|
||||
int start = srcIndex;
|
||||
_numberOfNames = src[srcIndex] & unchecked(0xFF);
|
||||
int namesLength = _numberOfNames * 18;
|
||||
int statsLength = RDataLength - namesLength - 1;
|
||||
_numberOfNames = src[srcIndex++] & unchecked(0xFF);
|
||||
// gotta read the mac first so we can populate addressArray with it
|
||||
Array.Copy(src, srcIndex + namesLength, _macAddress, 0, 6);
|
||||
srcIndex += ReadNodeNameArray(src, srcIndex);
|
||||
_stats = new byte[statsLength];
|
||||
Array.Copy(src, srcIndex, _stats, 0, statsLength);
|
||||
srcIndex += statsLength;
|
||||
return srcIndex - start;
|
||||
}
|
||||
|
||||
private int ReadNodeNameArray(byte[] src, int srcIndex)
|
||||
{
|
||||
int start = srcIndex;
|
||||
AddressArray = new NbtAddress[_numberOfNames];
|
||||
string n;
|
||||
int hexCode;
|
||||
string scope = _queryAddress.HostName.Scope;
|
||||
bool groupName;
|
||||
int ownerNodeType;
|
||||
bool isBeingDeleted;
|
||||
bool isInConflict;
|
||||
bool isActive;
|
||||
bool isPermanent;
|
||||
int j;
|
||||
bool addrFound = false;
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
|
||||
{
|
||||
for (j = srcIndex + 14; src[j] == unchecked(0x20); j--)
|
||||
{
|
||||
}
|
||||
n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
|
||||
);
|
||||
hexCode = src[srcIndex + 15] & unchecked(0xFF);
|
||||
groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
|
||||
ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5;
|
||||
isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false;
|
||||
isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : false;
|
||||
isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04)) ? true : false;
|
||||
isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02)) ? true : false;
|
||||
if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName
|
||||
== NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n)))
|
||||
{
|
||||
if (_queryAddress.HostName == NbtAddress.UnknownName)
|
||||
{
|
||||
_queryAddress.HostName = new Name(n, hexCode, scope);
|
||||
}
|
||||
_queryAddress.GroupName = groupName;
|
||||
_queryAddress.NodeType = ownerNodeType;
|
||||
_queryAddress.isBeingDeleted = isBeingDeleted;
|
||||
_queryAddress.isInConflict = isInConflict;
|
||||
_queryAddress.isActive = isActive;
|
||||
_queryAddress.isPermanent = isPermanent;
|
||||
_queryAddress.MacAddress = _macAddress;
|
||||
_queryAddress.IsDataFromNodeStatus = true;
|
||||
addrFound = true;
|
||||
AddressArray[i] = _queryAddress;
|
||||
}
|
||||
else
|
||||
{
|
||||
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
|
||||
, groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
|
||||
_macAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
return srcIndex - start;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NodeStatusResponse[" + base.ToString() + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
public class SessionRequestPacket : SessionServicePacket
|
||||
{
|
||||
private Name _calledName;
|
||||
|
||||
private Name _callingName;
|
||||
|
||||
public SessionRequestPacket()
|
||||
{
|
||||
_calledName = new Name();
|
||||
_callingName = new Name();
|
||||
}
|
||||
|
||||
public SessionRequestPacket(Name calledName, Name callingName)
|
||||
{
|
||||
Type = SessionRequest;
|
||||
this._calledName = calledName;
|
||||
this._callingName = callingName;
|
||||
}
|
||||
|
||||
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
dstIndex += _calledName.WriteWireFormat(dst, dstIndex);
|
||||
dstIndex += _callingName.WriteWireFormat(dst, dstIndex);
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
|
||||
)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
if (@in.Read(buffer, bufferIndex, Length) != Length)
|
||||
{
|
||||
throw new IOException("invalid session request wire format");
|
||||
}
|
||||
bufferIndex += _calledName.ReadWireFormat(buffer, bufferIndex);
|
||||
bufferIndex += _callingName.ReadWireFormat(buffer, bufferIndex);
|
||||
return bufferIndex - start;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
internal class SessionRetargetResponsePacket : SessionServicePacket
|
||||
{
|
||||
private NbtAddress _retargetAddress;
|
||||
|
||||
private int _retargetPort;
|
||||
|
||||
public SessionRetargetResponsePacket()
|
||||
{
|
||||
Type = SessionRetargetResponse;
|
||||
Length = 6;
|
||||
}
|
||||
|
||||
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
|
||||
)
|
||||
{
|
||||
if (@in.Read(buffer, bufferIndex, Length) != Length)
|
||||
{
|
||||
throw new IOException("unexpected EOF reading netbios retarget session response");
|
||||
}
|
||||
int addr = ReadInt4(buffer, bufferIndex);
|
||||
bufferIndex += 4;
|
||||
_retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
|
||||
_retargetPort = ReadInt2(buffer, bufferIndex);
|
||||
return Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Netbios
|
||||
{
|
||||
public abstract class SessionServicePacket
|
||||
{
|
||||
internal const int SessionMessage = unchecked(0x00);
|
||||
|
||||
internal const int SessionRequest = unchecked(0x81);
|
||||
|
||||
public const int PositiveSessionResponse = unchecked(0x82);
|
||||
|
||||
public const int NegativeSessionResponse = unchecked(0x83);
|
||||
|
||||
internal const int SessionRetargetResponse = unchecked(0x84);
|
||||
|
||||
internal const int SessionKeepAlive = unchecked(0x85);
|
||||
|
||||
internal const int MaxMessageSize = unchecked(0x0001FFFF);
|
||||
|
||||
internal const int HeaderLength = 4;
|
||||
|
||||
// session service packet types
|
||||
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
|
||||
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
|
||||
}
|
||||
|
||||
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
|
||||
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
|
||||
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
|
||||
}
|
||||
|
||||
internal static int ReadInt2(byte[] src, int srcIndex)
|
||||
{
|
||||
return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
|
||||
0xFF));
|
||||
}
|
||||
|
||||
internal static int ReadInt4(byte[] src, int srcIndex)
|
||||
{
|
||||
return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
|
||||
0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
|
||||
[srcIndex + 3] & unchecked(0xFF));
|
||||
}
|
||||
|
||||
internal static int ReadLength(byte[] src, int srcIndex)
|
||||
{
|
||||
srcIndex++;
|
||||
return ((src[srcIndex++] & unchecked(0x01)) << 16) + ((src[srcIndex++] & unchecked(
|
||||
0xFF)) << 8) + (src[srcIndex++] & unchecked(0xFF));
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static int Readn(InputStream @in, byte[] b, int off, int len)
|
||||
{
|
||||
int i = 0;
|
||||
int n;
|
||||
while (i < len)
|
||||
{
|
||||
n = @in.Read(b, off + i, len - i);
|
||||
if (n <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
i += n;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex
|
||||
)
|
||||
{
|
||||
int n;
|
||||
if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength)
|
||||
{
|
||||
if (n == -1)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
throw new IOException("unexpected EOF reading netbios session header");
|
||||
}
|
||||
int t = buffer[bufferIndex] & unchecked(0xFF);
|
||||
return t;
|
||||
}
|
||||
|
||||
internal int Type;
|
||||
|
||||
internal int Length;
|
||||
|
||||
public virtual int WriteWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
Length = WriteTrailerWireFormat(dst, dstIndex + HeaderLength);
|
||||
WriteHeaderWireFormat(dst, dstIndex);
|
||||
return HeaderLength + Length;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex
|
||||
)
|
||||
{
|
||||
ReadHeaderWireFormat(@in, buffer, bufferIndex);
|
||||
return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex);
|
||||
}
|
||||
|
||||
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex++] = unchecked((byte)Type);
|
||||
if (Length > unchecked(0x0000FFFF))
|
||||
{
|
||||
dst[dstIndex] = unchecked(unchecked(0x01));
|
||||
}
|
||||
dstIndex++;
|
||||
WriteInt2(Length, dst, dstIndex);
|
||||
return HeaderLength;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal virtual int ReadHeaderWireFormat(InputStream @in, byte[] buffer, int bufferIndex
|
||||
)
|
||||
{
|
||||
Type = buffer[bufferIndex++] & unchecked(0xFF);
|
||||
Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16) + ReadInt2(buffer
|
||||
, bufferIndex + 1);
|
||||
return HeaderLength;
|
||||
}
|
||||
|
||||
internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex);
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
|
||||
);
|
||||
}
|
||||
}
|
||||
197
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs
Normal file
197
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmFlags.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Ntlmssp
|
||||
{
|
||||
/// <summary>Flags used during negotiation of NTLMSSP authentication.</summary>
|
||||
/// <remarks>Flags used during negotiation of NTLMSSP authentication.</remarks>
|
||||
public abstract class NtlmFlags
|
||||
{
|
||||
/// <summary>Indicates whether Unicode strings are supported or used.</summary>
|
||||
/// <remarks>Indicates whether Unicode strings are supported or used.</remarks>
|
||||
public const int NtlmsspNegotiateUnicode = unchecked(0x00000001);
|
||||
|
||||
/// <summary>Indicates whether OEM strings are supported or used.</summary>
|
||||
/// <remarks>Indicates whether OEM strings are supported or used.</remarks>
|
||||
public const int NtlmsspNegotiateOem = unchecked(0x00000002);
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the authentication target is requested from
|
||||
/// the server.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indicates whether the authentication target is requested from
|
||||
/// the server.
|
||||
/// </remarks>
|
||||
public const int NtlmsspRequestTarget = unchecked(0x00000004);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies that communication across the authenticated channel
|
||||
/// should carry a digital signature (message integrity).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Specifies that communication across the authenticated channel
|
||||
/// should carry a digital signature (message integrity).
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateSign = unchecked(0x00000010);
|
||||
|
||||
/// <summary>
|
||||
/// Specifies that communication across the authenticated channel
|
||||
/// should be encrypted (message confidentiality).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Specifies that communication across the authenticated channel
|
||||
/// should be encrypted (message confidentiality).
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateSeal = unchecked(0x00000020);
|
||||
|
||||
/// <summary>Indicates datagram authentication.</summary>
|
||||
/// <remarks>Indicates datagram authentication.</remarks>
|
||||
public const int NtlmsspNegotiateDatagramStyle = unchecked(0x00000040);
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the LAN Manager session key should be used for
|
||||
/// signing and sealing authenticated communication.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indicates that the LAN Manager session key should be used for
|
||||
/// signing and sealing authenticated communication.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateLmKey = unchecked(0x00000080);
|
||||
|
||||
public const int NtlmsspNegotiateNetware = unchecked(0x00000100);
|
||||
|
||||
/// <summary>Indicates support for NTLM authentication.</summary>
|
||||
/// <remarks>Indicates support for NTLM authentication.</remarks>
|
||||
public const int NtlmsspNegotiateNtlm = unchecked(0x00000200);
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the OEM-formatted domain name in which the
|
||||
/// client workstation has membership is supplied in the Type-1 message.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indicates whether the OEM-formatted domain name in which the
|
||||
/// client workstation has membership is supplied in the Type-1 message.
|
||||
/// This is used in the negotation of local authentication.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateOemDomainSupplied = unchecked(0x00001000);
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether the OEM-formatted workstation name is supplied
|
||||
/// in the Type-1 message.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indicates whether the OEM-formatted workstation name is supplied
|
||||
/// in the Type-1 message. This is used in the negotiation of local
|
||||
/// authentication.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateOemWorkstationSupplied = unchecked(0x00002000);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the server to indicate that the server and client are
|
||||
/// on the same machine.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sent by the server to indicate that the server and client are
|
||||
/// on the same machine. This implies that the server will include
|
||||
/// a local security context handle in the Type 2 message, for
|
||||
/// use in local authentication.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateLocalCall = unchecked(0x00004000);
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that authenticated communication between the client
|
||||
/// and server should carry a "dummy" digital signature.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indicates that authenticated communication between the client
|
||||
/// and server should carry a "dummy" digital signature.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateAlwaysSign = unchecked(0x00008000);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the server in the Type 2 message to indicate that the
|
||||
/// target authentication realm is a domain.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sent by the server in the Type 2 message to indicate that the
|
||||
/// target authentication realm is a domain.
|
||||
/// </remarks>
|
||||
public const int NtlmsspTargetTypeDomain = unchecked(0x00010000);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the server in the Type 2 message to indicate that the
|
||||
/// target authentication realm is a server.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sent by the server in the Type 2 message to indicate that the
|
||||
/// target authentication realm is a server.
|
||||
/// </remarks>
|
||||
public const int NtlmsspTargetTypeServer = unchecked(0x00020000);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the server in the Type 2 message to indicate that the
|
||||
/// target authentication realm is a share (presumably for share-level
|
||||
/// authentication).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sent by the server in the Type 2 message to indicate that the
|
||||
/// target authentication realm is a share (presumably for share-level
|
||||
/// authentication).
|
||||
/// </remarks>
|
||||
public const int NtlmsspTargetTypeShare = unchecked(0x00040000);
|
||||
|
||||
/// <summary>
|
||||
/// Indicates that the NTLM2 signing and sealing scheme should be used
|
||||
/// for protecting authenticated communications.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Indicates that the NTLM2 signing and sealing scheme should be used
|
||||
/// for protecting authenticated communications. This refers to a
|
||||
/// particular session security scheme, and is not related to the use
|
||||
/// of NTLMv2 authentication.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateNtlm2 = unchecked(0x00080000);
|
||||
|
||||
public const int NtlmsspRequestInitResponse = unchecked(0x00100000);
|
||||
|
||||
public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000);
|
||||
|
||||
public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Sent by the server in the Type 2 message to indicate that it is
|
||||
/// including a Target Information block in the message.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sent by the server in the Type 2 message to indicate that it is
|
||||
/// including a Target Information block in the message. The Target
|
||||
/// Information block is used in the calculation of the NTLMv2 response.
|
||||
/// </remarks>
|
||||
public const int NtlmsspNegotiateTargetInfo = unchecked(0x00800000);
|
||||
|
||||
/// <summary>Indicates that 128-bit encryption is supported.</summary>
|
||||
/// <remarks>Indicates that 128-bit encryption is supported.</remarks>
|
||||
public const int NtlmsspNegotiate128 = unchecked(0x20000000);
|
||||
|
||||
public const int NtlmsspNegotiateKeyExch = unchecked(0x40000000);
|
||||
|
||||
/// <summary>Indicates that 56-bit encryption is supported.</summary>
|
||||
/// <remarks>Indicates that 56-bit encryption is supported.</remarks>
|
||||
public const int NtlmsspNegotiate56 = unchecked((int)(0x80000000));
|
||||
}
|
||||
}
|
||||
140
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs
Normal file
140
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/NtlmMessage.cs
Normal file
@@ -0,0 +1,140 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
|
||||
namespace SharpCifs.Ntlmssp
|
||||
{
|
||||
/// <summary>Abstract superclass for all NTLMSSP messages.</summary>
|
||||
/// <remarks>Abstract superclass for all NTLMSSP messages.</remarks>
|
||||
public abstract class NtlmMessage : NtlmFlags
|
||||
{
|
||||
/// <summary>The NTLMSSP "preamble".</summary>
|
||||
/// <remarks>The NTLMSSP "preamble".</remarks>
|
||||
protected internal static readonly byte[] NtlmsspSignature = { unchecked(
|
||||
(byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')),
|
||||
unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte
|
||||
)('S')), unchecked((byte)('P')), unchecked(0) };
|
||||
|
||||
private static readonly string OemEncoding = Config.DefaultOemEncoding;
|
||||
|
||||
protected internal static readonly string UniEncoding = "UTF-16LE";
|
||||
|
||||
private int _flags;
|
||||
|
||||
/// <summary>Returns the flags currently in use for this message.</summary>
|
||||
/// <remarks>Returns the flags currently in use for this message.</remarks>
|
||||
/// <returns>
|
||||
/// An <code>int</code> containing the flags in use for this
|
||||
/// message.
|
||||
/// </returns>
|
||||
public virtual int GetFlags()
|
||||
{
|
||||
return _flags;
|
||||
}
|
||||
|
||||
/// <summary>Sets the flags for this message.</summary>
|
||||
/// <remarks>Sets the flags for this message.</remarks>
|
||||
/// <param name="flags">The flags for this message.</param>
|
||||
public virtual void SetFlags(int flags)
|
||||
{
|
||||
this._flags = flags;
|
||||
}
|
||||
|
||||
/// <summary>Returns the status of the specified flag.</summary>
|
||||
/// <remarks>Returns the status of the specified flag.</remarks>
|
||||
/// <param name="flag">The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).</param>
|
||||
/// <returns>A <code>boolean</code> indicating whether the flag is set.</returns>
|
||||
public virtual bool GetFlag(int flag)
|
||||
{
|
||||
return (GetFlags() & flag) != 0;
|
||||
}
|
||||
|
||||
/// <summary>Sets or clears the specified flag.</summary>
|
||||
/// <remarks>Sets or clears the specified flag.</remarks>
|
||||
/// <param name="flag">
|
||||
/// The flag to set/clear (i.e.,
|
||||
/// <code>NTLMSSP_NEGOTIATE_OEM</code>).
|
||||
/// </param>
|
||||
/// <param name="value">
|
||||
/// Indicates whether to set (<code>true</code>) or
|
||||
/// clear (<code>false</code>) the specified flag.
|
||||
/// </param>
|
||||
public virtual void SetFlag(int flag, bool value)
|
||||
{
|
||||
SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff)
|
||||
) ^ flag)));
|
||||
}
|
||||
|
||||
internal static int ReadULong(byte[] src, int index)
|
||||
{
|
||||
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index
|
||||
+ 3] & unchecked(0xff)) << 24);
|
||||
}
|
||||
|
||||
internal static int ReadUShort(byte[] src, int index)
|
||||
{
|
||||
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8);
|
||||
}
|
||||
|
||||
internal static byte[] ReadSecurityBuffer(byte[] src, int index)
|
||||
{
|
||||
int length = ReadUShort(src, index);
|
||||
int offset = ReadULong(src, index + 4);
|
||||
byte[] buffer = new byte[length];
|
||||
Array.Copy(src, offset, buffer, 0, length);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
internal static void WriteULong(byte[] dest, int offset, int value)
|
||||
{
|
||||
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
|
||||
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
|
||||
dest[offset + 2] = unchecked((byte)(value >> 16 & unchecked(0xff)));
|
||||
dest[offset + 3] = unchecked((byte)(value >> 24 & unchecked(0xff)));
|
||||
}
|
||||
|
||||
internal static void WriteUShort(byte[] dest, int offset, int value)
|
||||
{
|
||||
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
|
||||
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
|
||||
}
|
||||
|
||||
internal static void WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset,
|
||||
byte[] src)
|
||||
{
|
||||
int length = (src != null) ? src.Length : 0;
|
||||
if (length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
WriteUShort(dest, offset, length);
|
||||
WriteUShort(dest, offset + 2, length);
|
||||
WriteULong(dest, offset + 4, bodyOffset);
|
||||
Array.Copy(src, 0, dest, bodyOffset, length);
|
||||
}
|
||||
|
||||
internal static string GetOemEncoding()
|
||||
{
|
||||
return OemEncoding;
|
||||
}
|
||||
|
||||
/// <summary>Returns the raw byte representation of this message.</summary>
|
||||
/// <remarks>Returns the raw byte representation of this message.</remarks>
|
||||
/// <returns>A <code>byte[]</code> containing the raw message material.</returns>
|
||||
public abstract byte[] ToByteArray();
|
||||
}
|
||||
}
|
||||
249
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs
Normal file
249
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type1Message.cs
Normal file
@@ -0,0 +1,249 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpCifs.Netbios;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Ntlmssp
|
||||
{
|
||||
/// <summary>Represents an NTLMSSP Type-1 message.</summary>
|
||||
/// <remarks>Represents an NTLMSSP Type-1 message.</remarks>
|
||||
public class Type1Message : NtlmMessage
|
||||
{
|
||||
private static readonly int DefaultFlags;
|
||||
|
||||
private static readonly string DefaultDomain;
|
||||
|
||||
private static readonly string DefaultWorkstation;
|
||||
|
||||
private string _suppliedDomain;
|
||||
|
||||
private string _suppliedWorkstation;
|
||||
|
||||
static Type1Message()
|
||||
{
|
||||
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
|
||||
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
|
||||
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
|
||||
string defaultWorkstation = null;
|
||||
try
|
||||
{
|
||||
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
}
|
||||
DefaultWorkstation = defaultWorkstation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Type-1 message using default values from the current
|
||||
/// environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Creates a Type-1 message using default values from the current
|
||||
/// environment.
|
||||
/// </remarks>
|
||||
public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation
|
||||
())
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-1 message with the specified parameters.</summary>
|
||||
/// <remarks>Creates a Type-1 message with the specified parameters.</remarks>
|
||||
/// <param name="flags">The flags to apply to this message.</param>
|
||||
/// <param name="suppliedDomain">The supplied authentication domain.</param>
|
||||
/// <param name="suppliedWorkstation">The supplied workstation name.</param>
|
||||
public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation)
|
||||
{
|
||||
SetFlags(GetDefaultFlags() | flags);
|
||||
SetSuppliedDomain(suppliedDomain);
|
||||
if (suppliedWorkstation == null)
|
||||
{
|
||||
suppliedWorkstation = GetDefaultWorkstation();
|
||||
}
|
||||
SetSuppliedWorkstation(suppliedWorkstation);
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary>
|
||||
/// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks>
|
||||
/// <param name="material">The raw Type-1 material used to construct this message.</param>
|
||||
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
|
||||
/// </exception>
|
||||
public Type1Message(byte[] material)
|
||||
{
|
||||
Parse(material);
|
||||
}
|
||||
|
||||
/// <summary>Returns the supplied authentication domain.</summary>
|
||||
/// <remarks>Returns the supplied authentication domain.</remarks>
|
||||
/// <returns>A <code>String</code> containing the supplied domain.</returns>
|
||||
public virtual string GetSuppliedDomain()
|
||||
{
|
||||
return _suppliedDomain;
|
||||
}
|
||||
|
||||
/// <summary>Sets the supplied authentication domain for this message.</summary>
|
||||
/// <remarks>Sets the supplied authentication domain for this message.</remarks>
|
||||
/// <param name="suppliedDomain">The supplied domain for this message.</param>
|
||||
public virtual void SetSuppliedDomain(string suppliedDomain)
|
||||
{
|
||||
this._suppliedDomain = suppliedDomain;
|
||||
}
|
||||
|
||||
/// <summary>Returns the supplied workstation name.</summary>
|
||||
/// <remarks>Returns the supplied workstation name.</remarks>
|
||||
/// <returns>A <code>String</code> containing the supplied workstation name.</returns>
|
||||
public virtual string GetSuppliedWorkstation()
|
||||
{
|
||||
return _suppliedWorkstation;
|
||||
}
|
||||
|
||||
/// <summary>Sets the supplied workstation name for this message.</summary>
|
||||
/// <remarks>Sets the supplied workstation name for this message.</remarks>
|
||||
/// <param name="suppliedWorkstation">The supplied workstation for this message.</param>
|
||||
public virtual void SetSuppliedWorkstation(string suppliedWorkstation)
|
||||
{
|
||||
this._suppliedWorkstation = suppliedWorkstation;
|
||||
}
|
||||
|
||||
public override byte[] ToByteArray()
|
||||
{
|
||||
try
|
||||
{
|
||||
string suppliedDomain = GetSuppliedDomain();
|
||||
string suppliedWorkstation = GetSuppliedWorkstation();
|
||||
int flags = GetFlags();
|
||||
bool hostInfo = false;
|
||||
byte[] domain = new byte[0];
|
||||
if (!string.IsNullOrEmpty(suppliedDomain))
|
||||
{
|
||||
hostInfo = true;
|
||||
flags |= NtlmsspNegotiateOemDomainSupplied;
|
||||
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding
|
||||
());
|
||||
}
|
||||
else
|
||||
{
|
||||
flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff)));
|
||||
}
|
||||
byte[] workstation = new byte[0];
|
||||
if (!string.IsNullOrEmpty(suppliedWorkstation))
|
||||
{
|
||||
hostInfo = true;
|
||||
flags |= NtlmsspNegotiateOemWorkstationSupplied;
|
||||
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding
|
||||
());
|
||||
}
|
||||
else
|
||||
{
|
||||
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff
|
||||
)));
|
||||
}
|
||||
byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16
|
||||
];
|
||||
Array.Copy(NtlmsspSignature, 0, type1, 0, 8);
|
||||
WriteULong(type1, 8, 1);
|
||||
WriteULong(type1, 12, flags);
|
||||
if (hostInfo)
|
||||
{
|
||||
WriteSecurityBuffer(type1, 16, 32, domain);
|
||||
WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation);
|
||||
}
|
||||
return type1;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new InvalidOperationException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string suppliedDomain = GetSuppliedDomain();
|
||||
string suppliedWorkstation = GetSuppliedWorkstation();
|
||||
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null"
|
||||
) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null"
|
||||
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default flags for a generic Type-1 message in the
|
||||
/// current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the default flags for a generic Type-1 message in the
|
||||
/// current environment.
|
||||
/// </remarks>
|
||||
/// <returns>An <code>int</code> containing the default flags.</returns>
|
||||
public static int GetDefaultFlags()
|
||||
{
|
||||
return DefaultFlags;
|
||||
}
|
||||
|
||||
/// <summary>Returns the default domain from the current environment.</summary>
|
||||
/// <remarks>Returns the default domain from the current environment.</remarks>
|
||||
/// <returns>A <code>String</code> containing the default domain.</returns>
|
||||
public static string GetDefaultDomain()
|
||||
{
|
||||
return DefaultDomain;
|
||||
}
|
||||
|
||||
/// <summary>Returns the default workstation from the current environment.</summary>
|
||||
/// <remarks>Returns the default workstation from the current environment.</remarks>
|
||||
/// <returns>A <code>String</code> containing the default workstation.</returns>
|
||||
public static string GetDefaultWorkstation()
|
||||
{
|
||||
return DefaultWorkstation;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
private void Parse(byte[] material)
|
||||
{
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
if (material[i] != NtlmsspSignature[i])
|
||||
{
|
||||
throw new IOException("Not an NTLMSSP message.");
|
||||
}
|
||||
}
|
||||
if (ReadULong(material, 8) != 1)
|
||||
{
|
||||
throw new IOException("Not a Type 1 message.");
|
||||
}
|
||||
int flags = ReadULong(material, 12);
|
||||
string suppliedDomain = null;
|
||||
if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0)
|
||||
{
|
||||
byte[] domain = ReadSecurityBuffer(material, 16);
|
||||
suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding());
|
||||
}
|
||||
string suppliedWorkstation = null;
|
||||
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
|
||||
{
|
||||
byte[] workstation = ReadSecurityBuffer(material, 24);
|
||||
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding
|
||||
());
|
||||
}
|
||||
SetFlags(flags);
|
||||
SetSuppliedDomain(suppliedDomain);
|
||||
SetSuppliedWorkstation(suppliedWorkstation);
|
||||
}
|
||||
}
|
||||
}
|
||||
438
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs
Normal file
438
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type2Message.cs
Normal file
@@ -0,0 +1,438 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpCifs.Netbios;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Ntlmssp
|
||||
{
|
||||
/// <summary>Represents an NTLMSSP Type-2 message.</summary>
|
||||
/// <remarks>Represents an NTLMSSP Type-2 message.</remarks>
|
||||
public class Type2Message : NtlmMessage
|
||||
{
|
||||
private static readonly int DefaultFlags;
|
||||
|
||||
private static readonly string DefaultDomain;
|
||||
|
||||
private static readonly byte[] DefaultTargetInformation;
|
||||
|
||||
private byte[] _challenge;
|
||||
|
||||
private string _target;
|
||||
|
||||
private byte[] _context;
|
||||
|
||||
private byte[] _targetInformation;
|
||||
|
||||
static Type2Message()
|
||||
{
|
||||
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
|
||||
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
|
||||
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
|
||||
byte[] domain = new byte[0];
|
||||
if (DefaultDomain != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
domain = Runtime.GetBytesForString(DefaultDomain, UniEncoding);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
int domainLength = domain.Length;
|
||||
byte[] server = new byte[0];
|
||||
try
|
||||
{
|
||||
string host = NbtAddress.GetLocalHost().GetHostName();
|
||||
if (host != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
server = Runtime.GetBytesForString(host, UniEncoding);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
}
|
||||
int serverLength = server.Length;
|
||||
byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength
|
||||
> 0 ? serverLength + 4 : 0) + 4];
|
||||
int offset = 0;
|
||||
if (domainLength > 0)
|
||||
{
|
||||
WriteUShort(targetInfo, offset, 2);
|
||||
offset += 2;
|
||||
WriteUShort(targetInfo, offset, domainLength);
|
||||
offset += 2;
|
||||
Array.Copy(domain, 0, targetInfo, offset, domainLength);
|
||||
offset += domainLength;
|
||||
}
|
||||
if (serverLength > 0)
|
||||
{
|
||||
WriteUShort(targetInfo, offset, 1);
|
||||
offset += 2;
|
||||
WriteUShort(targetInfo, offset, serverLength);
|
||||
offset += 2;
|
||||
Array.Copy(server, 0, targetInfo, offset, serverLength);
|
||||
}
|
||||
DefaultTargetInformation = targetInfo;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Type-2 message using default values from the current
|
||||
/// environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Creates a Type-2 message using default values from the current
|
||||
/// environment.
|
||||
/// </remarks>
|
||||
public Type2Message() : this(GetDefaultFlags(), null, null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Type-2 message in response to the given Type-1 message
|
||||
/// using default values from the current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Creates a Type-2 message in response to the given Type-1 message
|
||||
/// using default values from the current environment.
|
||||
/// </remarks>
|
||||
/// <param name="type1">The Type-1 message which this represents a response to.</param>
|
||||
public Type2Message(Type1Message type1) : this(type1, null, null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-2 message in response to the given Type-1 message.</summary>
|
||||
/// <remarks>Creates a Type-2 message in response to the given Type-1 message.</remarks>
|
||||
/// <param name="type1">The Type-1 message which this represents a response to.</param>
|
||||
/// <param name="challenge">The challenge from the domain controller/server.</param>
|
||||
/// <param name="target">The authentication target.</param>
|
||||
public Type2Message(Type1Message type1, byte[] challenge, string target) : this(GetDefaultFlags
|
||||
(type1), challenge, (type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget
|
||||
)) ? GetDefaultDomain() : target)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-2 message with the specified parameters.</summary>
|
||||
/// <remarks>Creates a Type-2 message with the specified parameters.</remarks>
|
||||
/// <param name="flags">The flags to apply to this message.</param>
|
||||
/// <param name="challenge">The challenge from the domain controller/server.</param>
|
||||
/// <param name="target">The authentication target.</param>
|
||||
public Type2Message(int flags, byte[] challenge, string target)
|
||||
{
|
||||
SetFlags(flags);
|
||||
SetChallenge(challenge);
|
||||
SetTarget(target);
|
||||
if (target != null)
|
||||
{
|
||||
SetTargetInformation(GetDefaultTargetInformation());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-2 message using the given raw Type-2 material.</summary>
|
||||
/// <remarks>Creates a Type-2 message using the given raw Type-2 material.</remarks>
|
||||
/// <param name="material">The raw Type-2 material used to construct this message.</param>
|
||||
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
|
||||
/// </exception>
|
||||
public Type2Message(byte[] material)
|
||||
{
|
||||
Parse(material);
|
||||
}
|
||||
|
||||
/// <summary>Returns the challenge for this message.</summary>
|
||||
/// <remarks>Returns the challenge for this message.</remarks>
|
||||
/// <returns>A <code>byte[]</code> containing the challenge.</returns>
|
||||
public virtual byte[] GetChallenge()
|
||||
{
|
||||
return _challenge;
|
||||
}
|
||||
|
||||
/// <summary>Sets the challenge for this message.</summary>
|
||||
/// <remarks>Sets the challenge for this message.</remarks>
|
||||
/// <param name="challenge">The challenge from the domain controller/server.</param>
|
||||
public virtual void SetChallenge(byte[] challenge)
|
||||
{
|
||||
this._challenge = challenge;
|
||||
}
|
||||
|
||||
/// <summary>Returns the authentication target.</summary>
|
||||
/// <remarks>Returns the authentication target.</remarks>
|
||||
/// <returns>A <code>String</code> containing the authentication target.</returns>
|
||||
public virtual string GetTarget()
|
||||
{
|
||||
return _target;
|
||||
}
|
||||
|
||||
/// <summary>Sets the authentication target.</summary>
|
||||
/// <remarks>Sets the authentication target.</remarks>
|
||||
/// <param name="target">The authentication target.</param>
|
||||
public virtual void SetTarget(string target)
|
||||
{
|
||||
this._target = target;
|
||||
}
|
||||
|
||||
/// <summary>Returns the target information block.</summary>
|
||||
/// <remarks>Returns the target information block.</remarks>
|
||||
/// <returns>
|
||||
/// A <code>byte[]</code> containing the target information block.
|
||||
/// The target information block is used by the client to create an
|
||||
/// NTLMv2 response.
|
||||
/// </returns>
|
||||
public virtual byte[] GetTargetInformation()
|
||||
{
|
||||
return _targetInformation;
|
||||
}
|
||||
|
||||
/// <summary>Sets the target information block.</summary>
|
||||
/// <remarks>
|
||||
/// Sets the target information block.
|
||||
/// The target information block is used by the client to create
|
||||
/// an NTLMv2 response.
|
||||
/// </remarks>
|
||||
/// <param name="targetInformation">The target information block.</param>
|
||||
public virtual void SetTargetInformation(byte[] targetInformation)
|
||||
{
|
||||
this._targetInformation = targetInformation;
|
||||
}
|
||||
|
||||
/// <summary>Returns the local security context.</summary>
|
||||
/// <remarks>Returns the local security context.</remarks>
|
||||
/// <returns>
|
||||
/// A <code>byte[]</code> containing the local security
|
||||
/// context. This is used by the client to negotiate local
|
||||
/// authentication.
|
||||
/// </returns>
|
||||
public virtual byte[] GetContext()
|
||||
{
|
||||
return _context;
|
||||
}
|
||||
|
||||
/// <summary>Sets the local security context.</summary>
|
||||
/// <remarks>
|
||||
/// Sets the local security context. This is used by the client
|
||||
/// to negotiate local authentication.
|
||||
/// </remarks>
|
||||
/// <param name="context">The local security context.</param>
|
||||
public virtual void SetContext(byte[] context)
|
||||
{
|
||||
this._context = context;
|
||||
}
|
||||
|
||||
public override byte[] ToByteArray()
|
||||
{
|
||||
try
|
||||
{
|
||||
string targetName = GetTarget();
|
||||
byte[] challenge = GetChallenge();
|
||||
byte[] context = GetContext();
|
||||
byte[] targetInformation = GetTargetInformation();
|
||||
int flags = GetFlags();
|
||||
byte[] target = new byte[0];
|
||||
if ((flags & NtlmsspRequestTarget) != 0)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(targetName))
|
||||
{
|
||||
target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString
|
||||
(targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper
|
||||
(), GetOemEncoding());
|
||||
}
|
||||
else
|
||||
{
|
||||
flags &= (unchecked((int)(0xffffffff)) ^ NtlmsspRequestTarget);
|
||||
}
|
||||
}
|
||||
if (targetInformation != null)
|
||||
{
|
||||
flags |= NtlmsspNegotiateTargetInfo;
|
||||
// empty context is needed for padding when t.i. is supplied.
|
||||
if (context == null)
|
||||
{
|
||||
context = new byte[8];
|
||||
}
|
||||
}
|
||||
int data = 32;
|
||||
if (context != null)
|
||||
{
|
||||
data += 8;
|
||||
}
|
||||
if (targetInformation != null)
|
||||
{
|
||||
data += 8;
|
||||
}
|
||||
byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation
|
||||
.Length : 0)];
|
||||
Array.Copy(NtlmsspSignature, 0, type2, 0, 8);
|
||||
WriteULong(type2, 8, 2);
|
||||
WriteSecurityBuffer(type2, 12, data, target);
|
||||
WriteULong(type2, 20, flags);
|
||||
Array.Copy(challenge ?? new byte[8], 0, type2, 24, 8);
|
||||
if (context != null)
|
||||
{
|
||||
Array.Copy(context, 0, type2, 32, 8);
|
||||
}
|
||||
if (targetInformation != null)
|
||||
{
|
||||
WriteSecurityBuffer(type2, 40, data + target.Length, targetInformation);
|
||||
}
|
||||
return type2;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new InvalidOperationException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string target = GetTarget();
|
||||
byte[] challenge = GetChallenge();
|
||||
byte[] context = GetContext();
|
||||
byte[] targetInformation = GetTargetInformation();
|
||||
return "Type2Message[target=" + target + ",challenge=" + (challenge == null ? "null"
|
||||
: "<" + challenge.Length + " bytes>") + ",context=" + (context == null ? "null"
|
||||
: "<" + context.Length + " bytes>") + ",targetInformation=" + (targetInformation
|
||||
== null ? "null" : "<" + targetInformation.Length + " bytes>") + ",flags=0x" +
|
||||
Hexdump.ToHexString(GetFlags(), 8) + "]";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default flags for a generic Type-2 message in the
|
||||
/// current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the default flags for a generic Type-2 message in the
|
||||
/// current environment.
|
||||
/// </remarks>
|
||||
/// <returns>An <code>int</code> containing the default flags.</returns>
|
||||
public static int GetDefaultFlags()
|
||||
{
|
||||
return DefaultFlags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default flags for a Type-2 message created in response
|
||||
/// to the given Type-1 message in the current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the default flags for a Type-2 message created in response
|
||||
/// to the given Type-1 message in the current environment.
|
||||
/// </remarks>
|
||||
/// <returns>An <code>int</code> containing the default flags.</returns>
|
||||
public static int GetDefaultFlags(Type1Message type1)
|
||||
{
|
||||
if (type1 == null)
|
||||
{
|
||||
return DefaultFlags;
|
||||
}
|
||||
int flags = NtlmsspNegotiateNtlm;
|
||||
int type1Flags = type1.GetFlags();
|
||||
flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
|
||||
: NtlmsspNegotiateOem;
|
||||
if ((type1Flags & NtlmsspRequestTarget) != 0)
|
||||
{
|
||||
string domain = GetDefaultDomain();
|
||||
if (domain != null)
|
||||
{
|
||||
flags |= NtlmsspRequestTarget | NtlmsspTargetTypeDomain;
|
||||
}
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
|
||||
/// <summary>Returns the default domain from the current environment.</summary>
|
||||
/// <remarks>Returns the default domain from the current environment.</remarks>
|
||||
/// <returns>A <code>String</code> containing the domain.</returns>
|
||||
public static string GetDefaultDomain()
|
||||
{
|
||||
return DefaultDomain;
|
||||
}
|
||||
|
||||
public static byte[] GetDefaultTargetInformation()
|
||||
{
|
||||
return DefaultTargetInformation;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
private void Parse(byte[] material)
|
||||
{
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
if (material[i] != NtlmsspSignature[i])
|
||||
{
|
||||
throw new IOException("Not an NTLMSSP message.");
|
||||
}
|
||||
}
|
||||
if (ReadULong(material, 8) != 2)
|
||||
{
|
||||
throw new IOException("Not a Type 2 message.");
|
||||
}
|
||||
int flags = ReadULong(material, 20);
|
||||
SetFlags(flags);
|
||||
string target = null;
|
||||
byte[] bytes = ReadSecurityBuffer(material, 12);
|
||||
if (bytes.Length != 0)
|
||||
{
|
||||
target = Runtime.GetStringForBytes(bytes, ((flags & NtlmsspNegotiateUnicode
|
||||
) != 0) ? UniEncoding : GetOemEncoding());
|
||||
}
|
||||
SetTarget(target);
|
||||
for (int i1 = 24; i1 < 32; i1++)
|
||||
{
|
||||
if (material[i1] != 0)
|
||||
{
|
||||
byte[] challenge = new byte[8];
|
||||
Array.Copy(material, 24, challenge, 0, 8);
|
||||
SetChallenge(challenge);
|
||||
break;
|
||||
}
|
||||
}
|
||||
int offset = ReadULong(material, 16);
|
||||
// offset of targetname start
|
||||
if (offset == 32 || material.Length == 32)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (int i2 = 32; i2 < 40; i2++)
|
||||
{
|
||||
if (material[i2] != 0)
|
||||
{
|
||||
byte[] context = new byte[8];
|
||||
Array.Copy(material, 32, context, 0, 8);
|
||||
SetContext(context);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (offset == 40 || material.Length == 40)
|
||||
{
|
||||
return;
|
||||
}
|
||||
bytes = ReadSecurityBuffer(material, 40);
|
||||
if (bytes.Length != 0)
|
||||
{
|
||||
SetTargetInformation(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
677
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs
Normal file
677
Emby.Server.Implementations/IO/SharpCifs/Ntlmssp/Type3Message.cs
Normal file
@@ -0,0 +1,677 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.IO;
|
||||
using SharpCifs.Netbios;
|
||||
using SharpCifs.Smb;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Ntlmssp
|
||||
{
|
||||
/// <summary>Represents an NTLMSSP Type-3 message.</summary>
|
||||
/// <remarks>Represents an NTLMSSP Type-3 message.</remarks>
|
||||
public class Type3Message : NtlmMessage
|
||||
{
|
||||
internal const long MillisecondsBetween1970And1601 = 11644473600000L;
|
||||
|
||||
private static readonly int DefaultFlags;
|
||||
|
||||
private static readonly string DefaultDomain;
|
||||
|
||||
private static readonly string DefaultUser;
|
||||
|
||||
private static readonly string DefaultPassword;
|
||||
|
||||
private static readonly string DefaultWorkstation;
|
||||
|
||||
private static readonly int LmCompatibility;
|
||||
|
||||
//private static readonly SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
private byte[] _lmResponse;
|
||||
|
||||
private byte[] _ntResponse;
|
||||
|
||||
private string _domain;
|
||||
|
||||
private string _user;
|
||||
|
||||
private string _workstation;
|
||||
|
||||
private byte[] _masterKey;
|
||||
|
||||
private byte[] _sessionKey;
|
||||
|
||||
static Type3Message()
|
||||
{
|
||||
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
|
||||
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
|
||||
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
|
||||
DefaultUser = Config.GetProperty("jcifs.smb.client.username", null);
|
||||
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", null);
|
||||
string defaultWorkstation = null;
|
||||
try
|
||||
{
|
||||
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
|
||||
}
|
||||
catch (UnknownHostException)
|
||||
{
|
||||
}
|
||||
DefaultWorkstation = defaultWorkstation;
|
||||
LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Type-3 message using default values from the current
|
||||
/// environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Creates a Type-3 message using default values from the current
|
||||
/// environment.
|
||||
/// </remarks>
|
||||
public Type3Message()
|
||||
{
|
||||
SetFlags(GetDefaultFlags());
|
||||
SetDomain(GetDefaultDomain());
|
||||
SetUser(GetDefaultUser());
|
||||
SetWorkstation(GetDefaultWorkstation());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a Type-3 message in response to the given Type-2 message
|
||||
/// using default values from the current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Creates a Type-3 message in response to the given Type-2 message
|
||||
/// using default values from the current environment.
|
||||
/// </remarks>
|
||||
/// <param name="type2">The Type-2 message which this represents a response to.</param>
|
||||
public Type3Message(Type2Message type2)
|
||||
{
|
||||
SetFlags(GetDefaultFlags(type2));
|
||||
SetWorkstation(GetDefaultWorkstation());
|
||||
string domain = GetDefaultDomain();
|
||||
SetDomain(domain);
|
||||
string user = GetDefaultUser();
|
||||
SetUser(user);
|
||||
string password = GetDefaultPassword();
|
||||
switch (LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
{
|
||||
SetLmResponse(GetLMResponse(type2, password));
|
||||
SetNtResponse(GetNTResponse(type2, password));
|
||||
break;
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
byte[] nt = GetNTResponse(type2, password);
|
||||
SetLmResponse(nt);
|
||||
SetNtResponse(nt);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
byte[] clientChallenge = new byte[8];
|
||||
//RANDOM.NextBytes(clientChallenge);
|
||||
SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge));
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
SetLmResponse(GetLMResponse(type2, password));
|
||||
SetNtResponse(GetNTResponse(type2, password));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-3 message in response to the given Type-2 message.</summary>
|
||||
/// <remarks>Creates a Type-3 message in response to the given Type-2 message.</remarks>
|
||||
/// <param name="type2">The Type-2 message which this represents a response to.</param>
|
||||
/// <param name="password">The password to use when constructing the response.</param>
|
||||
/// <param name="domain">The domain in which the user has an account.</param>
|
||||
/// <param name="user">The username for the authenticating user.</param>
|
||||
/// <param name="workstation">
|
||||
/// The workstation from which authentication is
|
||||
/// taking place.
|
||||
/// </param>
|
||||
public Type3Message(Type2Message type2, string password, string domain, string user
|
||||
, string workstation, int flags)
|
||||
{
|
||||
SetFlags(flags | GetDefaultFlags(type2));
|
||||
if (workstation == null)
|
||||
{
|
||||
workstation = GetDefaultWorkstation();
|
||||
}
|
||||
SetWorkstation(workstation);
|
||||
SetDomain(domain);
|
||||
SetUser(user);
|
||||
switch (LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
{
|
||||
if ((GetFlags() & NtlmsspNegotiateNtlm2) == 0)
|
||||
{
|
||||
SetLmResponse(GetLMResponse(type2, password));
|
||||
SetNtResponse(GetNTResponse(type2, password));
|
||||
}
|
||||
else
|
||||
{
|
||||
// NTLM2 Session Response
|
||||
byte[] clientChallenge = new byte[24];
|
||||
//RANDOM.NextBytes(clientChallenge);
|
||||
Arrays.Fill(clientChallenge, 8, 24, unchecked((byte)unchecked(0x00)));
|
||||
// NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient
|
||||
byte[] responseKeyNt = NtlmPasswordAuthentication.NtowFv1(password);
|
||||
byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
|
||||
type2.GetChallenge(), clientChallenge);
|
||||
SetLmResponse(clientChallenge);
|
||||
SetNtResponse(ntlm2Response);
|
||||
if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
|
||||
{
|
||||
byte[] sessionNonce = new byte[16];
|
||||
Array.Copy(type2.GetChallenge(), 0, sessionNonce, 0, 8);
|
||||
Array.Copy(clientChallenge, 0, sessionNonce, 8, 8);
|
||||
Md4 md4 = new Md4();
|
||||
md4.Update(responseKeyNt);
|
||||
byte[] userSessionKey = md4.Digest();
|
||||
Hmact64 hmac = new Hmact64(userSessionKey);
|
||||
hmac.Update(sessionNonce);
|
||||
byte[] ntlm2SessionKey = hmac.Digest();
|
||||
if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
|
||||
{
|
||||
_masterKey = new byte[16];
|
||||
//RANDOM.NextBytes(masterKey);
|
||||
byte[] exchangedKey = new byte[16];
|
||||
Rc4 rc4 = new Rc4(ntlm2SessionKey);
|
||||
rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
|
||||
SetSessionKey(exchangedKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
_masterKey = ntlm2SessionKey;
|
||||
SetSessionKey(_masterKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
byte[] nt = GetNTResponse(type2, password);
|
||||
SetLmResponse(nt);
|
||||
SetNtResponse(nt);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password
|
||||
);
|
||||
byte[] clientChallenge1 = new byte[8];
|
||||
//RANDOM.NextBytes(clientChallenge_1);
|
||||
SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1));
|
||||
byte[] clientChallenge2 = new byte[8];
|
||||
//RANDOM.NextBytes(clientChallenge2);
|
||||
SetNtResponse(GetNtlMv2Response(type2, responseKeyNt1, clientChallenge2));
|
||||
if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
|
||||
{
|
||||
Hmact64 hmac = new Hmact64(responseKeyNt1);
|
||||
hmac.Update(_ntResponse, 0, 16);
|
||||
// only first 16 bytes of ntResponse
|
||||
byte[] userSessionKey = hmac.Digest();
|
||||
if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
|
||||
{
|
||||
_masterKey = new byte[16];
|
||||
//RANDOM.NextBytes(masterKey);
|
||||
byte[] exchangedKey = new byte[16];
|
||||
Rc4 rc4 = new Rc4(userSessionKey);
|
||||
rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
|
||||
SetSessionKey(exchangedKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
_masterKey = userSessionKey;
|
||||
SetSessionKey(_masterKey);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
SetLmResponse(GetLMResponse(type2, password));
|
||||
SetNtResponse(GetNTResponse(type2, password));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-3 message with the specified parameters.</summary>
|
||||
/// <remarks>Creates a Type-3 message with the specified parameters.</remarks>
|
||||
/// <param name="flags">The flags to apply to this message.</param>
|
||||
/// <param name="lmResponse">The LanManager/LMv2 response.</param>
|
||||
/// <param name="ntResponse">The NT/NTLMv2 response.</param>
|
||||
/// <param name="domain">The domain in which the user has an account.</param>
|
||||
/// <param name="user">The username for the authenticating user.</param>
|
||||
/// <param name="workstation">
|
||||
/// The workstation from which authentication is
|
||||
/// taking place.
|
||||
/// </param>
|
||||
public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse, string domain
|
||||
, string user, string workstation)
|
||||
{
|
||||
SetFlags(flags);
|
||||
SetLmResponse(lmResponse);
|
||||
SetNtResponse(ntResponse);
|
||||
SetDomain(domain);
|
||||
SetUser(user);
|
||||
SetWorkstation(workstation);
|
||||
}
|
||||
|
||||
/// <summary>Creates a Type-3 message using the given raw Type-3 material.</summary>
|
||||
/// <remarks>Creates a Type-3 message using the given raw Type-3 material.</remarks>
|
||||
/// <param name="material">The raw Type-3 material used to construct this message.</param>
|
||||
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
|
||||
/// </exception>
|
||||
public Type3Message(byte[] material)
|
||||
{
|
||||
Parse(material);
|
||||
}
|
||||
|
||||
/// <summary>Returns the LanManager/LMv2 response.</summary>
|
||||
/// <remarks>Returns the LanManager/LMv2 response.</remarks>
|
||||
/// <returns>A <code>byte[]</code> containing the LanManager response.</returns>
|
||||
public virtual byte[] GetLMResponse()
|
||||
{
|
||||
return _lmResponse;
|
||||
}
|
||||
|
||||
/// <summary>Sets the LanManager/LMv2 response for this message.</summary>
|
||||
/// <remarks>Sets the LanManager/LMv2 response for this message.</remarks>
|
||||
/// <param name="lmResponse">The LanManager response.</param>
|
||||
public virtual void SetLmResponse(byte[] lmResponse)
|
||||
{
|
||||
this._lmResponse = lmResponse;
|
||||
}
|
||||
|
||||
/// <summary>Returns the NT/NTLMv2 response.</summary>
|
||||
/// <remarks>Returns the NT/NTLMv2 response.</remarks>
|
||||
/// <returns>A <code>byte[]</code> containing the NT/NTLMv2 response.</returns>
|
||||
public virtual byte[] GetNTResponse()
|
||||
{
|
||||
return _ntResponse;
|
||||
}
|
||||
|
||||
/// <summary>Sets the NT/NTLMv2 response for this message.</summary>
|
||||
/// <remarks>Sets the NT/NTLMv2 response for this message.</remarks>
|
||||
/// <param name="ntResponse">The NT/NTLMv2 response.</param>
|
||||
public virtual void SetNtResponse(byte[] ntResponse)
|
||||
{
|
||||
this._ntResponse = ntResponse;
|
||||
}
|
||||
|
||||
/// <summary>Returns the domain in which the user has an account.</summary>
|
||||
/// <remarks>Returns the domain in which the user has an account.</remarks>
|
||||
/// <returns>A <code>String</code> containing the domain for the user.</returns>
|
||||
public virtual string GetDomain()
|
||||
{
|
||||
return _domain;
|
||||
}
|
||||
|
||||
/// <summary>Sets the domain for this message.</summary>
|
||||
/// <remarks>Sets the domain for this message.</remarks>
|
||||
/// <param name="domain">The domain.</param>
|
||||
public virtual void SetDomain(string domain)
|
||||
{
|
||||
this._domain = domain;
|
||||
}
|
||||
|
||||
/// <summary>Returns the username for the authenticating user.</summary>
|
||||
/// <remarks>Returns the username for the authenticating user.</remarks>
|
||||
/// <returns>A <code>String</code> containing the user for this message.</returns>
|
||||
public virtual string GetUser()
|
||||
{
|
||||
return _user;
|
||||
}
|
||||
|
||||
/// <summary>Sets the user for this message.</summary>
|
||||
/// <remarks>Sets the user for this message.</remarks>
|
||||
/// <param name="user">The user.</param>
|
||||
public virtual void SetUser(string user)
|
||||
{
|
||||
this._user = user;
|
||||
}
|
||||
|
||||
/// <summary>Returns the workstation from which authentication is being performed.</summary>
|
||||
/// <remarks>Returns the workstation from which authentication is being performed.</remarks>
|
||||
/// <returns>A <code>String</code> containing the workstation.</returns>
|
||||
public virtual string GetWorkstation()
|
||||
{
|
||||
return _workstation;
|
||||
}
|
||||
|
||||
/// <summary>Sets the workstation for this message.</summary>
|
||||
/// <remarks>Sets the workstation for this message.</remarks>
|
||||
/// <param name="workstation">The workstation.</param>
|
||||
public virtual void SetWorkstation(string workstation)
|
||||
{
|
||||
this._workstation = workstation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The real session key if the regular session key is actually
|
||||
/// the encrypted version used for key exchange.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The real session key if the regular session key is actually
|
||||
/// the encrypted version used for key exchange.
|
||||
/// </remarks>
|
||||
/// <returns>A <code>byte[]</code> containing the session key.</returns>
|
||||
public virtual byte[] GetMasterKey()
|
||||
{
|
||||
return _masterKey;
|
||||
}
|
||||
|
||||
/// <summary>Returns the session key.</summary>
|
||||
/// <remarks>Returns the session key.</remarks>
|
||||
/// <returns>A <code>byte[]</code> containing the session key.</returns>
|
||||
public virtual byte[] GetSessionKey()
|
||||
{
|
||||
return _sessionKey;
|
||||
}
|
||||
|
||||
/// <summary>Sets the session key.</summary>
|
||||
/// <remarks>Sets the session key.</remarks>
|
||||
/// <param name="sessionKey">The session key.</param>
|
||||
public virtual void SetSessionKey(byte[] sessionKey)
|
||||
{
|
||||
this._sessionKey = sessionKey;
|
||||
}
|
||||
|
||||
public override byte[] ToByteArray()
|
||||
{
|
||||
try
|
||||
{
|
||||
int flags = GetFlags();
|
||||
bool unicode = (flags & NtlmsspNegotiateUnicode) != 0;
|
||||
string oem = unicode ? null : GetOemEncoding();
|
||||
string domainName = GetDomain();
|
||||
byte[] domain = null;
|
||||
if (!string.IsNullOrEmpty(domainName))
|
||||
{
|
||||
domain = unicode ? Runtime.GetBytesForString(domainName, UniEncoding) :
|
||||
Runtime.GetBytesForString(domainName, oem);
|
||||
}
|
||||
int domainLength = (domain != null) ? domain.Length : 0;
|
||||
string userName = GetUser();
|
||||
byte[] user = null;
|
||||
if (!string.IsNullOrEmpty(userName))
|
||||
{
|
||||
user = unicode ? Runtime.GetBytesForString(userName, UniEncoding) : Runtime.GetBytesForString
|
||||
(userName.ToUpper(), oem);
|
||||
}
|
||||
int userLength = (user != null) ? user.Length : 0;
|
||||
string workstationName = GetWorkstation();
|
||||
byte[] workstation = null;
|
||||
if (!string.IsNullOrEmpty(workstationName))
|
||||
{
|
||||
workstation = unicode ? Runtime.GetBytesForString(workstationName, UniEncoding
|
||||
) : Runtime.GetBytesForString(workstationName.ToUpper(), oem);
|
||||
}
|
||||
int workstationLength = (workstation != null) ? workstation.Length : 0;
|
||||
byte[] lmResponse = GetLMResponse();
|
||||
int lmLength = (lmResponse != null) ? lmResponse.Length : 0;
|
||||
byte[] ntResponse = GetNTResponse();
|
||||
int ntLength = (ntResponse != null) ? ntResponse.Length : 0;
|
||||
byte[] sessionKey = GetSessionKey();
|
||||
int keyLength = (sessionKey != null) ? sessionKey.Length : 0;
|
||||
byte[] type3 = new byte[64 + domainLength + userLength + workstationLength + lmLength
|
||||
+ ntLength + keyLength];
|
||||
Array.Copy(NtlmsspSignature, 0, type3, 0, 8);
|
||||
WriteULong(type3, 8, 3);
|
||||
int offset = 64;
|
||||
WriteSecurityBuffer(type3, 12, offset, lmResponse);
|
||||
offset += lmLength;
|
||||
WriteSecurityBuffer(type3, 20, offset, ntResponse);
|
||||
offset += ntLength;
|
||||
WriteSecurityBuffer(type3, 28, offset, domain);
|
||||
offset += domainLength;
|
||||
WriteSecurityBuffer(type3, 36, offset, user);
|
||||
offset += userLength;
|
||||
WriteSecurityBuffer(type3, 44, offset, workstation);
|
||||
offset += workstationLength;
|
||||
WriteSecurityBuffer(type3, 52, offset, sessionKey);
|
||||
WriteULong(type3, 60, flags);
|
||||
return type3;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
throw new InvalidOperationException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string user = GetUser();
|
||||
string domain = GetDomain();
|
||||
string workstation = GetWorkstation();
|
||||
byte[] lmResponse = GetLMResponse();
|
||||
byte[] ntResponse = GetNTResponse();
|
||||
byte[] sessionKey = GetSessionKey();
|
||||
return "Type3Message[domain=" + domain + ",user=" + user + ",workstation=" + workstation
|
||||
+ ",lmResponse=" + (lmResponse == null ? "null" : "<" + lmResponse.Length + " bytes>"
|
||||
) + ",ntResponse=" + (ntResponse == null ? "null" : "<" + ntResponse.Length + " bytes>"
|
||||
) + ",sessionKey=" + (sessionKey == null ? "null" : "<" + sessionKey.Length + " bytes>"
|
||||
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default flags for a generic Type-3 message in the
|
||||
/// current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the default flags for a generic Type-3 message in the
|
||||
/// current environment.
|
||||
/// </remarks>
|
||||
/// <returns>An <code>int</code> containing the default flags.</returns>
|
||||
public static int GetDefaultFlags()
|
||||
{
|
||||
return DefaultFlags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the default flags for a Type-3 message created in response
|
||||
/// to the given Type-2 message in the current environment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the default flags for a Type-3 message created in response
|
||||
/// to the given Type-2 message in the current environment.
|
||||
/// </remarks>
|
||||
/// <returns>An <code>int</code> containing the default flags.</returns>
|
||||
public static int GetDefaultFlags(Type2Message type2)
|
||||
{
|
||||
if (type2 == null)
|
||||
{
|
||||
return DefaultFlags;
|
||||
}
|
||||
int flags = NtlmsspNegotiateNtlm;
|
||||
flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
|
||||
: NtlmsspNegotiateOem;
|
||||
return flags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the LanManager response to the given Type-2 message using
|
||||
/// the supplied password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Constructs the LanManager response to the given Type-2 message using
|
||||
/// the supplied password.
|
||||
/// </remarks>
|
||||
/// <param name="type2">The Type-2 message.</param>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <returns>A <code>byte[]</code> containing the LanManager response.</returns>
|
||||
public static byte[] GetLMResponse(Type2Message type2, string password)
|
||||
{
|
||||
if (type2 == null || password == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return NtlmPasswordAuthentication.GetPreNtlmResponse(password, type2.GetChallenge
|
||||
());
|
||||
}
|
||||
|
||||
public static byte[] GetLMv2Response(Type2Message type2, string domain, string user
|
||||
, string password, byte[] clientChallenge)
|
||||
{
|
||||
if (type2 == null || domain == null || user == null || password == null || clientChallenge
|
||||
== null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return NtlmPasswordAuthentication.GetLMv2Response(domain, user, password, type2.GetChallenge
|
||||
(), clientChallenge);
|
||||
}
|
||||
|
||||
public static byte[] GetNtlMv2Response(Type2Message type2, byte[] responseKeyNt,
|
||||
byte[] clientChallenge)
|
||||
{
|
||||
if (type2 == null || responseKeyNt == null || clientChallenge == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
long nanos1601 = (Runtime.CurrentTimeMillis() + MillisecondsBetween1970And1601
|
||||
) * 10000L;
|
||||
return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, type2.GetChallenge
|
||||
(), clientChallenge, nanos1601, type2.GetTargetInformation());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the NT response to the given Type-2 message using
|
||||
/// the supplied password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Constructs the NT response to the given Type-2 message using
|
||||
/// the supplied password.
|
||||
/// </remarks>
|
||||
/// <param name="type2">The Type-2 message.</param>
|
||||
/// <param name="password">The password.</param>
|
||||
/// <returns>A <code>byte[]</code> containing the NT response.</returns>
|
||||
public static byte[] GetNTResponse(Type2Message type2, string password)
|
||||
{
|
||||
if (type2 == null || password == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return NtlmPasswordAuthentication.GetNtlmResponse(password, type2.GetChallenge());
|
||||
}
|
||||
|
||||
/// <summary>Returns the default domain from the current environment.</summary>
|
||||
/// <remarks>Returns the default domain from the current environment.</remarks>
|
||||
/// <returns>The default domain.</returns>
|
||||
public static string GetDefaultDomain()
|
||||
{
|
||||
return DefaultDomain;
|
||||
}
|
||||
|
||||
/// <summary>Returns the default user from the current environment.</summary>
|
||||
/// <remarks>Returns the default user from the current environment.</remarks>
|
||||
/// <returns>The default user.</returns>
|
||||
public static string GetDefaultUser()
|
||||
{
|
||||
return DefaultUser;
|
||||
}
|
||||
|
||||
/// <summary>Returns the default password from the current environment.</summary>
|
||||
/// <remarks>Returns the default password from the current environment.</remarks>
|
||||
/// <returns>The default password.</returns>
|
||||
public static string GetDefaultPassword()
|
||||
{
|
||||
return DefaultPassword;
|
||||
}
|
||||
|
||||
/// <summary>Returns the default workstation from the current environment.</summary>
|
||||
/// <remarks>Returns the default workstation from the current environment.</remarks>
|
||||
/// <returns>The default workstation.</returns>
|
||||
public static string GetDefaultWorkstation()
|
||||
{
|
||||
return DefaultWorkstation;
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
private void Parse(byte[] material)
|
||||
{
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
if (material[i] != NtlmsspSignature[i])
|
||||
{
|
||||
throw new IOException("Not an NTLMSSP message.");
|
||||
}
|
||||
}
|
||||
if (ReadULong(material, 8) != 3)
|
||||
{
|
||||
throw new IOException("Not a Type 3 message.");
|
||||
}
|
||||
byte[] lmResponse = ReadSecurityBuffer(material, 12);
|
||||
int lmResponseOffset = ReadULong(material, 16);
|
||||
byte[] ntResponse = ReadSecurityBuffer(material, 20);
|
||||
int ntResponseOffset = ReadULong(material, 24);
|
||||
byte[] domain = ReadSecurityBuffer(material, 28);
|
||||
int domainOffset = ReadULong(material, 32);
|
||||
byte[] user = ReadSecurityBuffer(material, 36);
|
||||
int userOffset = ReadULong(material, 40);
|
||||
byte[] workstation = ReadSecurityBuffer(material, 44);
|
||||
int workstationOffset = ReadULong(material, 48);
|
||||
int flags;
|
||||
string charset;
|
||||
byte[] _sessionKey = null;
|
||||
if (lmResponseOffset == 52 || ntResponseOffset == 52 || domainOffset == 52 || userOffset
|
||||
== 52 || workstationOffset == 52)
|
||||
{
|
||||
flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem;
|
||||
charset = GetOemEncoding();
|
||||
}
|
||||
else
|
||||
{
|
||||
_sessionKey = ReadSecurityBuffer(material, 52);
|
||||
flags = ReadULong(material, 60);
|
||||
charset = ((flags & NtlmsspNegotiateUnicode) != 0) ? UniEncoding : GetOemEncoding
|
||||
();
|
||||
}
|
||||
SetSessionKey(_sessionKey);
|
||||
SetFlags(flags);
|
||||
SetLmResponse(lmResponse);
|
||||
SetNtResponse(ntResponse);
|
||||
SetDomain(Runtime.GetStringForBytes(domain, charset));
|
||||
SetUser(Runtime.GetStringForBytes(user, charset));
|
||||
SetWorkstation(Runtime.GetStringForBytes(workstation, charset));
|
||||
}
|
||||
}
|
||||
}
|
||||
287
Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs
Normal file
287
Emby.Server.Implementations/IO/SharpCifs/Smb/ACE.cs
Normal file
@@ -0,0 +1,287 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.Text;
|
||||
using SharpCifs.Util;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
/// <summary>
|
||||
/// An Access Control Entry (ACE) is an element in a security descriptor
|
||||
/// such as those associated with files and directories.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An Access Control Entry (ACE) is an element in a security descriptor
|
||||
/// such as those associated with files and directories. The Windows OS
|
||||
/// determines which users have the necessary permissions to access objects
|
||||
/// based on these entries.
|
||||
/// <p>
|
||||
/// To fully understand the information exposed by this class a description
|
||||
/// of the access check algorithm used by Windows is required. The following
|
||||
/// is a basic description of the algorithm. For a more complete description
|
||||
/// we recommend reading the section on Access Control in Keith Brown's
|
||||
/// "The .NET Developer's Guide to Windows Security" (which is also
|
||||
/// available online).
|
||||
/// <p>
|
||||
/// Direct ACEs are evaluated first in order. The SID of the user performing
|
||||
/// the operation and the desired access bits are compared to the SID
|
||||
/// and access mask of each ACE. If the SID matches, the allow/deny flags
|
||||
/// and access mask are considered. If the ACE is a "deny"
|
||||
/// ACE and <i>any</i> of the desired access bits match bits in the access
|
||||
/// mask of the ACE, the whole access check fails. If the ACE is an "allow"
|
||||
/// ACE and <i>all</i> of the bits in the desired access bits match bits in
|
||||
/// the access mask of the ACE, the access check is successful. Otherwise,
|
||||
/// more ACEs are evaluated until all desired access bits (combined)
|
||||
/// are "allowed". If all of the desired access bits are not "allowed"
|
||||
/// the then same process is repeated for inherited ACEs.
|
||||
/// <p>
|
||||
/// For example, if user <tt>WNET\alice</tt> tries to open a file
|
||||
/// with desired access bits <tt>0x00000003</tt> (<tt>FILE_READ_DATA |
|
||||
/// FILE_WRITE_DATA</tt>) and the target file has the following security
|
||||
/// descriptor ACEs:
|
||||
/// <pre>
|
||||
/// Allow WNET\alice 0x001200A9 Direct
|
||||
/// Allow Administrators 0x001F01FF Inherited
|
||||
/// Allow SYSTEM 0x001F01FF Inherited
|
||||
/// </pre>
|
||||
/// the access check would fail because the direct ACE has an access mask
|
||||
/// of <tt>0x001200A9</tt> which doesn't have the
|
||||
/// <tt>FILE_WRITE_DATA</tt> bit on (bit <tt>0x00000002</tt>). Actually, this isn't quite correct. If
|
||||
/// <tt>WNET\alice</tt> is in the local <tt>Administrators</tt> group the access check
|
||||
/// will succeed because the inherited ACE allows local <tt>Administrators</tt>
|
||||
/// both <tt>FILE_READ_DATA</tt> and <tt>FILE_WRITE_DATA</tt> access.
|
||||
/// </remarks>
|
||||
public class Ace
|
||||
{
|
||||
public const int FileReadData = unchecked(0x00000001);
|
||||
|
||||
public const int FileWriteData = unchecked(0x00000002);
|
||||
|
||||
public const int FileAppendData = unchecked(0x00000004);
|
||||
|
||||
public const int FileReadEa = unchecked(0x00000008);
|
||||
|
||||
public const int FileWriteEa = unchecked(0x00000010);
|
||||
|
||||
public const int FileExecute = unchecked(0x00000020);
|
||||
|
||||
public const int FileDelete = unchecked(0x00000040);
|
||||
|
||||
public const int FileReadAttributes = unchecked(0x00000080);
|
||||
|
||||
public const int FileWriteAttributes = unchecked(0x00000100);
|
||||
|
||||
public const int Delete = unchecked(0x00010000);
|
||||
|
||||
public const int ReadControl = unchecked(0x00020000);
|
||||
|
||||
public const int WriteDac = unchecked(0x00040000);
|
||||
|
||||
public const int WriteOwner = unchecked(0x00080000);
|
||||
|
||||
public const int Synchronize = unchecked(0x00100000);
|
||||
|
||||
public const int GenericAll = unchecked(0x10000000);
|
||||
|
||||
public const int GenericExecute = unchecked(0x20000000);
|
||||
|
||||
public const int GenericWrite = unchecked(0x40000000);
|
||||
|
||||
public const int GenericRead = unchecked((int)(0x80000000));
|
||||
|
||||
public const int FlagsObjectInherit = unchecked(0x01);
|
||||
|
||||
public const int FlagsContainerInherit = unchecked(0x02);
|
||||
|
||||
public const int FlagsNoPropagate = unchecked(0x04);
|
||||
|
||||
public const int FlagsInheritOnly = unchecked(0x08);
|
||||
|
||||
public const int FlagsInherited = unchecked(0x10);
|
||||
|
||||
internal bool Allow;
|
||||
|
||||
internal int Flags;
|
||||
|
||||
internal int Access;
|
||||
|
||||
internal Sid Sid;
|
||||
|
||||
// 1
|
||||
// 2
|
||||
// 3
|
||||
// 4
|
||||
// 5
|
||||
// 6
|
||||
// 7
|
||||
// 8
|
||||
// 9
|
||||
// 16
|
||||
// 17
|
||||
// 18
|
||||
// 19
|
||||
// 20
|
||||
// 28
|
||||
// 29
|
||||
// 30
|
||||
// 31
|
||||
/// <summary>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</summary>
|
||||
/// <remarks>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</remarks>
|
||||
public virtual bool IsAllow()
|
||||
{
|
||||
return Allow;
|
||||
}
|
||||
|
||||
/// <summary>Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
|
||||
/// <p>
|
||||
/// Note: For reasons not fully understood, <tt>FLAGS_INHERITED</tt> may
|
||||
/// not be set within all security descriptors even though the ACE was in
|
||||
/// face inherited. If an inherited ACE is added to a parent the Windows
|
||||
/// ACL editor will rebuild all children ACEs and set this flag accordingly.
|
||||
/// </remarks>
|
||||
public virtual bool IsInherited()
|
||||
{
|
||||
return (Flags & FlagsInherited) != 0;
|
||||
}
|
||||
|
||||
/// <summary>Returns the flags for this ACE.</summary>
|
||||
/// <remarks>
|
||||
/// Returns the flags for this ACE. The </tt>isInherited()</tt>
|
||||
/// method checks the <tt>FLAGS_INHERITED</tt> bit in these flags.
|
||||
/// </remarks>
|
||||
public virtual int GetFlags()
|
||||
{
|
||||
return Flags;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the 'Apply To' text for inheritance of ACEs on
|
||||
/// directories such as 'This folder, subfolder and files'.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the 'Apply To' text for inheritance of ACEs on
|
||||
/// directories such as 'This folder, subfolder and files'. For
|
||||
/// files the text is always 'This object only'.
|
||||
/// </remarks>
|
||||
public virtual string GetApplyToText()
|
||||
{
|
||||
switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly
|
||||
))
|
||||
{
|
||||
case unchecked(0x00):
|
||||
{
|
||||
return "This folder only";
|
||||
}
|
||||
|
||||
case unchecked(0x03):
|
||||
{
|
||||
return "This folder, subfolders and files";
|
||||
}
|
||||
|
||||
case unchecked(0x0B):
|
||||
{
|
||||
return "Subfolders and files only";
|
||||
}
|
||||
|
||||
case unchecked(0x02):
|
||||
{
|
||||
return "This folder and subfolders";
|
||||
}
|
||||
|
||||
case unchecked(0x0A):
|
||||
{
|
||||
return "Subfolders only";
|
||||
}
|
||||
|
||||
case unchecked(0x01):
|
||||
{
|
||||
return "This folder and files";
|
||||
}
|
||||
|
||||
case unchecked(0x09):
|
||||
{
|
||||
return "Files only";
|
||||
}
|
||||
}
|
||||
return "Invalid";
|
||||
}
|
||||
|
||||
/// <summary>Returns the access mask accociated with this ACE.</summary>
|
||||
/// <remarks>
|
||||
/// Returns the access mask accociated with this ACE. Use the
|
||||
/// constants for <tt>FILE_READ_DATA</tt>, <tt>FILE_WRITE_DATA</tt>,
|
||||
/// <tt>READ_CONTROL</tt>, <tt>GENERIC_ALL</tt>, etc with bitwise
|
||||
/// operators to determine which bits of the mask are on or off.
|
||||
/// </remarks>
|
||||
public virtual int GetAccessMask()
|
||||
{
|
||||
return Access;
|
||||
}
|
||||
|
||||
/// <summary>Return the SID associated with this ACE.</summary>
|
||||
/// <remarks>Return the SID associated with this ACE.</remarks>
|
||||
public virtual Sid GetSid()
|
||||
{
|
||||
return Sid;
|
||||
}
|
||||
|
||||
internal virtual int Decode(byte[] buf, int bi)
|
||||
{
|
||||
Allow = buf[bi++] == unchecked(unchecked(0x00));
|
||||
Flags = buf[bi++] & unchecked(0xFF);
|
||||
int size = ServerMessageBlock.ReadInt2(buf, bi);
|
||||
bi += 2;
|
||||
Access = ServerMessageBlock.ReadInt4(buf, bi);
|
||||
bi += 4;
|
||||
Sid = new Sid(buf, bi);
|
||||
return size;
|
||||
}
|
||||
|
||||
internal virtual void AppendCol(StringBuilder sb, string str, int width)
|
||||
{
|
||||
sb.Append(str);
|
||||
int count = width - str.Length;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
sb.Append(' ');
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Return a string represeting this ACE.</summary>
|
||||
/// <remarks>
|
||||
/// Return a string represeting this ACE.
|
||||
/// <p>
|
||||
/// Note: This function should probably be changed to return SDDL
|
||||
/// fragments but currently it does not.
|
||||
/// </remarks>
|
||||
public override string ToString()
|
||||
{
|
||||
int count;
|
||||
int i;
|
||||
string str;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(IsAllow() ? "Allow " : "Deny ");
|
||||
AppendCol(sb, Sid.ToDisplayString(), 25);
|
||||
sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' ');
|
||||
sb.Append(IsInherited() ? "Inherited " : "Direct ");
|
||||
AppendCol(sb, GetApplyToText(), 34);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
25
Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs
Normal file
25
Emby.Server.Implementations/IO/SharpCifs/Smb/AllocInfo.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal interface IAllocInfo
|
||||
{
|
||||
long GetCapacity();
|
||||
|
||||
long GetFree();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal abstract class AndXServerMessageBlock : ServerMessageBlock
|
||||
{
|
||||
private const int AndxCommandOffset = 1;
|
||||
|
||||
private const int AndxReservedOffset = 2;
|
||||
|
||||
private const int AndxOffsetOffset = 3;
|
||||
|
||||
private byte _andxCommand = unchecked(unchecked(0xFF));
|
||||
|
||||
private int _andxOffset;
|
||||
|
||||
internal ServerMessageBlock Andx;
|
||||
|
||||
public AndXServerMessageBlock()
|
||||
{
|
||||
}
|
||||
|
||||
internal AndXServerMessageBlock(ServerMessageBlock andx)
|
||||
{
|
||||
if (andx != null)
|
||||
{
|
||||
this.Andx = andx;
|
||||
_andxCommand = andx.Command;
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual int GetBatchLimit(byte command)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int Encode(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = HeaderStart = dstIndex;
|
||||
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
|
||||
dstIndex += WriteAndXWireFormat(dst, dstIndex);
|
||||
Length = dstIndex - start;
|
||||
if (Digest != null)
|
||||
{
|
||||
Digest.Sign(dst, HeaderStart, Length, this, Response);
|
||||
}
|
||||
return Length;
|
||||
}
|
||||
|
||||
internal override int Decode(byte[] buffer, int bufferIndex)
|
||||
{
|
||||
int start = HeaderStart = bufferIndex;
|
||||
bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
|
||||
bufferIndex += ReadAndXWireFormat(buffer, bufferIndex);
|
||||
Length = bufferIndex - start;
|
||||
return Length;
|
||||
}
|
||||
|
||||
internal virtual int WriteAndXWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
WordCount = WriteParameterWordsWireFormat(dst, start + AndxOffsetOffset + 2);
|
||||
WordCount += 4;
|
||||
// for command, reserved, and offset
|
||||
dstIndex += WordCount + 1;
|
||||
WordCount /= 2;
|
||||
dst[start] = unchecked((byte)(WordCount & unchecked(0xFF)));
|
||||
ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
|
||||
dst[dstIndex++] = unchecked((byte)(ByteCount & unchecked(0xFF)));
|
||||
dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & unchecked(0xFF)));
|
||||
dstIndex += ByteCount;
|
||||
if (Andx == null || SmbConstants.UseBatching == false || BatchLevel >= GetBatchLimit(Andx.Command
|
||||
))
|
||||
{
|
||||
_andxCommand = unchecked(unchecked(0xFF));
|
||||
Andx = null;
|
||||
dst[start + AndxCommandOffset] = unchecked(unchecked(0xFF));
|
||||
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
|
||||
// dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
|
||||
// dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
|
||||
dst[start + AndxOffsetOffset] = unchecked(unchecked(0xde));
|
||||
dst[start + AndxOffsetOffset + 1] = unchecked(unchecked(0xde));
|
||||
// andx not used; return
|
||||
return dstIndex - start;
|
||||
}
|
||||
Andx.BatchLevel = BatchLevel + 1;
|
||||
dst[start + AndxCommandOffset] = _andxCommand;
|
||||
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
|
||||
_andxOffset = dstIndex - HeaderStart;
|
||||
WriteInt2(_andxOffset, dst, start + AndxOffsetOffset);
|
||||
Andx.UseUnicode = UseUnicode;
|
||||
if (Andx is AndXServerMessageBlock)
|
||||
{
|
||||
Andx.Uid = Uid;
|
||||
dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
// the andx smb is not of type andx so lets just write it here and
|
||||
// were done.
|
||||
int andxStart = dstIndex;
|
||||
Andx.WordCount = Andx.WriteParameterWordsWireFormat(dst, dstIndex);
|
||||
dstIndex += Andx.WordCount + 1;
|
||||
Andx.WordCount /= 2;
|
||||
dst[andxStart] = unchecked((byte)(Andx.WordCount & unchecked(0xFF)));
|
||||
Andx.ByteCount = Andx.WriteBytesWireFormat(dst, dstIndex + 2);
|
||||
dst[dstIndex++] = unchecked((byte)(Andx.ByteCount & unchecked(0xFF)));
|
||||
dst[dstIndex++] = unchecked((byte)((Andx.ByteCount >> 8) & unchecked(0xFF)
|
||||
));
|
||||
dstIndex += Andx.ByteCount;
|
||||
}
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal virtual int ReadAndXWireFormat(byte[] buffer, int bufferIndex)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
WordCount = buffer[bufferIndex++];
|
||||
if (WordCount != 0)
|
||||
{
|
||||
_andxCommand = buffer[bufferIndex];
|
||||
_andxOffset = ReadInt2(buffer, bufferIndex + 2);
|
||||
if (_andxOffset == 0)
|
||||
{
|
||||
_andxCommand = unchecked(unchecked(0xFF));
|
||||
}
|
||||
if (WordCount > 2)
|
||||
{
|
||||
ReadParameterWordsWireFormat(buffer, bufferIndex + 4);
|
||||
if (Command == SmbComNtCreateAndx && ((SmbComNtCreateAndXResponse)this).IsExtended)
|
||||
{
|
||||
WordCount += 8;
|
||||
}
|
||||
}
|
||||
bufferIndex = start + 1 + (WordCount * 2);
|
||||
}
|
||||
ByteCount = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
if (ByteCount != 0)
|
||||
{
|
||||
int n;
|
||||
n = ReadBytesWireFormat(buffer, bufferIndex);
|
||||
bufferIndex += ByteCount;
|
||||
}
|
||||
if (ErrorCode != 0 || _andxCommand == unchecked(unchecked(0xFF)))
|
||||
{
|
||||
_andxCommand = unchecked(unchecked(0xFF));
|
||||
Andx = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Andx == null)
|
||||
{
|
||||
_andxCommand = unchecked(unchecked(0xFF));
|
||||
throw new RuntimeException("no andx command supplied with response");
|
||||
}
|
||||
bufferIndex = HeaderStart + _andxOffset;
|
||||
Andx.HeaderStart = HeaderStart;
|
||||
Andx.Command = _andxCommand;
|
||||
Andx.ErrorCode = ErrorCode;
|
||||
Andx.Flags = Flags;
|
||||
Andx.Flags2 = Flags2;
|
||||
Andx.Tid = Tid;
|
||||
Andx.Pid = Pid;
|
||||
Andx.Uid = Uid;
|
||||
Andx.Mid = Mid;
|
||||
Andx.UseUnicode = UseUnicode;
|
||||
if (Andx is AndXServerMessageBlock)
|
||||
{
|
||||
bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer
|
||||
, bufferIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))
|
||||
);
|
||||
if (Andx.WordCount != 0)
|
||||
{
|
||||
if (Andx.WordCount > 2)
|
||||
{
|
||||
bufferIndex += Andx.ReadParameterWordsWireFormat(buffer, bufferIndex);
|
||||
}
|
||||
}
|
||||
Andx.ByteCount = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
if (Andx.ByteCount != 0)
|
||||
{
|
||||
Andx.ReadBytesWireFormat(buffer, bufferIndex);
|
||||
bufferIndex += Andx.ByteCount;
|
||||
}
|
||||
}
|
||||
Andx.Received = true;
|
||||
}
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand
|
||||
, 2) + ",andxOffset=" + _andxOffset;
|
||||
}
|
||||
}
|
||||
}
|
||||
80
Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs
Normal file
80
Emby.Server.Implementations/IO/SharpCifs/Smb/BufferCache.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public class BufferCache
|
||||
{
|
||||
private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16
|
||||
);
|
||||
|
||||
internal static object[] Cache = new object[MaxBuffers];
|
||||
|
||||
private static int _freeBuffers;
|
||||
|
||||
public static byte[] GetBuffer()
|
||||
{
|
||||
lock (Cache)
|
||||
{
|
||||
byte[] buf;
|
||||
if (_freeBuffers > 0)
|
||||
{
|
||||
for (int i = 0; i < MaxBuffers; i++)
|
||||
{
|
||||
if (Cache[i] != null)
|
||||
{
|
||||
buf = (byte[])Cache[i];
|
||||
Cache[i] = null;
|
||||
_freeBuffers--;
|
||||
return buf;
|
||||
}
|
||||
}
|
||||
}
|
||||
buf = new byte[SmbComTransaction.TransactionBufSize];
|
||||
return buf;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse
|
||||
rsp)
|
||||
{
|
||||
lock (Cache)
|
||||
{
|
||||
req.TxnBuf = GetBuffer();
|
||||
rsp.TxnBuf = GetBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
public static void ReleaseBuffer(byte[] buf)
|
||||
{
|
||||
lock (Cache)
|
||||
{
|
||||
if (_freeBuffers < MaxBuffers)
|
||||
{
|
||||
for (int i = 0; i < MaxBuffers; i++)
|
||||
{
|
||||
if (Cache[i] == null)
|
||||
{
|
||||
Cache[i] = buf;
|
||||
_freeBuffers++;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
389
Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs
Normal file
389
Emby.Server.Implementations/IO/SharpCifs/Smb/Dfs.cs
Normal file
@@ -0,0 +1,389 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public class Dfs
|
||||
{
|
||||
internal class CacheEntry
|
||||
{
|
||||
internal long Expiration;
|
||||
|
||||
internal Hashtable Map;
|
||||
|
||||
internal CacheEntry(long ttl)
|
||||
{
|
||||
if (ttl == 0)
|
||||
{
|
||||
ttl = Ttl;
|
||||
}
|
||||
Expiration = Runtime.CurrentTimeMillis() + ttl * 1000L;
|
||||
Map = new Hashtable();
|
||||
}
|
||||
}
|
||||
|
||||
internal static LogStream Log = LogStream.GetInstance();
|
||||
|
||||
internal static readonly bool StrictView = Config.GetBoolean("jcifs.smb.client.dfs.strictView"
|
||||
, false);
|
||||
|
||||
internal static readonly long Ttl = Config.GetLong("jcifs.smb.client.dfs.ttl", 300
|
||||
);
|
||||
|
||||
internal static readonly bool Disabled = Config.GetBoolean("jcifs.smb.client.dfs.disabled"
|
||||
, false);
|
||||
|
||||
internal static CacheEntry FalseEntry = new CacheEntry(0L);
|
||||
|
||||
internal CacheEntry Domains;
|
||||
|
||||
internal CacheEntry Referrals;
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
|
||||
public virtual Hashtable GetTrustedDomains(NtlmPasswordAuthentication auth)
|
||||
{
|
||||
if (Disabled || auth.Domain == "?")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (Domains != null && Runtime.CurrentTimeMillis() > Domains.Expiration)
|
||||
{
|
||||
Domains = null;
|
||||
}
|
||||
if (Domains != null)
|
||||
{
|
||||
return Domains.Map;
|
||||
}
|
||||
try
|
||||
{
|
||||
UniAddress addr = UniAddress.GetByName(auth.Domain, true);
|
||||
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
|
||||
CacheEntry entry = new CacheEntry(Ttl * 10L);
|
||||
DfsReferral dr = trans.GetDfsReferrals(auth, string.Empty, 0);
|
||||
if (dr != null)
|
||||
{
|
||||
DfsReferral start = dr;
|
||||
do
|
||||
{
|
||||
string domain = dr.Server.ToLower();
|
||||
entry.Map.Put(domain, new Hashtable());
|
||||
dr = dr.Next;
|
||||
}
|
||||
while (dr != start);
|
||||
Domains = entry;
|
||||
return Domains.Map;
|
||||
}
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (Log.Level >= 3)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, Log);
|
||||
}
|
||||
if (StrictView && ioe is SmbAuthException)
|
||||
{
|
||||
throw (SmbAuthException)ioe;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
|
||||
public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth
|
||||
)
|
||||
{
|
||||
Hashtable domains = GetTrustedDomains(auth);
|
||||
if (domains == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
domain = domain.ToLower();
|
||||
return domains.Get(domain) != null;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
|
||||
public virtual SmbTransport GetDc(string domain, NtlmPasswordAuthentication auth)
|
||||
{
|
||||
if (Disabled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
try
|
||||
{
|
||||
UniAddress addr = UniAddress.GetByName(domain, true);
|
||||
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
|
||||
DfsReferral dr = trans.GetDfsReferrals(auth, "\\" + domain, 1);
|
||||
if (dr != null)
|
||||
{
|
||||
DfsReferral start = dr;
|
||||
IOException e = null;
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
addr = UniAddress.GetByName(dr.Server);
|
||||
return SmbTransport.GetSmbTransport(addr, 0);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
e = ioe;
|
||||
}
|
||||
dr = dr.Next;
|
||||
}
|
||||
while (dr != start);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (Log.Level >= 3)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, Log);
|
||||
}
|
||||
if (StrictView && ioe is SmbAuthException)
|
||||
{
|
||||
throw (SmbAuthException)ioe;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
|
||||
public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string
|
||||
root, string path, NtlmPasswordAuthentication auth)
|
||||
{
|
||||
if (Disabled)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
try
|
||||
{
|
||||
string p = "\\" + domain + "\\" + root;
|
||||
if (path != null)
|
||||
{
|
||||
p += path;
|
||||
}
|
||||
DfsReferral dr = trans.GetDfsReferrals(auth, p, 0);
|
||||
if (dr != null)
|
||||
{
|
||||
return dr;
|
||||
}
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
if (Log.Level >= 4)
|
||||
{
|
||||
Runtime.PrintStackTrace(ioe, Log);
|
||||
}
|
||||
if (StrictView && ioe is SmbAuthException)
|
||||
{
|
||||
throw (SmbAuthException)ioe;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
|
||||
public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication
|
||||
auth)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
DfsReferral dr = null;
|
||||
long now = Runtime.CurrentTimeMillis();
|
||||
if (Disabled || root.Equals("IPC$"))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
Hashtable domains = GetTrustedDomains(auth);
|
||||
if (domains != null)
|
||||
{
|
||||
domain = domain.ToLower();
|
||||
Hashtable roots = (Hashtable)domains.Get(domain);
|
||||
if (roots != null)
|
||||
{
|
||||
SmbTransport trans = null;
|
||||
root = root.ToLower();
|
||||
CacheEntry links = (CacheEntry)roots.Get(root);
|
||||
if (links != null && now > links.Expiration)
|
||||
{
|
||||
//Sharpen.Collections.Remove(roots, root);
|
||||
roots.Remove(root);
|
||||
links = null;
|
||||
}
|
||||
if (links == null)
|
||||
{
|
||||
if ((trans = GetDc(domain, auth)) == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
dr = GetReferral(trans, domain, root, path, auth);
|
||||
if (dr != null)
|
||||
{
|
||||
int len = 1 + domain.Length + 1 + root.Length;
|
||||
links = new CacheEntry(0L);
|
||||
DfsReferral tmp = dr;
|
||||
do
|
||||
{
|
||||
if (path == null)
|
||||
{
|
||||
// TODO: fix this
|
||||
//tmp.map = links.map;
|
||||
tmp.Key = "\\";
|
||||
}
|
||||
tmp.PathConsumed -= len;
|
||||
tmp = tmp.Next;
|
||||
}
|
||||
while (tmp != dr);
|
||||
if (dr.Key != null)
|
||||
{
|
||||
links.Map.Put(dr.Key, dr);
|
||||
}
|
||||
roots.Put(root, links);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (path == null)
|
||||
{
|
||||
roots.Put(root, FalseEntry);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (links == FalseEntry)
|
||||
{
|
||||
links = null;
|
||||
}
|
||||
}
|
||||
if (links != null)
|
||||
{
|
||||
string link = "\\";
|
||||
dr = (DfsReferral)links.Map.Get(link);
|
||||
if (dr != null && now > dr.Expiration)
|
||||
{
|
||||
//Sharpen.Collections.Remove(links.map, link);
|
||||
links.Map.Remove(link);
|
||||
dr = null;
|
||||
}
|
||||
if (dr == null)
|
||||
{
|
||||
if (trans == null)
|
||||
{
|
||||
if ((trans = GetDc(domain, auth)) == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
dr = GetReferral(trans, domain, root, path, auth);
|
||||
if (dr != null)
|
||||
{
|
||||
dr.PathConsumed -= 1 + domain.Length + 1 + root.Length;
|
||||
dr.Link = link;
|
||||
links.Map.Put(link, dr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dr == null && path != null)
|
||||
{
|
||||
if (Referrals != null && now > Referrals.Expiration)
|
||||
{
|
||||
Referrals = null;
|
||||
}
|
||||
if (Referrals == null)
|
||||
{
|
||||
Referrals = new CacheEntry(0);
|
||||
}
|
||||
string key = "\\" + domain + "\\" + root;
|
||||
if (path.Equals("\\") == false)
|
||||
{
|
||||
key += path;
|
||||
}
|
||||
key = key.ToLower();
|
||||
//ListIterator<object> iter = new ListIterator<object>(referrals.map.Keys.GetEnumerator(), 0);
|
||||
foreach (var current in Referrals.Map.Keys)
|
||||
{
|
||||
string _key = (string)current;
|
||||
int klen = _key.Length;
|
||||
bool match = false;
|
||||
if (klen == key.Length)
|
||||
{
|
||||
match = _key.Equals(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (klen < key.Length)
|
||||
{
|
||||
match = _key.RegionMatches(false, 0, key, 0, klen) && key[klen] == '\\';
|
||||
}
|
||||
}
|
||||
if (match)
|
||||
{
|
||||
dr = (DfsReferral)Referrals.Map.Get(_key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dr;
|
||||
}
|
||||
}
|
||||
|
||||
internal virtual void Insert(string path, DfsReferral dr)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
int s1;
|
||||
int s2;
|
||||
string server;
|
||||
string share;
|
||||
string key;
|
||||
if (Disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
s1 = path.IndexOf('\\', 1);
|
||||
s2 = path.IndexOf('\\', s1 + 1);
|
||||
server = Runtime.Substring(path, 1, s1);
|
||||
share = Runtime.Substring(path, s1 + 1, s2);
|
||||
key = Runtime.Substring(path, 0, dr.PathConsumed).ToLower();
|
||||
int ki = key.Length;
|
||||
while (ki > 1 && key[ki - 1] == '\\')
|
||||
{
|
||||
ki--;
|
||||
}
|
||||
if (ki < key.Length)
|
||||
{
|
||||
key = Runtime.Substring(key, 0, ki);
|
||||
}
|
||||
dr.PathConsumed -= 1 + server.Length + 1 + share.Length;
|
||||
if (Referrals != null && (Runtime.CurrentTimeMillis() + 10000) > Referrals.Expiration)
|
||||
{
|
||||
Referrals = null;
|
||||
}
|
||||
if (Referrals == null)
|
||||
{
|
||||
Referrals = new CacheEntry(0);
|
||||
}
|
||||
Referrals.Map.Put(key, dr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs
Normal file
67
Emby.Server.Implementations/IO/SharpCifs/Smb/DfsReferral.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
|
||||
public class DfsReferral : SmbException
|
||||
{
|
||||
public int PathConsumed;
|
||||
|
||||
public long Ttl;
|
||||
|
||||
public string Server;
|
||||
|
||||
public string Share;
|
||||
|
||||
public string Link;
|
||||
|
||||
public string Path;
|
||||
|
||||
public bool ResolveHashes;
|
||||
|
||||
public long Expiration;
|
||||
|
||||
internal DfsReferral Next;
|
||||
|
||||
internal IDictionary<string, DfsReferral> Map;
|
||||
|
||||
internal string Key = null;
|
||||
|
||||
public DfsReferral()
|
||||
{
|
||||
// Server
|
||||
// Share
|
||||
// Path relative to tree from which this referral was thrown
|
||||
Next = this;
|
||||
}
|
||||
|
||||
internal virtual void Append(DfsReferral dr)
|
||||
{
|
||||
dr.Next = Next;
|
||||
Next = dr;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share="
|
||||
+ Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" +
|
||||
Expiration + ",resolveHashes=" + ResolveHashes + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
64
Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs
Normal file
64
Emby.Server.Implementations/IO/SharpCifs/Smb/DosError.cs
Normal file
@@ -0,0 +1,64 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public static class DosError
|
||||
{
|
||||
public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked(
|
||||
(int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)(
|
||||
0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a
|
||||
)) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
|
||||
new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked(
|
||||
0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked(
|
||||
(int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)(
|
||||
0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2
|
||||
)) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
|
||||
new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked(
|
||||
0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, new[] { unchecked(0x00270003), unchecked(
|
||||
(int)(0xc000007f)) }, new[] { unchecked(0x00340001), unchecked((int)(
|
||||
0xC00000bd)) }, new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc
|
||||
)) }, new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) },
|
||||
new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) }, new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) }, new[] { unchecked(
|
||||
0x005a0002), unchecked((int)(0xc00000ce)) }, new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) }, new[] { unchecked(0x007b0001), unchecked(
|
||||
(int)(0xc0000033)) }, new[] { unchecked(0x00910001), unchecked((int)(
|
||||
0xC0000101)) }, new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035
|
||||
)) }, new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) },
|
||||
new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) }, new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) }, new[] { unchecked(
|
||||
0x00ea0001), unchecked((int)(0xc0000016)) }, new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) }, new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) }, new[] { unchecked(0x08c10002), unchecked(
|
||||
(int)(0xC000006f)) }, new[] { unchecked(0x08c20002), unchecked((int)(
|
||||
0xC0000071)) } };
|
||||
|
||||
public static string[] DosErrorMessages = { "The operation completed successfully."
|
||||
, "Incorrect function.", "Incorrect function.", "The system cannot find the file specified."
|
||||
, "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function."
|
||||
, "Access is denied.", "The TID specified was invalid.", "The handle is invalid."
|
||||
, "The network name cannot be found.", "Not enough storage is available to process this command."
|
||||
, "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning."
|
||||
, "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process."
|
||||
, "The process cannot access the file because it is being used by another process."
|
||||
, "The process cannot access the file because another process has locked a portion of the file."
|
||||
, "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found."
|
||||
, "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session."
|
||||
, "The Uid is not known as a valid user identifier on this session.", "The pipe has been ended."
|
||||
, "The filename, directory name, or volume label syntax is incorrect.", "The directory is not empty."
|
||||
, "Cannot create a file when that file already exists.", "All pipe instances are busy."
|
||||
, "The pipe is being closed.", "No process is on the other end of the pipe.", "More data is available."
|
||||
, "This user account has expired.", "The user is not allowed to log on from this workstation."
|
||||
, "The user is not allowed to log on at this time.", "The password of this user has expired."
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public class DosFileFilter : ISmbFileFilter
|
||||
{
|
||||
protected internal string Wildcard;
|
||||
|
||||
protected internal int Attributes;
|
||||
|
||||
public DosFileFilter(string wildcard, int attributes)
|
||||
{
|
||||
this.Wildcard = wildcard;
|
||||
this.Attributes = attributes;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
public virtual bool Accept(SmbFile file)
|
||||
{
|
||||
return (file.GetAttributes() & Attributes) != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
33
Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs
Normal file
33
Emby.Server.Implementations/IO/SharpCifs/Smb/FileEntry.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public interface IFileEntry
|
||||
{
|
||||
string GetName();
|
||||
|
||||
int GetType();
|
||||
|
||||
int GetAttributes();
|
||||
|
||||
long CreateTime();
|
||||
|
||||
long LastModified();
|
||||
|
||||
long Length();
|
||||
}
|
||||
}
|
||||
29
Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs
Normal file
29
Emby.Server.Implementations/IO/SharpCifs/Smb/IInfo.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal interface IInfo
|
||||
{
|
||||
int GetAttributes();
|
||||
|
||||
long GetCreateTime();
|
||||
|
||||
long GetLastWriteTime();
|
||||
|
||||
long GetSize();
|
||||
}
|
||||
}
|
||||
122
Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs
Normal file
122
Emby.Server.Implementations/IO/SharpCifs/Smb/NetServerEnum2.cs
Normal file
@@ -0,0 +1,122 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal class NetServerEnum2 : SmbComTransaction
|
||||
{
|
||||
internal const int SvTypeAll = unchecked((int)(0xFFFFFFFF));
|
||||
|
||||
internal const int SvTypeDomainEnum = unchecked((int)(0x80000000));
|
||||
|
||||
internal static readonly string[] Descr = { "WrLehDO\u0000B16BBDz\u0000"
|
||||
, "WrLehDz\u0000B16BBDz\u0000" };
|
||||
|
||||
internal string Domain;
|
||||
|
||||
internal string LastName;
|
||||
|
||||
internal int ServerTypes;
|
||||
|
||||
internal NetServerEnum2(string domain, int serverTypes)
|
||||
{
|
||||
this.Domain = domain;
|
||||
this.ServerTypes = serverTypes;
|
||||
Command = SmbComTransaction;
|
||||
SubCommand = NetServerEnum2;
|
||||
// not really true be used by upper logic
|
||||
Name = "\\PIPE\\LANMAN";
|
||||
MaxParameterCount = 8;
|
||||
MaxDataCount = 16384;
|
||||
MaxSetupCount = unchecked(unchecked(0x00));
|
||||
SetupCount = 0;
|
||||
Timeout = 5000;
|
||||
}
|
||||
|
||||
internal override void Reset(int key, string lastName)
|
||||
{
|
||||
base.Reset();
|
||||
this.LastName = lastName;
|
||||
}
|
||||
|
||||
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
byte[] descr;
|
||||
int which = SubCommand == NetServerEnum2 ? 0 : 1;
|
||||
try
|
||||
{
|
||||
descr = Runtime.GetBytesForString(Descr[which], "UTF-8"); //"ASCII");
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
WriteInt2(SubCommand & unchecked(0xFF), dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
|
||||
dstIndex += descr.Length;
|
||||
WriteInt2(unchecked(0x0001), dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
WriteInt2(MaxDataCount, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
WriteInt4(ServerTypes, dst, dstIndex);
|
||||
dstIndex += 4;
|
||||
dstIndex += WriteString(Domain.ToUpper(), dst, dstIndex, false);
|
||||
if (which == 1)
|
||||
{
|
||||
dstIndex += WriteString(LastName.ToUpper(), dst, dstIndex, false);
|
||||
}
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
|
||||
len)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NetServerEnum2[" + base.ToString() + ",name=" + Name + ",serverTypes="
|
||||
+ (ServerTypes == SvTypeAll ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM") + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Util;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal class NetServerEnum2Response : SmbComTransactionResponse
|
||||
{
|
||||
internal class ServerInfo1 : IFileEntry
|
||||
{
|
||||
internal string Name;
|
||||
|
||||
internal int VersionMajor;
|
||||
|
||||
internal int VersionMinor;
|
||||
|
||||
internal int Type;
|
||||
|
||||
internal string CommentOrMasterBrowser;
|
||||
|
||||
public virtual string GetName()
|
||||
{
|
||||
return Name;
|
||||
}
|
||||
|
||||
public new virtual int GetType()
|
||||
{
|
||||
return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup :
|
||||
SmbFile.TypeServer;
|
||||
}
|
||||
|
||||
public virtual int GetAttributes()
|
||||
{
|
||||
return SmbFile.AttrReadonly | SmbFile.AttrDirectory;
|
||||
}
|
||||
|
||||
public virtual long CreateTime()
|
||||
{
|
||||
return 0L;
|
||||
}
|
||||
|
||||
public virtual long LastModified()
|
||||
{
|
||||
return 0L;
|
||||
}
|
||||
|
||||
public virtual long Length()
|
||||
{
|
||||
return 0L;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString
|
||||
(Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
|
||||
}
|
||||
|
||||
internal ServerInfo1(NetServerEnum2Response enclosing)
|
||||
{
|
||||
this._enclosing = enclosing;
|
||||
}
|
||||
|
||||
private readonly NetServerEnum2Response _enclosing;
|
||||
}
|
||||
|
||||
private int _converter;
|
||||
|
||||
private int _totalAvailableEntries;
|
||||
|
||||
internal string LastName;
|
||||
|
||||
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
|
||||
len)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
Status = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
_converter = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
NumEntries = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
ServerInfo1 e = null;
|
||||
Results = new ServerInfo1[NumEntries];
|
||||
for (int i = 0; i < NumEntries; i++)
|
||||
{
|
||||
Results[i] = e = new ServerInfo1(this);
|
||||
e.Name = ReadString(buffer, bufferIndex, 16, false);
|
||||
bufferIndex += 16;
|
||||
e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF);
|
||||
e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF);
|
||||
e.Type = ReadInt4(buffer, bufferIndex);
|
||||
bufferIndex += 4;
|
||||
int off = ReadInt4(buffer, bufferIndex);
|
||||
bufferIndex += 4;
|
||||
off = (off & unchecked(0xFFFF)) - _converter;
|
||||
off = start + off;
|
||||
e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false);
|
||||
if (Log.Level >= 4)
|
||||
{
|
||||
Log.WriteLine(e);
|
||||
}
|
||||
}
|
||||
LastName = NumEntries == 0 ? null : e.Name;
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status
|
||||
+ ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
|
||||
+ _totalAvailableEntries + ",lastName=" + LastName + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
95
Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs
Normal file
95
Emby.Server.Implementations/IO/SharpCifs/Smb/NetShareEnum.cs
Normal file
@@ -0,0 +1,95 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal class NetShareEnum : SmbComTransaction
|
||||
{
|
||||
private static readonly string Descr = "WrLeh\u0000B13BWz\u0000";
|
||||
|
||||
public NetShareEnum()
|
||||
{
|
||||
Command = SmbComTransaction;
|
||||
SubCommand = NetShareEnum;
|
||||
// not really true be used by upper logic
|
||||
Name ="\\PIPE\\LANMAN";
|
||||
MaxParameterCount = 8;
|
||||
// maxDataCount = 4096; why was this set?
|
||||
MaxSetupCount = 0x00;
|
||||
SetupCount = 0;
|
||||
Timeout = 5000;
|
||||
}
|
||||
|
||||
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
byte[] descr;
|
||||
try
|
||||
{
|
||||
//descr = Runtime.GetBytesForString(Descr, "ASCII");
|
||||
descr = Runtime.GetBytesForString(Descr, "UTF-8");
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
WriteInt2(NetShareEnum, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
|
||||
dstIndex += descr.Length;
|
||||
WriteInt2(unchecked(0x0001), dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
WriteInt2(MaxDataCount, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
|
||||
len)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NetShareEnum[" + base.ToString() + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal class NetShareEnumResponse : SmbComTransactionResponse
|
||||
{
|
||||
private int _converter;
|
||||
|
||||
private int _totalAvailableEntries;
|
||||
|
||||
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
|
||||
len)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
Status = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
_converter = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
NumEntries = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
SmbShareInfo e;
|
||||
UseUnicode = false;
|
||||
Results = new SmbShareInfo[NumEntries];
|
||||
for (int i = 0; i < NumEntries; i++)
|
||||
{
|
||||
Results[i] = e = new SmbShareInfo();
|
||||
e.NetName = ReadString(buffer, bufferIndex, 13, false);
|
||||
bufferIndex += 14;
|
||||
e.Type = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
int off = ReadInt4(buffer, bufferIndex);
|
||||
bufferIndex += 4;
|
||||
off = (off & unchecked(0xFFFF)) - _converter;
|
||||
off = start + off;
|
||||
e.Remark = ReadString(buffer, off, 128, false);
|
||||
if (Log.Level >= 4)
|
||||
{
|
||||
Log.WriteLine(e);
|
||||
}
|
||||
}
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NetShareEnumResponse[" + base.ToString() + ",status=" + Status
|
||||
+ ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
|
||||
+ _totalAvailableEntries + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
202
Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs
Normal file
202
Emby.Server.Implementations/IO/SharpCifs/Smb/NtStatus.cs
Normal file
@@ -0,0 +1,202 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public static class NtStatus
|
||||
{
|
||||
public const int NtStatusOk = unchecked(0x00000000);
|
||||
|
||||
public const int NtStatusUnsuccessful = unchecked((int)(0xC0000001));
|
||||
|
||||
public const int NtStatusNotImplemented = unchecked((int)(0xC0000002));
|
||||
|
||||
public const int NtStatusInvalidInfoClass = unchecked((int)(0xC0000003));
|
||||
|
||||
public const int NtStatusAccessViolation = unchecked((int)(0xC0000005));
|
||||
|
||||
public const int NtStatusInvalidHandle = unchecked((int)(0xC0000008));
|
||||
|
||||
public const int NtStatusInvalidParameter = unchecked((int)(0xC000000d));
|
||||
|
||||
public const int NtStatusNoSuchDevice = unchecked((int)(0xC000000e));
|
||||
|
||||
public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f));
|
||||
|
||||
public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016)
|
||||
);
|
||||
|
||||
public const int NtStatusAccessDenied = unchecked((int)(0xC0000022));
|
||||
|
||||
public const int NtStatusBufferTooSmall = unchecked((int)(0xC0000023));
|
||||
|
||||
public const int NtStatusObjectNameInvalid = unchecked((int)(0xC0000033));
|
||||
|
||||
public const int NtStatusObjectNameNotFound = unchecked((int)(0xC0000034));
|
||||
|
||||
public const int NtStatusObjectNameCollision = unchecked((int)(0xC0000035));
|
||||
|
||||
public const int NtStatusPortDisconnected = unchecked((int)(0xC0000037));
|
||||
|
||||
public const int NtStatusObjectPathInvalid = unchecked((int)(0xC0000039));
|
||||
|
||||
public const int NtStatusObjectPathNotFound = unchecked((int)(0xC000003a));
|
||||
|
||||
public const int NtStatusObjectPathSyntaxBad = unchecked((int)(0xC000003b));
|
||||
|
||||
public const int NtStatusSharingViolation = unchecked((int)(0xC0000043));
|
||||
|
||||
public const int NtStatusDeletePending = unchecked((int)(0xC0000056));
|
||||
|
||||
public const int NtStatusNoLogonServers = unchecked((int)(0xC000005e));
|
||||
|
||||
public const int NtStatusUserExists = unchecked((int)(0xC0000063));
|
||||
|
||||
public const int NtStatusNoSuchUser = unchecked((int)(0xC0000064));
|
||||
|
||||
public const int NtStatusWrongPassword = unchecked((int)(0xC000006a));
|
||||
|
||||
public const int NtStatusLogonFailure = unchecked((int)(0xC000006d));
|
||||
|
||||
public const int NtStatusAccountRestriction = unchecked((int)(0xC000006e));
|
||||
|
||||
public const int NtStatusInvalidLogonHours = unchecked((int)(0xC000006f));
|
||||
|
||||
public const int NtStatusInvalidWorkstation = unchecked((int)(0xC0000070));
|
||||
|
||||
public const int NtStatusPasswordExpired = unchecked((int)(0xC0000071));
|
||||
|
||||
public const int NtStatusAccountDisabled = unchecked((int)(0xC0000072));
|
||||
|
||||
public const int NtStatusNoneMapped = unchecked((int)(0xC0000073));
|
||||
|
||||
public const int NtStatusInvalidSid = unchecked((int)(0xC0000078));
|
||||
|
||||
public const int NtStatusInstanceNotAvailable = unchecked((int)(0xC00000ab));
|
||||
|
||||
public const int NtStatusPipeNotAvailable = unchecked((int)(0xC00000ac));
|
||||
|
||||
public const int NtStatusInvalidPipeState = unchecked((int)(0xC00000ad));
|
||||
|
||||
public const int NtStatusPipeBusy = unchecked((int)(0xC00000ae));
|
||||
|
||||
public const int NtStatusPipeDisconnected = unchecked((int)(0xC00000b0));
|
||||
|
||||
public const int NtStatusPipeClosing = unchecked((int)(0xC00000b1));
|
||||
|
||||
public const int NtStatusPipeListening = unchecked((int)(0xC00000b3));
|
||||
|
||||
public const int NtStatusFileIsADirectory = unchecked((int)(0xC00000ba));
|
||||
|
||||
public const int NtStatusDuplicateName = unchecked((int)(0xC00000bd));
|
||||
|
||||
public const int NtStatusNetworkNameDeleted = unchecked((int)(0xC00000c9));
|
||||
|
||||
public const int NtStatusNetworkAccessDenied = unchecked((int)(0xC00000ca));
|
||||
|
||||
public const int NtStatusBadNetworkName = unchecked((int)(0xC00000cc));
|
||||
|
||||
public const int NtStatusRequestNotAccepted = unchecked((int)(0xC00000d0));
|
||||
|
||||
public const int NtStatusCantAccessDomainInfo = unchecked((int)(0xC00000da));
|
||||
|
||||
public const int NtStatusNoSuchDomain = unchecked((int)(0xC00000df));
|
||||
|
||||
public const int NtStatusNotADirectory = unchecked((int)(0xC0000103));
|
||||
|
||||
public const int NtStatusCannotDelete = unchecked((int)(0xC0000121));
|
||||
|
||||
public const int NtStatusInvalidComputerName = unchecked((int)(0xC0000122));
|
||||
|
||||
public const int NtStatusPipeBroken = unchecked((int)(0xC000014b));
|
||||
|
||||
public const int NtStatusNoSuchAlias = unchecked((int)(0xC0000151));
|
||||
|
||||
public const int NtStatusLogonTypeNotGranted = unchecked((int)(0xC000015b));
|
||||
|
||||
public const int NtStatusNoTrustSamAccount = unchecked((int)(0xC000018b));
|
||||
|
||||
public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c));
|
||||
|
||||
public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199
|
||||
));
|
||||
|
||||
public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224));
|
||||
|
||||
public const int NtStatusNotFound = unchecked((int)(0xC0000225));
|
||||
|
||||
public const int NtStatusAccountLockedOut = unchecked((int)(0xC0000234));
|
||||
|
||||
public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
|
||||
|
||||
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279
|
||||
));
|
||||
|
||||
public static int[] NtStatusCodes = { NtStatusOk, NtStatusUnsuccessful
|
||||
, NtStatusNotImplemented, NtStatusInvalidInfoClass, NtStatusAccessViolation
|
||||
, NtStatusInvalidHandle, NtStatusInvalidParameter, NtStatusNoSuchDevice
|
||||
, NtStatusNoSuchFile, NtStatusMoreProcessingRequired, NtStatusAccessDenied
|
||||
, NtStatusBufferTooSmall, NtStatusObjectNameInvalid, NtStatusObjectNameNotFound
|
||||
, NtStatusObjectNameCollision, NtStatusPortDisconnected, NtStatusObjectPathInvalid
|
||||
, NtStatusObjectPathNotFound, NtStatusObjectPathSyntaxBad, NtStatusSharingViolation
|
||||
, NtStatusDeletePending, NtStatusNoLogonServers, NtStatusUserExists, NtStatusNoSuchUser
|
||||
, NtStatusWrongPassword, NtStatusLogonFailure, NtStatusAccountRestriction
|
||||
, NtStatusInvalidLogonHours, NtStatusInvalidWorkstation, NtStatusPasswordExpired
|
||||
, NtStatusAccountDisabled, NtStatusNoneMapped, NtStatusInvalidSid, NtStatusInstanceNotAvailable
|
||||
, NtStatusPipeNotAvailable, NtStatusInvalidPipeState, NtStatusPipeBusy
|
||||
, NtStatusPipeDisconnected, NtStatusPipeClosing, NtStatusPipeListening,
|
||||
NtStatusFileIsADirectory, NtStatusDuplicateName, NtStatusNetworkNameDeleted
|
||||
, NtStatusNetworkAccessDenied, NtStatusBadNetworkName, NtStatusRequestNotAccepted
|
||||
, NtStatusCantAccessDomainInfo, NtStatusNoSuchDomain, NtStatusNotADirectory
|
||||
, NtStatusCannotDelete, NtStatusInvalidComputerName, NtStatusPipeBroken
|
||||
, NtStatusNoSuchAlias, NtStatusLogonTypeNotGranted, NtStatusNoTrustSamAccount
|
||||
, NtStatusTrustedDomainFailure, NtStatusNologonWorkstationTrustAccount,
|
||||
NtStatusPasswordMustChange, NtStatusNotFound, NtStatusAccountLockedOut
|
||||
, NtStatusPathNotCovered, NtStatusIoReparseTagNotHandled };
|
||||
|
||||
public static string[] NtStatusMessages = { "The operation completed successfully."
|
||||
, "A device attached to the system is not functioning.", "Incorrect function.",
|
||||
"The parameter is incorrect.", "Invalid access to memory location.", "The handle is invalid."
|
||||
, "The parameter is incorrect.", "The system cannot find the file specified.", "The system cannot find the file specified."
|
||||
, "More data is available.", "Access is denied.", "The data area passed to a system call is too small."
|
||||
, "The filename, directory name, or volume label syntax is incorrect.", "The system cannot find the file specified."
|
||||
, "Cannot create a file when that file already exists.", "The handle is invalid."
|
||||
, "The specified path is invalid.", "The system cannot find the path specified."
|
||||
, "The specified path is invalid.", "The process cannot access the file because it is being used by another process."
|
||||
, "Access is denied.", "There are currently no logon servers available to service the logon request."
|
||||
, "The specified user already exists.", "The specified user does not exist.", "The specified network password is not correct."
|
||||
, "Logon failure: unknown user name or bad password.", "Logon failure: user account restriction."
|
||||
, "Logon failure: account logon time restriction violation.", "Logon failure: user not allowed to log on to this computer."
|
||||
, "Logon failure: the specified account password has expired.", "Logon failure: account currently disabled."
|
||||
, "No mapping between account names and security IDs was done.", "The security ID structure is invalid."
|
||||
, "All pipe instances are busy.", "All pipe instances are busy.", "The pipe state is invalid."
|
||||
, "All pipe instances are busy.", "No process is on the other end of the pipe.",
|
||||
"The pipe is being closed.", "Waiting for a process to open the other end of the pipe."
|
||||
, "Access is denied.", "A duplicate name exists on the network.", "The specified network name is no longer available."
|
||||
, "Network access is denied.", "The network name cannot be found.", "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept."
|
||||
, "Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved."
|
||||
, "The specified domain did not exist.", "The directory name is invalid.", "Access is denied."
|
||||
, "The format of the specified computer name is invalid.", "The pipe has been ended."
|
||||
, "The specified local group does not exist.", "Logon failure: the user has not been granted the requested logon type at this computer."
|
||||
, "The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship."
|
||||
, "The trust relationship between the primary domain and the trusted domain failed."
|
||||
, "The account used is a Computer Account. Use your global user account or local user account to access this server."
|
||||
, "The user must change his password before he logs on the first time.", "NT_STATUS_NOT_FOUND"
|
||||
, "The referenced account is currently locked out and may not be logged on to.",
|
||||
"The remote system is not reachable by the transport.", "NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED"
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Util;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal class NtTransQuerySecurityDesc : SmbComNtTransaction
|
||||
{
|
||||
internal int Fid;
|
||||
|
||||
internal int SecurityInformation;
|
||||
|
||||
internal NtTransQuerySecurityDesc(int fid, int securityInformation)
|
||||
{
|
||||
this.Fid = fid;
|
||||
this.SecurityInformation = securityInformation;
|
||||
Command = SmbComNtTransact;
|
||||
Function = NtTransactQuerySecurityDesc;
|
||||
SetupCount = 0;
|
||||
TotalDataCount = 0;
|
||||
MaxParameterCount = 4;
|
||||
MaxDataCount = 32768;
|
||||
MaxSetupCount = unchecked(unchecked(0x00));
|
||||
}
|
||||
|
||||
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = dstIndex;
|
||||
WriteInt2(Fid, dst, dstIndex);
|
||||
dstIndex += 2;
|
||||
dst[dstIndex++] = unchecked(unchecked(0x00));
|
||||
// Reserved
|
||||
dst[dstIndex++] = unchecked(unchecked(0x00));
|
||||
// Reserved
|
||||
WriteInt4(SecurityInformation, dst, dstIndex);
|
||||
dstIndex += 4;
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
|
||||
len)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NtTransQuerySecurityDesc[" + base.ToString() + ",fid=0x" + Hexdump
|
||||
.ToHexString(Fid, 4) + ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation
|
||||
, 8) + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
internal class NtTransQuerySecurityDescResponse : SmbComNtTransactionResponse
|
||||
{
|
||||
internal SecurityDescriptor SecurityDescriptor;
|
||||
|
||||
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
|
||||
len)
|
||||
{
|
||||
Length = ReadInt4(buffer, bufferIndex);
|
||||
return 4;
|
||||
}
|
||||
|
||||
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
if (ErrorCode != 0)
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
try
|
||||
{
|
||||
SecurityDescriptor = new SecurityDescriptor();
|
||||
bufferIndex += SecurityDescriptor.Decode(buffer, bufferIndex, len);
|
||||
}
|
||||
catch (IOException ioe)
|
||||
{
|
||||
throw new RuntimeException(ioe.Message);
|
||||
}
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NtTransQuerySecurityResponse[" + base.ToString() + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
/// <summary>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials.
|
||||
/// </summary>
|
||||
/// <remarks>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. Read <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for complete details.
|
||||
/// </remarks>
|
||||
public abstract class NtlmAuthenticator
|
||||
{
|
||||
private static NtlmAuthenticator _auth;
|
||||
|
||||
private string _url;
|
||||
|
||||
private SmbAuthException _sae;
|
||||
|
||||
private void Reset()
|
||||
{
|
||||
_url = null;
|
||||
_sae = null;
|
||||
}
|
||||
|
||||
/// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary>
|
||||
/// <remarks>Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect.
|
||||
/// </remarks>
|
||||
public static void SetDefault(NtlmAuthenticator a)
|
||||
{
|
||||
lock (typeof(NtlmAuthenticator))
|
||||
{
|
||||
if (_auth != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_auth = a;
|
||||
}
|
||||
}
|
||||
|
||||
protected internal string GetRequestingUrl()
|
||||
{
|
||||
return _url;
|
||||
}
|
||||
|
||||
protected internal SmbAuthException GetRequestingException()
|
||||
{
|
||||
return _sae;
|
||||
}
|
||||
|
||||
/// <summary>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
|
||||
/// </summary>
|
||||
/// <remarks>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
|
||||
/// </remarks>
|
||||
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string
|
||||
url, SmbAuthException sae)
|
||||
{
|
||||
if (_auth == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
lock (_auth)
|
||||
{
|
||||
_auth._url = url;
|
||||
_auth._sae = sae;
|
||||
return _auth.GetNtlmPasswordAuthentication();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
|
||||
/// If this method returns <tt>null</tt> the <tt>SmbAuthException</tt> that triggered the authenticator check will simply be rethrown. The default implementation returns <tt>null</tt>.
|
||||
/// </remarks>
|
||||
protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication
|
||||
()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using SharpCifs.Util;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
|
||||
public sealed class NtlmChallenge
|
||||
{
|
||||
public byte[] Challenge;
|
||||
|
||||
public UniAddress Dc;
|
||||
|
||||
internal NtlmChallenge(byte[] challenge, UniAddress dc)
|
||||
{
|
||||
this.Challenge = challenge;
|
||||
this.Dc = dc;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge
|
||||
.Length * 2) + ",dc=" + Dc + "]";
|
||||
}
|
||||
}
|
||||
}
|
||||
206
Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs
Normal file
206
Emby.Server.Implementations/IO/SharpCifs/Smb/NtlmContext.cs
Normal file
@@ -0,0 +1,206 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Ntlmssp;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
/// <summary>For initiating NTLM authentication (including NTLMv2).</summary>
|
||||
/// <remarks>For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. Note that JCIFS does not implement the acceptor side of NTLM authentication.
|
||||
/// </remarks>
|
||||
public class NtlmContext
|
||||
{
|
||||
internal NtlmPasswordAuthentication Auth;
|
||||
|
||||
internal int NtlmsspFlags;
|
||||
|
||||
internal string Workstation;
|
||||
|
||||
internal bool isEstablished;
|
||||
|
||||
internal byte[] ServerChallenge;
|
||||
|
||||
internal byte[] SigningKey;
|
||||
|
||||
internal string NetbiosName = null;
|
||||
|
||||
internal int State = 1;
|
||||
|
||||
internal LogStream Log;
|
||||
|
||||
public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
|
||||
{
|
||||
this.Auth = auth;
|
||||
NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2
|
||||
| NtlmFlags.NtlmsspNegotiate128;
|
||||
if (doSigning)
|
||||
{
|
||||
NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign
|
||||
| NtlmFlags.NtlmsspNegotiateKeyExch;
|
||||
}
|
||||
Workstation = Type1Message.GetDefaultWorkstation();
|
||||
Log = LogStream.GetInstance();
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString
|
||||
(NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished
|
||||
+ ",state=" + State + ",serverChallenge=";
|
||||
if (ServerChallenge == null)
|
||||
{
|
||||
ret += "null";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret += Hexdump.ToHexString(ServerChallenge, 0, ServerChallenge.Length * 2);
|
||||
}
|
||||
ret += ",signingKey=";
|
||||
if (SigningKey == null)
|
||||
{
|
||||
ret += "null";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret += Hexdump.ToHexString(SigningKey, 0, SigningKey.Length * 2);
|
||||
}
|
||||
ret += "]";
|
||||
return ret;
|
||||
}
|
||||
|
||||
public virtual bool IsEstablished()
|
||||
{
|
||||
return isEstablished;
|
||||
}
|
||||
|
||||
public virtual byte[] GetServerChallenge()
|
||||
{
|
||||
return ServerChallenge;
|
||||
}
|
||||
|
||||
public virtual byte[] GetSigningKey()
|
||||
{
|
||||
return SigningKey;
|
||||
}
|
||||
|
||||
public virtual string GetNetbiosName()
|
||||
{
|
||||
return NetbiosName;
|
||||
}
|
||||
|
||||
private string GetNtlmsspListItem(byte[] type2Token, int id0)
|
||||
{
|
||||
int ri = 58;
|
||||
for (; ; )
|
||||
{
|
||||
int id = Encdec.Dec_uint16le(type2Token, ri);
|
||||
int len = Encdec.Dec_uint16le(type2Token, ri + 2);
|
||||
ri += 4;
|
||||
if (id == 0 || (ri + len) > type2Token.Length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (id == id0)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding
|
||||
);
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
ri += len;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
public virtual byte[] InitSecContext(byte[] token, int offset, int len)
|
||||
{
|
||||
switch (State)
|
||||
{
|
||||
case 1:
|
||||
{
|
||||
Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation);
|
||||
token = msg1.ToByteArray();
|
||||
if (Log.Level >= 4)
|
||||
{
|
||||
Log.WriteLine(msg1);
|
||||
if (Log.Level >= 6)
|
||||
{
|
||||
Hexdump.ToHexdump(Log, token, 0, token.Length);
|
||||
}
|
||||
}
|
||||
State++;
|
||||
break;
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
try
|
||||
{
|
||||
Type2Message msg2 = new Type2Message(token);
|
||||
if (Log.Level >= 4)
|
||||
{
|
||||
Log.WriteLine(msg2);
|
||||
if (Log.Level >= 6)
|
||||
{
|
||||
Hexdump.ToHexdump(Log, token, 0, token.Length);
|
||||
}
|
||||
}
|
||||
ServerChallenge = msg2.GetChallenge();
|
||||
NtlmsspFlags &= msg2.GetFlags();
|
||||
// netbiosName = getNtlmsspListItem(token, 0x0001);
|
||||
Type3Message msg3 = new Type3Message(msg2, Auth.GetPassword(), Auth.GetDomain(),
|
||||
Auth.GetUsername(), Workstation, NtlmsspFlags);
|
||||
token = msg3.ToByteArray();
|
||||
if (Log.Level >= 4)
|
||||
{
|
||||
Log.WriteLine(msg3);
|
||||
if (Log.Level >= 6)
|
||||
{
|
||||
Hexdump.ToHexdump(Log, token, 0, token.Length);
|
||||
}
|
||||
}
|
||||
if ((NtlmsspFlags & NtlmFlags.NtlmsspNegotiateSign) != 0)
|
||||
{
|
||||
SigningKey = msg3.GetMasterKey();
|
||||
}
|
||||
isEstablished = true;
|
||||
State++;
|
||||
break;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new SmbException(e.Message, e);
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
throw new SmbException("Invalid state");
|
||||
}
|
||||
}
|
||||
return token;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,807 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
/// <summary>This class stores and encrypts NTLM user credentials.</summary>
|
||||
/// <remarks>
|
||||
/// This class stores and encrypts NTLM user credentials. The default
|
||||
/// credentials are retrieved from the <tt>jcifs.smb.client.domain</tt>,
|
||||
/// <tt>jcifs.smb.client.username</tt>, and <tt>jcifs.smb.client.password</tt>
|
||||
/// properties.
|
||||
/// <p>
|
||||
/// Read <a href="../../../authhandler.html">jCIFS Exceptions and
|
||||
/// NtlmAuthenticator</a> for related information.
|
||||
/// </remarks>
|
||||
|
||||
public sealed class NtlmPasswordAuthentication : Principal
|
||||
{
|
||||
private static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility"
|
||||
, 3);
|
||||
|
||||
private static readonly Random Random = new Random();
|
||||
|
||||
private static LogStream _log = LogStream.GetInstance();
|
||||
|
||||
private static readonly byte[] S8 = { unchecked(unchecked(0x4b)), unchecked(unchecked(0x47)), unchecked(unchecked(0x53)), unchecked(unchecked(0x21)), unchecked(unchecked(0x40)), unchecked(unchecked(0x23)), unchecked(unchecked(0x24)), unchecked(unchecked(0x25)) };
|
||||
|
||||
// KGS!@#$%
|
||||
private static void E(byte[] key, byte[] data, byte[] e)
|
||||
{
|
||||
byte[] key7 = new byte[7];
|
||||
byte[] e8 = new byte[8];
|
||||
for (int i = 0; i < key.Length / 7; i++)
|
||||
{
|
||||
Array.Copy(key, i * 7, key7, 0, 7);
|
||||
DES des = new DES(key7);
|
||||
des.Encrypt(data, e8);
|
||||
Array.Copy(e8, 0, e, i * 8, 8);
|
||||
}
|
||||
}
|
||||
|
||||
internal static string DefaultDomain;
|
||||
|
||||
internal static string DefaultUsername;
|
||||
|
||||
internal static string DefaultPassword;
|
||||
|
||||
internal static readonly string Blank = string.Empty;
|
||||
|
||||
public static readonly NtlmPasswordAuthentication Anonymous = new NtlmPasswordAuthentication
|
||||
(string.Empty, string.Empty, string.Empty);
|
||||
|
||||
internal static void InitDefaults()
|
||||
{
|
||||
if (DefaultDomain != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", "?");
|
||||
DefaultUsername = Config.GetProperty("jcifs.smb.client.username", "GUEST");
|
||||
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank);
|
||||
}
|
||||
|
||||
/// <summary>Generate the ANSI DES hash for the password associated with these credentials.
|
||||
/// </summary>
|
||||
/// <remarks>Generate the ANSI DES hash for the password associated with these credentials.
|
||||
/// </remarks>
|
||||
public static byte[] GetPreNtlmResponse(string password, byte[] challenge)
|
||||
{
|
||||
byte[] p14 = new byte[14];
|
||||
byte[] p21 = new byte[21];
|
||||
byte[] p24 = new byte[24];
|
||||
byte[] passwordBytes;
|
||||
try
|
||||
{
|
||||
passwordBytes = Runtime.GetBytesForString(password.ToUpper(), SmbConstants.OemEncoding);
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
throw new RuntimeException("Try setting jcifs.encoding=US-ASCII", uee);
|
||||
}
|
||||
int passwordLength = passwordBytes.Length;
|
||||
// Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
|
||||
if (passwordLength > 14)
|
||||
{
|
||||
passwordLength = 14;
|
||||
}
|
||||
Array.Copy(passwordBytes, 0, p14, 0, passwordLength);
|
||||
E(p14, S8, p21);
|
||||
E(p21, challenge, p24);
|
||||
return p24;
|
||||
}
|
||||
|
||||
/// <summary>Generate the Unicode MD4 hash for the password associated with these credentials.
|
||||
/// </summary>
|
||||
/// <remarks>Generate the Unicode MD4 hash for the password associated with these credentials.
|
||||
/// </remarks>
|
||||
public static byte[] GetNtlmResponse(string password, byte[] challenge)
|
||||
{
|
||||
byte[] uni = null;
|
||||
byte[] p21 = new byte[21];
|
||||
byte[] p24 = new byte[24];
|
||||
try
|
||||
{
|
||||
uni = Runtime.GetBytesForString(password, SmbConstants.UniEncoding);
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(uee, _log);
|
||||
}
|
||||
}
|
||||
Md4 md4 = new Md4();
|
||||
md4.Update(uni);
|
||||
try
|
||||
{
|
||||
md4.Digest(p21, 0, 16);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, _log);
|
||||
}
|
||||
}
|
||||
E(p21, challenge, p24);
|
||||
return p24;
|
||||
}
|
||||
|
||||
/// <summary>Creates the LMv2 response for the supplied information.</summary>
|
||||
/// <remarks>Creates the LMv2 response for the supplied information.</remarks>
|
||||
/// <param name="domain">The domain in which the username exists.</param>
|
||||
/// <param name="user">The username.</param>
|
||||
/// <param name="password">The user's password.</param>
|
||||
/// <param name="challenge">The server challenge.</param>
|
||||
/// <param name="clientChallenge">The client challenge (nonce).</param>
|
||||
public static byte[] GetLMv2Response(string domain, string user, string password,
|
||||
byte[] challenge, byte[] clientChallenge)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] hash = new byte[16];
|
||||
byte[] response = new byte[24];
|
||||
// The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password
|
||||
Md4 md4 = new Md4();
|
||||
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
|
||||
);
|
||||
Hmact64 hmac = new Hmact64(md4.Digest());
|
||||
hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding
|
||||
));
|
||||
hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding
|
||||
));
|
||||
hmac = new Hmact64(hmac.Digest());
|
||||
hmac.Update(challenge);
|
||||
hmac.Update(clientChallenge);
|
||||
hmac.Digest(response, 0, 16);
|
||||
Array.Copy(clientChallenge, 0, response, 16, 8);
|
||||
return response;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, _log);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] GetNtlm2Response(byte[] nTowFv1, byte[] serverChallenge, byte
|
||||
[] clientChallenge)
|
||||
{
|
||||
byte[] sessionHash = new byte[8];
|
||||
try
|
||||
{
|
||||
MessageDigest md5;
|
||||
md5 = MessageDigest.GetInstance("MD5");
|
||||
md5.Update(serverChallenge);
|
||||
md5.Update(clientChallenge, 0, 8);
|
||||
Array.Copy(md5.Digest(), 0, sessionHash, 0, 8);
|
||||
}
|
||||
catch (Exception gse)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(gse, _log);
|
||||
}
|
||||
throw new RuntimeException("MD5", gse);
|
||||
}
|
||||
byte[] key = new byte[21];
|
||||
Array.Copy(nTowFv1, 0, key, 0, 16);
|
||||
byte[] ntResponse = new byte[24];
|
||||
E(key, sessionHash, ntResponse);
|
||||
return ntResponse;
|
||||
}
|
||||
|
||||
public static byte[] NtowFv1(string password)
|
||||
{
|
||||
if (password == null)
|
||||
{
|
||||
throw new RuntimeException("Password parameter is required");
|
||||
}
|
||||
try
|
||||
{
|
||||
Md4 md4 = new Md4();
|
||||
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
|
||||
);
|
||||
return md4.Digest();
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
throw new RuntimeException(uee.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] NtowFv2(string domain, string username, string password)
|
||||
{
|
||||
try
|
||||
{
|
||||
Md4 md4 = new Md4();
|
||||
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
|
||||
);
|
||||
Hmact64 hmac = new Hmact64(md4.Digest());
|
||||
hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding
|
||||
));
|
||||
hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding));
|
||||
return hmac.Digest();
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
throw new RuntimeException(uee.Message);
|
||||
}
|
||||
}
|
||||
|
||||
internal static byte[] ComputeResponse(byte[] responseKey, byte[] serverChallenge
|
||||
, byte[] clientData, int offset, int length)
|
||||
{
|
||||
Hmact64 hmac = new Hmact64(responseKey);
|
||||
hmac.Update(serverChallenge);
|
||||
hmac.Update(clientData, offset, length);
|
||||
byte[] mac = hmac.Digest();
|
||||
byte[] ret = new byte[mac.Length + clientData.Length];
|
||||
Array.Copy(mac, 0, ret, 0, mac.Length);
|
||||
Array.Copy(clientData, 0, ret, mac.Length, clientData.Length);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public static byte[] GetLMv2Response(byte[] responseKeyLm, byte[] serverChallenge
|
||||
, byte[] clientChallenge)
|
||||
{
|
||||
return ComputeResponse(responseKeyLm, serverChallenge
|
||||
, clientChallenge, 0, clientChallenge.Length);
|
||||
}
|
||||
|
||||
public static byte[] GetNtlMv2Response(byte[] responseKeyNt, byte[] serverChallenge
|
||||
, byte[] clientChallenge, long nanos1601, byte[] targetInfo)
|
||||
{
|
||||
int targetInfoLength = targetInfo != null ? targetInfo.Length : 0;
|
||||
byte[] temp = new byte[28 + targetInfoLength + 4];
|
||||
Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0);
|
||||
// Header
|
||||
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 4);
|
||||
// Reserved
|
||||
Encdec.Enc_uint64le(nanos1601, temp, 8);
|
||||
Array.Copy(clientChallenge, 0, temp, 16, 8);
|
||||
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 24);
|
||||
// Unknown
|
||||
if (targetInfo != null)
|
||||
{
|
||||
Array.Copy(targetInfo, 0, temp, 28, targetInfoLength);
|
||||
}
|
||||
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength);
|
||||
// mystery bytes!
|
||||
return ComputeResponse(responseKeyNt, serverChallenge
|
||||
, temp, 0, temp.Length);
|
||||
}
|
||||
|
||||
internal static readonly NtlmPasswordAuthentication Null = new NtlmPasswordAuthentication
|
||||
(string.Empty, string.Empty, string.Empty);
|
||||
|
||||
internal static readonly NtlmPasswordAuthentication Guest = new NtlmPasswordAuthentication
|
||||
("?", "GUEST", string.Empty);
|
||||
|
||||
internal static readonly NtlmPasswordAuthentication Default = new NtlmPasswordAuthentication
|
||||
(null);
|
||||
|
||||
internal string Domain;
|
||||
|
||||
internal string Username;
|
||||
|
||||
internal string Password;
|
||||
|
||||
internal byte[] AnsiHash;
|
||||
|
||||
internal byte[] UnicodeHash;
|
||||
|
||||
internal bool HashesExternal;
|
||||
|
||||
internal byte[] ClientChallenge;
|
||||
|
||||
internal byte[] Challenge;
|
||||
|
||||
/// <summary>
|
||||
/// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
|
||||
/// component of an SMB URL like "<tt>domain;user:pass</tt>".
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
|
||||
/// component of an SMB URL like "<tt>domain;user:pass</tt>". This constructor
|
||||
/// is used internally be jCIFS when parsing SMB URLs.
|
||||
/// </remarks>
|
||||
public NtlmPasswordAuthentication(string userInfo)
|
||||
{
|
||||
Domain = Username = Password = null;
|
||||
if (userInfo != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
userInfo = Unescape(userInfo);
|
||||
}
|
||||
catch (UnsupportedEncodingException)
|
||||
{
|
||||
}
|
||||
int i;
|
||||
int u;
|
||||
int end;
|
||||
char c;
|
||||
end = userInfo.Length;
|
||||
for (i = 0, u = 0; i < end; i++)
|
||||
{
|
||||
c = userInfo[i];
|
||||
if (c == ';')
|
||||
{
|
||||
Domain = Runtime.Substring(userInfo, 0, i);
|
||||
u = i + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (c == ':')
|
||||
{
|
||||
Password = Runtime.Substring(userInfo, i + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Username = Runtime.Substring(userInfo, u, i);
|
||||
}
|
||||
InitDefaults();
|
||||
if (Domain == null)
|
||||
{
|
||||
Domain = DefaultDomain;
|
||||
}
|
||||
if (Username == null)
|
||||
{
|
||||
Username = DefaultUsername;
|
||||
}
|
||||
if (Password == null)
|
||||
{
|
||||
Password = DefaultPassword;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create an <tt>NtlmPasswordAuthentication</tt> object from a
|
||||
/// domain, username, and password.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Create an <tt>NtlmPasswordAuthentication</tt> object from a
|
||||
/// domain, username, and password. Parameters that are <tt>null</tt>
|
||||
/// will be substituted with <tt>jcifs.smb.client.domain</tt>,
|
||||
/// <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt>
|
||||
/// property values.
|
||||
/// </remarks>
|
||||
public NtlmPasswordAuthentication(string domain, string username, string password
|
||||
)
|
||||
{
|
||||
int ci;
|
||||
if (username != null)
|
||||
{
|
||||
ci = username.IndexOf('@');
|
||||
if (ci > 0)
|
||||
{
|
||||
domain = Runtime.Substring(username, ci + 1);
|
||||
username = Runtime.Substring(username, 0, ci);
|
||||
}
|
||||
else
|
||||
{
|
||||
ci = username.IndexOf('\\');
|
||||
if (ci > 0)
|
||||
{
|
||||
domain = Runtime.Substring(username, 0, ci);
|
||||
username = Runtime.Substring(username, ci + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.Domain = domain;
|
||||
this.Username = username;
|
||||
this.Password = password;
|
||||
InitDefaults();
|
||||
if (domain == null)
|
||||
{
|
||||
this.Domain = DefaultDomain;
|
||||
}
|
||||
if (username == null)
|
||||
{
|
||||
this.Username = DefaultUsername;
|
||||
}
|
||||
if (password == null)
|
||||
{
|
||||
this.Password = DefaultPassword;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
|
||||
/// hashes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
|
||||
/// hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt>
|
||||
/// class which is in turn used by NTLM HTTP authentication functionality.
|
||||
/// </remarks>
|
||||
public NtlmPasswordAuthentication(string domain, string username, byte[] challenge
|
||||
, byte[] ansiHash, byte[] unicodeHash)
|
||||
{
|
||||
if (domain == null || username == null || ansiHash == null || unicodeHash == null)
|
||||
{
|
||||
throw new ArgumentException("External credentials cannot be null");
|
||||
}
|
||||
this.Domain = domain;
|
||||
this.Username = username;
|
||||
Password = null;
|
||||
this.Challenge = challenge;
|
||||
this.AnsiHash = ansiHash;
|
||||
this.UnicodeHash = unicodeHash;
|
||||
HashesExternal = true;
|
||||
}
|
||||
|
||||
/// <summary>Returns the domain.</summary>
|
||||
/// <remarks>Returns the domain.</remarks>
|
||||
public string GetDomain()
|
||||
{
|
||||
return Domain;
|
||||
}
|
||||
|
||||
/// <summary>Returns the username.</summary>
|
||||
/// <remarks>Returns the username.</remarks>
|
||||
public string GetUsername()
|
||||
{
|
||||
return Username;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the password in plain text or <tt>null</tt> if the raw password
|
||||
/// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
|
||||
/// object which will be the case when NTLM HTTP Authentication is
|
||||
/// used.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Returns the password in plain text or <tt>null</tt> if the raw password
|
||||
/// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
|
||||
/// object which will be the case when NTLM HTTP Authentication is
|
||||
/// used. There is no way to retrieve a users password in plain text unless
|
||||
/// it is supplied by the user at runtime.
|
||||
/// </remarks>
|
||||
public string GetPassword()
|
||||
{
|
||||
return Password;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the domain and username in the format:
|
||||
/// <tt>domain\\username</tt>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return the domain and username in the format:
|
||||
/// <tt>domain\\username</tt>. This is equivalent to <tt>toString()</tt>.
|
||||
/// </remarks>
|
||||
public new string GetName()
|
||||
{
|
||||
bool d = Domain.Length > 0 && Domain.Equals("?") == false;
|
||||
return d ? Domain + "\\" + Username : Username;
|
||||
}
|
||||
|
||||
/// <summary>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
|
||||
/// </summary>
|
||||
/// <remarks>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
|
||||
/// </remarks>
|
||||
public byte[] GetAnsiHash(byte[] challenge)
|
||||
{
|
||||
if (HashesExternal)
|
||||
{
|
||||
return AnsiHash;
|
||||
}
|
||||
switch (LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
{
|
||||
return GetPreNtlmResponse(Password, challenge);
|
||||
}
|
||||
|
||||
case 2:
|
||||
{
|
||||
return GetNtlmResponse(Password, challenge);
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
if (ClientChallenge == null)
|
||||
{
|
||||
ClientChallenge = new byte[8];
|
||||
Random.NextBytes(ClientChallenge);
|
||||
}
|
||||
return GetLMv2Response(Domain, Username, Password, challenge, ClientChallenge);
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
return GetPreNtlmResponse(Password, challenge);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
|
||||
/// </summary>
|
||||
/// <remarks>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
|
||||
/// </remarks>
|
||||
public byte[] GetUnicodeHash(byte[] challenge)
|
||||
{
|
||||
if (HashesExternal)
|
||||
{
|
||||
return UnicodeHash;
|
||||
}
|
||||
switch (LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
{
|
||||
return GetNtlmResponse(Password, challenge);
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
return GetNtlmResponse(Password, challenge);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
public byte[] GetSigningKey(byte[] challenge)
|
||||
{
|
||||
switch (LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
{
|
||||
byte[] signingKey = new byte[40];
|
||||
GetUserSessionKey(challenge, signingKey, 0);
|
||||
Array.Copy(GetUnicodeHash(challenge), 0, signingKey, 16, 24);
|
||||
return signingKey;
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
throw new SmbException("NTLMv2 requires extended security (jcifs.smb.client.useExtendedSecurity must be true if jcifs.smb.lmCompatibility >= 3)"
|
||||
);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Returns the effective user session key.</summary>
|
||||
/// <remarks>Returns the effective user session key.</remarks>
|
||||
/// <param name="challenge">The server challenge.</param>
|
||||
/// <returns>
|
||||
/// A <code>byte[]</code> containing the effective user session key,
|
||||
/// used in SMB MAC signing and NTLMSSP signing and sealing.
|
||||
/// </returns>
|
||||
public byte[] GetUserSessionKey(byte[] challenge)
|
||||
{
|
||||
if (HashesExternal)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
byte[] key = new byte[16];
|
||||
try
|
||||
{
|
||||
GetUserSessionKey(challenge, key, 0);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, _log);
|
||||
}
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <summary>Calculates the effective user session key.</summary>
|
||||
/// <remarks>Calculates the effective user session key.</remarks>
|
||||
/// <param name="challenge">The server challenge.</param>
|
||||
/// <param name="dest">
|
||||
/// The destination array in which the user session key will be
|
||||
/// placed.
|
||||
/// </param>
|
||||
/// <param name="offset">
|
||||
/// The offset in the destination array at which the
|
||||
/// session key will start.
|
||||
/// </param>
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
internal void GetUserSessionKey(byte[] challenge, byte[] dest, int offset)
|
||||
{
|
||||
if (HashesExternal)
|
||||
{
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
Md4 md4 = new Md4();
|
||||
md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding)
|
||||
);
|
||||
switch (LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
{
|
||||
md4.Update(md4.Digest());
|
||||
md4.Digest(dest, offset, 16);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
if (ClientChallenge == null)
|
||||
{
|
||||
ClientChallenge = new byte[8];
|
||||
Random.NextBytes(ClientChallenge);
|
||||
}
|
||||
Hmact64 hmac = new Hmact64(md4.Digest());
|
||||
hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), SmbConstants.UniEncoding
|
||||
));
|
||||
hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding
|
||||
));
|
||||
byte[] ntlmv2Hash = hmac.Digest();
|
||||
hmac = new Hmact64(ntlmv2Hash);
|
||||
hmac.Update(challenge);
|
||||
hmac.Update(ClientChallenge);
|
||||
Hmact64 userKey = new Hmact64(ntlmv2Hash);
|
||||
userKey.Update(hmac.Digest());
|
||||
userKey.Digest(dest, offset, 16);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
md4.Update(md4.Digest());
|
||||
md4.Digest(dest, offset, 16);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new SmbException(string.Empty, e);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
|
||||
/// equality.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
|
||||
/// equality. Two <tt>NtlmPasswordAuthentication</tt> objects are equal if
|
||||
/// their caseless domain and username fields are equal and either both hashes are external and they are equal or both internally supplied passwords are equal. If one <tt>NtlmPasswordAuthentication</tt> object has external hashes (meaning negotiated via NTLM HTTP Authentication) and the other does not they will not be equal. This is technically not correct however the server 8 byte challage would be required to compute and compare the password hashes but that it not available with this method.
|
||||
/// </remarks>
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (obj is NtlmPasswordAuthentication)
|
||||
{
|
||||
NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication
|
||||
)obj;
|
||||
if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) && ntlm.Username.ToUpper().Equals
|
||||
(Username.ToUpper()))
|
||||
{
|
||||
if (HashesExternal && ntlm.HashesExternal)
|
||||
{
|
||||
|
||||
return Arrays.Equals(AnsiHash, ntlm.AnsiHash) && Arrays.Equals(UnicodeHash, ntlm.
|
||||
UnicodeHash);
|
||||
}
|
||||
if (!HashesExternal && Password.Equals(ntlm.Password))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Return the upcased username hash code.</summary>
|
||||
/// <remarks>Return the upcased username hash code.</remarks>
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return GetName().ToUpper().GetHashCode();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the domain and username in the format:
|
||||
/// <tt>domain\\username</tt>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return the domain and username in the format:
|
||||
/// <tt>domain\\username</tt>. This is equivalent to <tt>getName()</tt>.
|
||||
/// </remarks>
|
||||
public override string ToString()
|
||||
{
|
||||
return GetName();
|
||||
}
|
||||
|
||||
/// <exception cref="System.FormatException"></exception>
|
||||
/// <exception cref="UnsupportedEncodingException"></exception>
|
||||
internal static string Unescape(string str)
|
||||
{
|
||||
char ch;
|
||||
int i;
|
||||
int j;
|
||||
int state;
|
||||
int len;
|
||||
char[] @out;
|
||||
byte[] b = new byte[1];
|
||||
if (str == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
len = str.Length;
|
||||
@out = new char[len];
|
||||
state = 0;
|
||||
for (i = j = 0; i < len; i++)
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
case 0:
|
||||
{
|
||||
ch = str[i];
|
||||
if (ch == '%')
|
||||
{
|
||||
state = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
@out[j++] = ch;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 1:
|
||||
{
|
||||
b[0] = unchecked((byte)(Convert.ToInt32(Runtime.Substring(str, i,
|
||||
i + 2), 16) & unchecked(0xFF)));
|
||||
@out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0];
|
||||
i++;
|
||||
state = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new string(@out, 0, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
28
Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs
Normal file
28
Emby.Server.Implementations/IO/SharpCifs/Smb/Principal.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public class Principal
|
||||
{
|
||||
private string _name = "";
|
||||
|
||||
public string GetName()
|
||||
{
|
||||
return _name;
|
||||
}
|
||||
}
|
||||
}
|
||||
900
Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs
Normal file
900
Emby.Server.Implementations/IO/SharpCifs/Smb/SID.cs
Normal file
@@ -0,0 +1,900 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using SharpCifs.Dcerpc;
|
||||
using SharpCifs.Dcerpc.Msrpc;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
using Hashtable = SharpCifs.Util.Sharpen.Hashtable; //not System.Collections.Hashtable
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
/// <summary>
|
||||
/// A Windows SID is a numeric identifier used to represent Windows
|
||||
/// accounts.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A Windows SID is a numeric identifier used to represent Windows
|
||||
/// accounts. SIDs are commonly represented using a textual format such as
|
||||
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt> but they may
|
||||
/// also be resolved to yield the name of the associated Windows account
|
||||
/// such as <tt>Administrators</tt> or <tt>MYDOM\alice</tt>.
|
||||
/// <p>
|
||||
/// Consider the following output of <tt>examples/SidLookup.java</tt>:
|
||||
/// <pre>
|
||||
/// toString: S-1-5-21-4133388617-793952518-2001621813-512
|
||||
/// toDisplayString: WNET\Domain Admins
|
||||
/// getType: 2
|
||||
/// getTypeText: Domain group
|
||||
/// getDomainName: WNET
|
||||
/// getAccountName: Domain Admins
|
||||
/// </pre>
|
||||
/// </remarks>
|
||||
public class Sid : Rpc.SidT
|
||||
{
|
||||
public const int SidTypeUseNone = Lsarpc.SidNameUseNone;
|
||||
|
||||
public const int SidTypeUser = Lsarpc.SidNameUser;
|
||||
|
||||
public const int SidTypeDomGrp = Lsarpc.SidNameDomGrp;
|
||||
|
||||
public const int SidTypeDomain = Lsarpc.SidNameDomain;
|
||||
|
||||
public const int SidTypeAlias = Lsarpc.SidNameAlias;
|
||||
|
||||
public const int SidTypeWknGrp = Lsarpc.SidNameWknGrp;
|
||||
|
||||
public const int SidTypeDeleted = Lsarpc.SidNameDeleted;
|
||||
|
||||
public const int SidTypeInvalid = Lsarpc.SidNameInvalid;
|
||||
|
||||
public const int SidTypeUnknown = Lsarpc.SidNameUnknown;
|
||||
|
||||
internal static readonly string[] SidTypeNames = { "0", "User", "Domain group"
|
||||
, "Domain", "Local group", "Builtin group", "Deleted", "Invalid", "Unknown" };
|
||||
|
||||
public const int SidFlagResolveSids = unchecked(0x0001);
|
||||
|
||||
public static Sid Everyone;
|
||||
|
||||
public static Sid CreatorOwner;
|
||||
|
||||
public static Sid SYSTEM;
|
||||
|
||||
static Sid()
|
||||
{
|
||||
try
|
||||
{
|
||||
Everyone = new Sid("S-1-1-0");
|
||||
CreatorOwner = new Sid("S-1-3-0");
|
||||
SYSTEM = new Sid("S-1-5-18");
|
||||
}
|
||||
catch (SmbException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
internal static Hashtable SidCache = new Hashtable();
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static void ResolveSids(DcerpcHandle handle, LsaPolicyHandle policyHandle
|
||||
, Sid[] sids)
|
||||
{
|
||||
MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids);
|
||||
handle.Sendrecv(rpc);
|
||||
switch (rpc.Retval)
|
||||
{
|
||||
case 0:
|
||||
case NtStatus.NtStatusNoneMapped:
|
||||
case unchecked(0x00000107):
|
||||
{
|
||||
// NT_STATUS_SOME_NOT_MAPPED
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
}
|
||||
for (int si = 0; si < sids.Length; si++)
|
||||
{
|
||||
sids[si].Type = rpc.Names.Names[si].SidType;
|
||||
sids[si].DomainName = null;
|
||||
switch (sids[si].Type)
|
||||
{
|
||||
case SidTypeUser:
|
||||
case SidTypeDomGrp:
|
||||
case SidTypeDomain:
|
||||
case SidTypeAlias:
|
||||
case SidTypeWknGrp:
|
||||
{
|
||||
int sidIndex = rpc.Names.Names[si].SidIndex;
|
||||
Rpc.Unicode_string ustr = rpc.Domains.Domains[sidIndex].Name;
|
||||
sids[si].DomainName = (new UnicodeString(ustr, false)).ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
sids[si].AcctName = (new UnicodeString(rpc.Names.Names[si].Name, false)).ToString
|
||||
();
|
||||
sids[si].OriginServer = null;
|
||||
sids[si].OriginAuth = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static void ResolveSids0(string authorityServerName, NtlmPasswordAuthentication
|
||||
auth, Sid[] sids)
|
||||
{
|
||||
DcerpcHandle handle = null;
|
||||
LsaPolicyHandle policyHandle = null;
|
||||
lock (SidCache)
|
||||
{
|
||||
try
|
||||
{
|
||||
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]"
|
||||
, auth);
|
||||
string server = authorityServerName;
|
||||
int dot = server.IndexOf('.');
|
||||
if (dot > 0 && char.IsDigit(server[0]) == false)
|
||||
{
|
||||
server = Runtime.Substring(server, 0, dot);
|
||||
}
|
||||
policyHandle = new LsaPolicyHandle(handle, "\\\\" + server, unchecked(0x00000800));
|
||||
ResolveSids(handle, policyHandle, sids);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (handle != null)
|
||||
{
|
||||
if (policyHandle != null)
|
||||
{
|
||||
policyHandle.Close();
|
||||
}
|
||||
handle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
|
||||
auth, Sid[] sids, int offset, int length)
|
||||
{
|
||||
List<object> list = new List<object>();//new List<object>(sids.Length);
|
||||
int si;
|
||||
lock (SidCache)
|
||||
{
|
||||
for (si = 0; si < length; si++)
|
||||
{
|
||||
Sid sid = (Sid)SidCache.Get(sids[offset + si]);
|
||||
if (sid != null)
|
||||
{
|
||||
sids[offset + si].Type = sid.Type;
|
||||
sids[offset + si].DomainName = sid.DomainName;
|
||||
sids[offset + si].AcctName = sid.AcctName;
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(sids[offset + si]);
|
||||
}
|
||||
}
|
||||
if (list.Count > 0)
|
||||
{
|
||||
//sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
|
||||
sids = (Sid[])list.ToArray();
|
||||
ResolveSids0(authorityServerName, auth, sids);
|
||||
for (si = 0; si < sids.Length; si++)
|
||||
{
|
||||
SidCache.Put(sids[si], sids[si]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Resolve an array of SIDs using a cache and at most one MSRPC request.</summary>
|
||||
/// <remarks>
|
||||
/// Resolve an array of SIDs using a cache and at most one MSRPC request.
|
||||
/// <p>
|
||||
/// This method will attempt
|
||||
/// to resolve SIDs using a cache and cache the results of any SIDs that
|
||||
/// required resolving with the authority. SID cache entries are currently not
|
||||
/// expired because under normal circumstances SID information never changes.
|
||||
/// </remarks>
|
||||
/// <param name="authorityServerName">The hostname of the server that should be queried. For maximum efficiency this should be the hostname of a domain controller however a member server will work as well and a domain controller may not return names for SIDs corresponding to local accounts for which the domain controller is not an authority.
|
||||
/// </param>
|
||||
/// <param name="auth">The credentials that should be used to communicate with the named server. As usual, <tt>null</tt> indicates that default credentials should be used.
|
||||
/// </param>
|
||||
/// <param name="sids">The SIDs that should be resolved. After this function is called, the names associated with the SIDs may be queried with the <tt>toDisplayString</tt>, <tt>getDomainName</tt>, and <tt>getAccountName</tt> methods.
|
||||
/// </param>
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
|
||||
auth, Sid[] sids)
|
||||
{
|
||||
List<object> list = new List<object>();//new List<object>(sids.Length);
|
||||
int si;
|
||||
lock (SidCache)
|
||||
{
|
||||
for (si = 0; si < sids.Length; si++)
|
||||
{
|
||||
Sid sid = (Sid)SidCache.Get(sids[si]);
|
||||
if (sid != null)
|
||||
{
|
||||
sids[si].Type = sid.Type;
|
||||
sids[si].DomainName = sid.DomainName;
|
||||
sids[si].AcctName = sid.AcctName;
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(sids[si]);
|
||||
}
|
||||
}
|
||||
if (list.Count > 0)
|
||||
{
|
||||
//sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
|
||||
sids = (Sid[]) list.ToArray();
|
||||
ResolveSids0(authorityServerName, auth, sids);
|
||||
for (si = 0; si < sids.Length; si++)
|
||||
{
|
||||
SidCache.Put(sids[si], sids[si]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public static Sid GetServerSid(string server, NtlmPasswordAuthentication
|
||||
auth)
|
||||
{
|
||||
DcerpcHandle handle = null;
|
||||
LsaPolicyHandle policyHandle = null;
|
||||
Lsarpc.LsarDomainInfo info = new Lsarpc.LsarDomainInfo();
|
||||
MsrpcQueryInformationPolicy rpc;
|
||||
lock (SidCache)
|
||||
{
|
||||
try
|
||||
{
|
||||
handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth);
|
||||
// NetApp doesn't like the 'generic' access mask values
|
||||
policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001));
|
||||
rpc = new MsrpcQueryInformationPolicy(policyHandle, Lsarpc.PolicyInfoAccountDomain
|
||||
, info);
|
||||
handle.Sendrecv(rpc);
|
||||
if (rpc.Retval != 0)
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
return new Sid(info.Sid, SidTypeDomain, (new UnicodeString
|
||||
(info.Name, false)).ToString(), null, false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (handle != null)
|
||||
{
|
||||
if (policyHandle != null)
|
||||
{
|
||||
policyHandle.Close();
|
||||
}
|
||||
handle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] ToByteArray(Rpc.SidT sid)
|
||||
{
|
||||
byte[] dst = new byte[1 + 1 + 6 + sid.SubAuthorityCount * 4];
|
||||
int di = 0;
|
||||
dst[di++] = sid.Revision;
|
||||
dst[di++] = sid.SubAuthorityCount;
|
||||
Array.Copy(sid.IdentifierAuthority, 0, dst, di, 6);
|
||||
di += 6;
|
||||
for (int ii = 0; ii < sid.SubAuthorityCount; ii++)
|
||||
{
|
||||
Encdec.Enc_uint32le(sid.SubAuthority[ii], dst, di);
|
||||
di += 4;
|
||||
}
|
||||
return dst;
|
||||
}
|
||||
|
||||
internal int Type;
|
||||
|
||||
internal string DomainName;
|
||||
|
||||
internal string AcctName;
|
||||
|
||||
internal string OriginServer;
|
||||
|
||||
internal NtlmPasswordAuthentication OriginAuth;
|
||||
|
||||
public Sid(byte[] src, int si)
|
||||
{
|
||||
Revision = src[si++];
|
||||
SubAuthorityCount = src[si++];
|
||||
IdentifierAuthority = new byte[6];
|
||||
Array.Copy(src, si, IdentifierAuthority, 0, 6);
|
||||
si += 6;
|
||||
if (SubAuthorityCount > 100)
|
||||
{
|
||||
throw new RuntimeException("Invalid SID sub_authority_count");
|
||||
}
|
||||
SubAuthority = new int[SubAuthorityCount];
|
||||
for (int i = 0; i < SubAuthorityCount; i++)
|
||||
{
|
||||
SubAuthority[i] = ServerMessageBlock.ReadInt4(src, si);
|
||||
si += 4;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct a SID from it's textual representation such as
|
||||
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Construct a SID from it's textual representation such as
|
||||
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
|
||||
/// </remarks>
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
public Sid(string textual)
|
||||
{
|
||||
StringTokenizer st = new StringTokenizer(textual, "-");
|
||||
if (st.CountTokens() < 3 || !st.NextToken().Equals("S"))
|
||||
{
|
||||
// need S-N-M
|
||||
throw new SmbException("Bad textual SID format: " + textual);
|
||||
}
|
||||
Revision = byte.Parse(st.NextToken());
|
||||
string tmp = st.NextToken();
|
||||
long id = 0;
|
||||
if (tmp.StartsWith("0x"))
|
||||
{
|
||||
//id = long.Parse(Sharpen.Runtime.Substring(tmp, 2), 16);
|
||||
id = long.Parse(Runtime.Substring(tmp, 2));
|
||||
}
|
||||
else
|
||||
{
|
||||
id = long.Parse(tmp);
|
||||
}
|
||||
IdentifierAuthority = new byte[6];
|
||||
for (int i = 5; id > 0; i--)
|
||||
{
|
||||
IdentifierAuthority[i] = unchecked((byte)(id % 256));
|
||||
id >>= 8;
|
||||
}
|
||||
SubAuthorityCount = unchecked((byte)st.CountTokens());
|
||||
if (SubAuthorityCount > 0)
|
||||
{
|
||||
SubAuthority = new int[SubAuthorityCount];
|
||||
for (int i1 = 0; i1 < SubAuthorityCount; i1++)
|
||||
{
|
||||
SubAuthority[i1] = (int)(long.Parse(st.NextToken()) & unchecked(0xFFFFFFFFL));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construct a SID from a domain SID and an RID
|
||||
/// (relative identifier).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Construct a SID from a domain SID and an RID
|
||||
/// (relative identifier). For example, a domain SID
|
||||
/// <tt>S-1-5-21-1496946806-2192648263-3843101252</tt> and RID <tt>1029</tt> would
|
||||
/// yield the SID <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
|
||||
/// </remarks>
|
||||
public Sid(Sid domsid, int rid)
|
||||
{
|
||||
Revision = domsid.Revision;
|
||||
IdentifierAuthority = domsid.IdentifierAuthority;
|
||||
SubAuthorityCount = unchecked((byte)(domsid.SubAuthorityCount + 1));
|
||||
SubAuthority = new int[SubAuthorityCount];
|
||||
int i;
|
||||
for (i = 0; i < domsid.SubAuthorityCount; i++)
|
||||
{
|
||||
SubAuthority[i] = domsid.SubAuthority[i];
|
||||
}
|
||||
SubAuthority[i] = rid;
|
||||
}
|
||||
|
||||
public Sid(Rpc.SidT sid, int type, string domainName, string acctName, bool decrementAuthority
|
||||
)
|
||||
{
|
||||
Revision = sid.Revision;
|
||||
SubAuthorityCount = sid.SubAuthorityCount;
|
||||
IdentifierAuthority = sid.IdentifierAuthority;
|
||||
SubAuthority = sid.SubAuthority;
|
||||
this.Type = type;
|
||||
this.DomainName = domainName;
|
||||
this.AcctName = acctName;
|
||||
if (decrementAuthority)
|
||||
{
|
||||
SubAuthorityCount--;
|
||||
SubAuthority = new int[SubAuthorityCount];
|
||||
for (int i = 0; i < SubAuthorityCount; i++)
|
||||
{
|
||||
SubAuthority[i] = sid.SubAuthority[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public virtual Sid GetDomainSid()
|
||||
{
|
||||
return new Sid(this, SidTypeDomain, DomainName, null, GetType()
|
||||
!= SidTypeDomain);
|
||||
}
|
||||
|
||||
public virtual int GetRid()
|
||||
{
|
||||
if (GetType() == SidTypeDomain)
|
||||
{
|
||||
throw new ArgumentException("This SID is a domain sid");
|
||||
}
|
||||
return SubAuthority[SubAuthorityCount - 1];
|
||||
}
|
||||
|
||||
/// <summary>Returns the type of this SID indicating the state or type of account.</summary>
|
||||
/// <remarks>
|
||||
/// Returns the type of this SID indicating the state or type of account.
|
||||
/// <p>
|
||||
/// SID types are described in the following table.
|
||||
/// <tt>
|
||||
/// <table>
|
||||
/// <tr><th>Type</th><th>Name</th></tr>
|
||||
/// <tr><td>SID_TYPE_USE_NONE</td><td>0</td></tr>
|
||||
/// <tr><td>SID_TYPE_USER</td><td>User</td></tr>
|
||||
/// <tr><td>SID_TYPE_DOM_GRP</td><td>Domain group</td></tr>
|
||||
/// <tr><td>SID_TYPE_DOMAIN</td><td>Domain</td></tr>
|
||||
/// <tr><td>SID_TYPE_ALIAS</td><td>Local group</td></tr>
|
||||
/// <tr><td>SID_TYPE_WKN_GRP</td><td>Builtin group</td></tr>
|
||||
/// <tr><td>SID_TYPE_DELETED</td><td>Deleted</td></tr>
|
||||
/// <tr><td>SID_TYPE_INVALID</td><td>Invalid</td></tr>
|
||||
/// <tr><td>SID_TYPE_UNKNOWN</td><td>Unknown</td></tr>
|
||||
/// </table>
|
||||
/// </tt>
|
||||
/// </remarks>
|
||||
public virtual int GetType()
|
||||
{
|
||||
if (OriginServer != null)
|
||||
{
|
||||
ResolveWeak();
|
||||
}
|
||||
return Type;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return text represeting the SID type suitable for display to
|
||||
/// users.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return text represeting the SID type suitable for display to
|
||||
/// users. Text includes 'User', 'Domain group', 'Local group', etc.
|
||||
/// </remarks>
|
||||
public virtual string GetTypeText()
|
||||
{
|
||||
if (OriginServer != null)
|
||||
{
|
||||
ResolveWeak();
|
||||
}
|
||||
return SidTypeNames[Type];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the domain name of this SID unless it could not be
|
||||
/// resolved in which case the numeric representation is returned.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return the domain name of this SID unless it could not be
|
||||
/// resolved in which case the numeric representation is returned.
|
||||
/// </remarks>
|
||||
public virtual string GetDomainName()
|
||||
{
|
||||
if (OriginServer != null)
|
||||
{
|
||||
ResolveWeak();
|
||||
}
|
||||
if (Type == SidTypeUnknown)
|
||||
{
|
||||
string full = ToString();
|
||||
return Runtime.Substring(full, 0, full.Length - GetAccountName().Length -
|
||||
1);
|
||||
}
|
||||
return DomainName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the sAMAccountName of this SID unless it could not
|
||||
/// be resolved in which case the numeric RID is returned.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return the sAMAccountName of this SID unless it could not
|
||||
/// be resolved in which case the numeric RID is returned. If this
|
||||
/// SID is a domain SID, this method will return an empty String.
|
||||
/// </remarks>
|
||||
public virtual string GetAccountName()
|
||||
{
|
||||
if (OriginServer != null)
|
||||
{
|
||||
ResolveWeak();
|
||||
}
|
||||
if (Type == SidTypeUnknown)
|
||||
{
|
||||
return string.Empty + SubAuthority[SubAuthorityCount - 1];
|
||||
}
|
||||
if (Type == SidTypeDomain)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
return AcctName;
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
int hcode = IdentifierAuthority[5];
|
||||
for (int i = 0; i < SubAuthorityCount; i++)
|
||||
{
|
||||
hcode += 65599 * SubAuthority[i];
|
||||
}
|
||||
return hcode;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (obj is Sid)
|
||||
{
|
||||
Sid sid = (Sid)obj;
|
||||
if (sid == this)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (sid.SubAuthorityCount == SubAuthorityCount)
|
||||
{
|
||||
int i = SubAuthorityCount;
|
||||
while (i-- > 0)
|
||||
{
|
||||
if (sid.SubAuthority[i] != SubAuthority[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < 6; i++)
|
||||
{
|
||||
if (sid.IdentifierAuthority[i] != IdentifierAuthority[i])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return sid.Revision == Revision;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return the numeric representation of this sid such as
|
||||
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return the numeric representation of this sid such as
|
||||
/// <tt>S-1-5-21-1496946806-2192648263-3843101252-1029</tt>.
|
||||
/// </remarks>
|
||||
public override string ToString()
|
||||
{
|
||||
string ret = "S-" + (Revision & unchecked(0xFF)) + "-";
|
||||
if (IdentifierAuthority[0] != unchecked(0) || IdentifierAuthority[1] != unchecked(
|
||||
0))
|
||||
{
|
||||
ret += "0x";
|
||||
ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6);
|
||||
}
|
||||
else
|
||||
{
|
||||
int shift = 0;
|
||||
long id = 0;
|
||||
for (int i = 5; i > 1; i--)
|
||||
{
|
||||
id += (IdentifierAuthority[i] & unchecked(0xFFL)) << shift;
|
||||
shift += 8;
|
||||
}
|
||||
ret += id;
|
||||
}
|
||||
for (int i1 = 0; i1 < SubAuthorityCount; i1++)
|
||||
{
|
||||
ret += "-" + (SubAuthority[i1] & unchecked(0xFFFFFFFFL));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return a String representing this SID ideal for display to
|
||||
/// users.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Return a String representing this SID ideal for display to
|
||||
/// users. This method should return the same text that the ACL
|
||||
/// editor in Windows would display.
|
||||
/// <p>
|
||||
/// Specifically, if the SID has
|
||||
/// been resolved and it is not a domain SID or builtin account,
|
||||
/// the full DOMAIN\name form of the account will be
|
||||
/// returned (e.g. MYDOM\alice or MYDOM\Domain Users).
|
||||
/// If the SID has been resolved but it is is a domain SID,
|
||||
/// only the domain name will be returned (e.g. MYDOM).
|
||||
/// If the SID has been resolved but it is a builtin account,
|
||||
/// only the name component will be returned (e.g. SYSTEM).
|
||||
/// If the sid cannot be resolved the numeric representation from
|
||||
/// toString() is returned.
|
||||
/// </remarks>
|
||||
public virtual string ToDisplayString()
|
||||
{
|
||||
if (OriginServer != null)
|
||||
{
|
||||
ResolveWeak();
|
||||
}
|
||||
if (DomainName != null)
|
||||
{
|
||||
string str;
|
||||
if (Type == SidTypeDomain)
|
||||
{
|
||||
str = DomainName;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Type == SidTypeWknGrp || DomainName.Equals("BUILTIN"))
|
||||
{
|
||||
if (Type == SidTypeUnknown)
|
||||
{
|
||||
str = ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
str = AcctName;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
str = DomainName + "\\" + AcctName;
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
return ToString();
|
||||
}
|
||||
|
||||
/// <summary>Manually resolve this SID.</summary>
|
||||
/// <remarks>
|
||||
/// Manually resolve this SID. Normally SIDs are automatically
|
||||
/// resolved. However, if a SID is constructed explicitly using a SID
|
||||
/// constructor, JCIFS will have no knowledge of the server that created the
|
||||
/// SID and therefore cannot possibly resolve it automatically. In this case,
|
||||
/// this method will be necessary.
|
||||
/// </remarks>
|
||||
/// <param name="authorityServerName">The FQDN of the server that is an authority for the SID.
|
||||
/// </param>
|
||||
/// <param name="auth">Credentials suitable for accessing the SID's information.</param>
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual void Resolve(string authorityServerName, NtlmPasswordAuthentication
|
||||
auth)
|
||||
{
|
||||
Sid[] sids = new Sid[1];
|
||||
sids[0] = this;
|
||||
ResolveSids(authorityServerName, auth, sids);
|
||||
}
|
||||
|
||||
internal virtual void ResolveWeak()
|
||||
{
|
||||
if (OriginServer != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
Resolve(OriginServer, OriginAuth);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
OriginServer = null;
|
||||
OriginAuth = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle
|
||||
domainHandle, Sid domsid, int rid, int flags)
|
||||
{
|
||||
SamrAliasHandle aliasHandle = null;
|
||||
Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray();
|
||||
MsrpcGetMembersInAlias rpc = null;
|
||||
try
|
||||
{
|
||||
aliasHandle = new SamrAliasHandle(handle, domainHandle, unchecked(0x0002000c), rid);
|
||||
rpc = new MsrpcGetMembersInAlias(aliasHandle, sidarray);
|
||||
handle.Sendrecv(rpc);
|
||||
if (rpc.Retval != 0)
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
Sid[] sids = new Sid[rpc.Sids.NumSids];
|
||||
string originServer = handle.GetServer();
|
||||
NtlmPasswordAuthentication originAuth = (NtlmPasswordAuthentication)handle.GetPrincipal
|
||||
();
|
||||
for (int i = 0; i < sids.Length; i++)
|
||||
{
|
||||
sids[i] = new Sid(rpc.Sids.Sids[i].Sid, 0, null, null, false);
|
||||
sids[i].OriginServer = originServer;
|
||||
sids[i].OriginAuth = originAuth;
|
||||
}
|
||||
if (sids.Length > 0 && (flags & SidFlagResolveSids) != 0)
|
||||
{
|
||||
ResolveSids(originServer, originAuth, sids);
|
||||
}
|
||||
return sids;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (aliasHandle != null)
|
||||
{
|
||||
aliasHandle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication
|
||||
auth, int flags)
|
||||
{
|
||||
if (Type != SidTypeDomGrp && Type != SidTypeAlias)
|
||||
{
|
||||
return new Sid[0];
|
||||
}
|
||||
DcerpcHandle handle = null;
|
||||
SamrPolicyHandle policyHandle = null;
|
||||
SamrDomainHandle domainHandle = null;
|
||||
Sid domsid = GetDomainSid();
|
||||
lock (SidCache)
|
||||
{
|
||||
try
|
||||
{
|
||||
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
|
||||
, auth);
|
||||
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030));
|
||||
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid);
|
||||
return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(),
|
||||
flags);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (handle != null)
|
||||
{
|
||||
if (policyHandle != null)
|
||||
{
|
||||
if (domainHandle != null)
|
||||
{
|
||||
domainHandle.Close();
|
||||
}
|
||||
policyHandle.Close();
|
||||
}
|
||||
handle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This specialized method returns a Map of users and local groups for the
|
||||
/// target server where keys are SIDs representing an account and each value
|
||||
/// is an List<object> of SIDs represents the local groups that the account is
|
||||
/// a member of.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This specialized method returns a Map of users and local groups for the
|
||||
/// target server where keys are SIDs representing an account and each value
|
||||
/// is an List<object> of SIDs represents the local groups that the account is
|
||||
/// a member of.
|
||||
/// <p/>
|
||||
/// This method is designed to assist with computing access control for a
|
||||
/// given user when the target object's ACL has local groups. Local groups
|
||||
/// are not listed in a user's group membership (e.g. as represented by the
|
||||
/// tokenGroups constructed attribute retrived via LDAP).
|
||||
/// <p/>
|
||||
/// Domain groups nested inside a local group are currently not expanded. In
|
||||
/// this case the key (SID) type will be SID_TYPE_DOM_GRP rather than
|
||||
/// SID_TYPE_USER.
|
||||
/// </remarks>
|
||||
/// <param name="authorityServerName">The server from which the local groups will be queried.
|
||||
/// </param>
|
||||
/// <param name="auth">The credentials required to query groups and group members.</param>
|
||||
/// <param name="flags">
|
||||
/// Flags that control the behavior of the operation. When all
|
||||
/// name associated with SIDs will be required, the SID_FLAG_RESOLVE_SIDS
|
||||
/// flag should be used which causes all group member SIDs to be resolved
|
||||
/// together in a single more efficient operation.
|
||||
/// </param>
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
internal static Hashtable GetLocalGroupsMap(string authorityServerName, NtlmPasswordAuthentication
|
||||
auth, int flags)
|
||||
{
|
||||
Sid domsid = GetServerSid(authorityServerName, auth);
|
||||
DcerpcHandle handle = null;
|
||||
SamrPolicyHandle policyHandle = null;
|
||||
SamrDomainHandle domainHandle = null;
|
||||
Samr.SamrSamArray sam = new Samr.SamrSamArray();
|
||||
MsrpcEnumerateAliasesInDomain rpc;
|
||||
lock (SidCache)
|
||||
{
|
||||
try
|
||||
{
|
||||
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
|
||||
, auth);
|
||||
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000));
|
||||
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid);
|
||||
rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam
|
||||
);
|
||||
handle.Sendrecv(rpc);
|
||||
if (rpc.Retval != 0)
|
||||
{
|
||||
throw new SmbException(rpc.Retval, false);
|
||||
}
|
||||
Hashtable map = new Hashtable();
|
||||
for (int ei = 0; ei < rpc.Sam.Count; ei++)
|
||||
{
|
||||
Samr.SamrSamEntry entry = rpc.Sam.Entries[ei];
|
||||
Sid[] mems = GetGroupMemberSids0(handle, domainHandle, domsid
|
||||
, entry.Idx, flags);
|
||||
Sid groupSid = new Sid(domsid, entry.Idx);
|
||||
groupSid.Type = SidTypeAlias;
|
||||
groupSid.DomainName = domsid.GetDomainName();
|
||||
groupSid.AcctName = (new UnicodeString(entry.Name, false)).ToString();
|
||||
for (int mi = 0; mi < mems.Length; mi++)
|
||||
{
|
||||
List<object> groups = (List<object>)map.Get(mems[mi]);
|
||||
if (groups == null)
|
||||
{
|
||||
groups = new List<object>();
|
||||
map.Put(mems[mi], groups);
|
||||
}
|
||||
if (!groups.Contains(groupSid))
|
||||
{
|
||||
groups.Add(groupSid);
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (handle != null)
|
||||
{
|
||||
if (policyHandle != null)
|
||||
{
|
||||
if (domainHandle != null)
|
||||
{
|
||||
domainHandle.Close();
|
||||
}
|
||||
policyHandle.Close();
|
||||
}
|
||||
handle.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System.IO;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public class SecurityDescriptor
|
||||
{
|
||||
public int Type;
|
||||
|
||||
public Ace[] Aces;
|
||||
|
||||
public SecurityDescriptor()
|
||||
{
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public SecurityDescriptor(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
Decode(buffer, bufferIndex, len);
|
||||
}
|
||||
|
||||
/// <exception cref="System.IO.IOException"></exception>
|
||||
public virtual int Decode(byte[] buffer, int bufferIndex, int len)
|
||||
{
|
||||
int start = bufferIndex;
|
||||
bufferIndex++;
|
||||
// revision
|
||||
bufferIndex++;
|
||||
Type = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
|
||||
// offset to owner sid
|
||||
bufferIndex += 4;
|
||||
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
|
||||
// offset to group sid
|
||||
bufferIndex += 4;
|
||||
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
|
||||
// offset to sacl
|
||||
bufferIndex += 4;
|
||||
int daclOffset = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
|
||||
bufferIndex = start + daclOffset;
|
||||
bufferIndex++;
|
||||
// revision
|
||||
bufferIndex++;
|
||||
int size = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
int numAces = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
|
||||
bufferIndex += 4;
|
||||
if (numAces > 4096)
|
||||
{
|
||||
throw new IOException("Invalid SecurityDescriptor");
|
||||
}
|
||||
if (daclOffset != 0)
|
||||
{
|
||||
Aces = new Ace[numAces];
|
||||
for (int i = 0; i < numAces; i++)
|
||||
{
|
||||
Aces[i] = new Ace();
|
||||
bufferIndex += Aces[i].Decode(buffer, bufferIndex);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Aces = null;
|
||||
}
|
||||
return bufferIndex - start;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string ret = "SecurityDescriptor:\n";
|
||||
if (Aces != null)
|
||||
{
|
||||
for (int ai = 0; ai < Aces.Length; ai++)
|
||||
{
|
||||
ret += Aces[ai] + "\n";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ret += "NULL";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,692 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
using SharpCifs.Util.Transport;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
public abstract class ServerMessageBlock: Response
|
||||
{
|
||||
internal static LogStream Log = LogStream.GetInstance();
|
||||
|
||||
internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks;
|
||||
|
||||
internal static readonly byte[] Header = { 0xFF, (byte)('S'), (byte)('M'),
|
||||
(byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
internal static void WriteInt2(long val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex] = unchecked((byte)(val));
|
||||
dst[++dstIndex] = unchecked((byte)(val >> 8));
|
||||
}
|
||||
|
||||
internal static void WriteInt4(long val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex] = unchecked((byte)(val));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >> 8));
|
||||
}
|
||||
|
||||
internal static int ReadInt2(byte[] src, int srcIndex)
|
||||
{
|
||||
return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8);
|
||||
}
|
||||
|
||||
internal static int ReadInt4(byte[] src, int srcIndex)
|
||||
{
|
||||
return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2]
|
||||
& 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24);
|
||||
}
|
||||
|
||||
internal static long ReadInt8(byte[] src, int srcIndex)
|
||||
{
|
||||
return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) + unchecked((long)(ReadInt4
|
||||
(src, srcIndex + 4)) << 32);
|
||||
}
|
||||
|
||||
internal static void WriteInt8(long val, byte[] dst, int dstIndex)
|
||||
{
|
||||
dst[dstIndex] = unchecked((byte)(val));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >>= 8));
|
||||
dst[++dstIndex] = unchecked((byte)(val >> 8));
|
||||
}
|
||||
|
||||
internal static long ReadTime(byte[] src, int srcIndex)
|
||||
{
|
||||
int low = ReadInt4(src, srcIndex);
|
||||
int hi = ReadInt4(src, srcIndex + 4);
|
||||
long t = ((long)hi << (int)32L) | (low & unchecked((long)(0xFFFFFFFFL)));
|
||||
t = (t / 10000L - SmbConstants.MillisecondsBetween1970And1601);
|
||||
return t;
|
||||
}
|
||||
|
||||
internal static void WriteTime(long t, byte[] dst, int dstIndex)
|
||||
{
|
||||
if (t != 0L)
|
||||
{
|
||||
t = (t + SmbConstants.MillisecondsBetween1970And1601) * 10000L;
|
||||
}
|
||||
WriteInt8(t, dst, dstIndex);
|
||||
}
|
||||
|
||||
internal static long ReadUTime(byte[] buffer, int bufferIndex)
|
||||
{
|
||||
return ReadInt4(buffer, bufferIndex) * 1000L;
|
||||
}
|
||||
|
||||
internal static void WriteUTime(long t, byte[] dst, int dstIndex)
|
||||
{
|
||||
if (t == 0L || t == unchecked((long)(0xFFFFFFFFFFFFFFFFL)))
|
||||
{
|
||||
WriteInt4(unchecked((int)(0xFFFFFFFF)), dst, dstIndex);
|
||||
return;
|
||||
}
|
||||
// t isn't in DST either
|
||||
WriteInt4((int)(t / 1000L), dst, dstIndex);
|
||||
}
|
||||
|
||||
internal const byte SmbComCreateDirectory = 0x00;
|
||||
|
||||
internal const byte SmbComDeleteDirectory = 0x01;
|
||||
|
||||
internal const byte SmbComClose = 0x04;
|
||||
|
||||
internal const byte SmbComDelete = 0x06;
|
||||
|
||||
internal const byte SmbComRename = 0x07;
|
||||
|
||||
internal const byte SmbComQueryInformation = 0x08;
|
||||
|
||||
internal const byte SmbComWrite = 0x0B;
|
||||
|
||||
internal const byte SmbComCheckDirectory = 0x10;
|
||||
|
||||
internal const byte SmbComTransaction = 0x25;
|
||||
|
||||
internal const byte SmbComTransactionSecondary = 0x26;
|
||||
|
||||
internal const byte SmbComMove = 0x2A;
|
||||
|
||||
internal const byte SmbComEcho = 0x2B;
|
||||
|
||||
internal const byte SmbComOpenAndx = 0x2D;
|
||||
|
||||
internal const byte SmbComReadAndx = 0x2E;
|
||||
|
||||
internal const byte SmbComWriteAndx = 0x2F;
|
||||
|
||||
internal const byte SmbComTransaction2 = 0x32;
|
||||
|
||||
internal const byte SmbComFindClose2 = 0x34;
|
||||
|
||||
internal const byte SmbComTreeDisconnect = 0x71;
|
||||
|
||||
internal const byte SmbComNegotiate = 0x72;
|
||||
|
||||
internal const byte SmbComSessionSetupAndx = 0x73;
|
||||
|
||||
internal const byte SmbComLogoffAndx = 0x74;
|
||||
|
||||
internal const byte SmbComTreeConnectAndx = 0x75;
|
||||
|
||||
internal const byte SmbComNtTransact = 0xA0;
|
||||
|
||||
internal const byte SmbComNtTransactSecondary = 0xA1;
|
||||
|
||||
internal const byte SmbComNtCreateAndx = 0xA2;
|
||||
|
||||
internal byte Command;
|
||||
|
||||
internal byte Flags;
|
||||
|
||||
internal int HeaderStart;
|
||||
|
||||
internal int Length;
|
||||
|
||||
internal int BatchLevel;
|
||||
|
||||
internal int ErrorCode;
|
||||
|
||||
internal int Flags2;
|
||||
|
||||
internal int Tid;
|
||||
|
||||
internal int Pid;
|
||||
|
||||
internal int Uid;
|
||||
|
||||
internal int Mid;
|
||||
|
||||
internal int WordCount;
|
||||
|
||||
internal int ByteCount;
|
||||
|
||||
internal bool UseUnicode;
|
||||
|
||||
internal bool Received;
|
||||
|
||||
internal bool ExtendedSecurity;
|
||||
|
||||
internal long ResponseTimeout = 1;
|
||||
|
||||
internal int SignSeq;
|
||||
|
||||
internal bool VerifyFailed;
|
||||
|
||||
internal NtlmPasswordAuthentication Auth = null;
|
||||
|
||||
internal string Path;
|
||||
|
||||
internal SigningDigest Digest;
|
||||
|
||||
internal ServerMessageBlock Response;
|
||||
|
||||
public ServerMessageBlock()
|
||||
{
|
||||
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
|
||||
));
|
||||
Pid = SmbConstants.Pid;
|
||||
BatchLevel = 0;
|
||||
}
|
||||
|
||||
internal virtual void Reset()
|
||||
{
|
||||
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
|
||||
));
|
||||
Flags2 = 0;
|
||||
ErrorCode = 0;
|
||||
Received = false;
|
||||
Digest = null;
|
||||
}
|
||||
|
||||
internal virtual int WriteString(string str, byte[] dst, int dstIndex)
|
||||
{
|
||||
return WriteString(str, dst, dstIndex, UseUnicode);
|
||||
}
|
||||
|
||||
internal virtual int WriteString(string str, byte[] dst, int dstIndex, bool useUnicode
|
||||
)
|
||||
{
|
||||
int start = dstIndex;
|
||||
try
|
||||
{
|
||||
if (useUnicode)
|
||||
{
|
||||
// Unicode requires word alignment
|
||||
if (((dstIndex - HeaderStart) % 2) != 0)
|
||||
{
|
||||
dst[dstIndex++] = (byte)('\0');
|
||||
}
|
||||
Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex
|
||||
, str.Length * 2);
|
||||
dstIndex += str.Length * 2;
|
||||
dst[dstIndex++] = (byte)('\0');
|
||||
dst[dstIndex++] = (byte)('\0');
|
||||
}
|
||||
else
|
||||
{
|
||||
byte[] b = Runtime.GetBytesForString(str, SmbConstants.OemEncoding);
|
||||
Array.Copy(b, 0, dst, dstIndex, b.Length);
|
||||
dstIndex += b.Length;
|
||||
dst[dstIndex++] = (byte)('\0');
|
||||
}
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
if (Log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(uee, Log);
|
||||
}
|
||||
}
|
||||
return dstIndex - start;
|
||||
}
|
||||
|
||||
internal virtual string ReadString(byte[] src, int srcIndex)
|
||||
{
|
||||
return ReadString(src, srcIndex, 256, UseUnicode);
|
||||
}
|
||||
|
||||
internal virtual string ReadString(byte[] src, int srcIndex, int maxLen, bool useUnicode
|
||||
)
|
||||
{
|
||||
int len = 0;
|
||||
string str = null;
|
||||
try
|
||||
{
|
||||
if (useUnicode)
|
||||
{
|
||||
// Unicode requires word alignment
|
||||
if (((srcIndex - HeaderStart) % 2) != 0)
|
||||
{
|
||||
srcIndex++;
|
||||
}
|
||||
while (src[srcIndex + len] != 0x00 || src[srcIndex
|
||||
+ len + 1] != 0x00)
|
||||
{
|
||||
len += 2;
|
||||
if (len > maxLen)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
|
||||
128);
|
||||
}
|
||||
throw new RuntimeException("zero termination not found");
|
||||
}
|
||||
}
|
||||
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
|
||||
}
|
||||
else
|
||||
{
|
||||
while (src[srcIndex + len] != 0x00)
|
||||
{
|
||||
len++;
|
||||
if (len > maxLen)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
|
||||
128);
|
||||
}
|
||||
throw new RuntimeException("zero termination not found");
|
||||
}
|
||||
}
|
||||
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding);
|
||||
}
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
if (Log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(uee, Log);
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen
|
||||
, bool useUnicode)
|
||||
{
|
||||
int len = 0;
|
||||
string str = null;
|
||||
try
|
||||
{
|
||||
if (useUnicode)
|
||||
{
|
||||
// Unicode requires word alignment
|
||||
if (((srcIndex - HeaderStart) % 2) != 0)
|
||||
{
|
||||
srcIndex++;
|
||||
}
|
||||
for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2)
|
||||
{
|
||||
if (src[srcIndex + len] == 0x00 && src[srcIndex
|
||||
+ len + 1] == 0x00)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (len > maxLen)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
|
||||
128);
|
||||
}
|
||||
throw new RuntimeException("zero termination not found");
|
||||
}
|
||||
}
|
||||
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (len = 0; srcIndex < srcEnd; len++)
|
||||
{
|
||||
if (src[srcIndex + len] == 0x00)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (len > maxLen)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
|
||||
128);
|
||||
}
|
||||
throw new RuntimeException("zero termination not found");
|
||||
}
|
||||
}
|
||||
str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding);
|
||||
}
|
||||
}
|
||||
catch (UnsupportedEncodingException uee)
|
||||
{
|
||||
if (Log.Level > 1)
|
||||
{
|
||||
Runtime.PrintStackTrace(uee, Log);
|
||||
}
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
internal virtual int StringWireLength(string str, int offset)
|
||||
{
|
||||
int len = str.Length + 1;
|
||||
if (UseUnicode)
|
||||
{
|
||||
len = str.Length * 2 + 2;
|
||||
len = (offset % 2) != 0 ? len + 1 : len;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
internal virtual int ReadStringLength(byte[] src, int srcIndex, int max)
|
||||
{
|
||||
int len = 0;
|
||||
while (src[srcIndex + len] != 0x00)
|
||||
{
|
||||
if (len++ > max)
|
||||
{
|
||||
throw new RuntimeException("zero termination not found: " + this);
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
|
||||
internal virtual int Encode(byte[] dst, int dstIndex)
|
||||
{
|
||||
int start = HeaderStart = dstIndex;
|
||||
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
|
||||
WordCount = WriteParameterWordsWireFormat(dst, dstIndex + 1);
|
||||
dst[dstIndex++] = unchecked((byte)((WordCount / 2) & 0xFF));
|
||||
dstIndex += WordCount;
|
||||
WordCount /= 2;
|
||||
ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
|
||||
dst[dstIndex++] = unchecked((byte)(ByteCount & 0xFF));
|
||||
dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & 0xFF));
|
||||
dstIndex += ByteCount;
|
||||
Length = dstIndex - start;
|
||||
if (Digest != null)
|
||||
{
|
||||
Digest.Sign(dst, HeaderStart, Length, this, Response);
|
||||
}
|
||||
return Length;
|
||||
}
|
||||
|
||||
internal virtual int Decode(byte[] buffer, int bufferIndex)
|
||||
{
|
||||
int start = HeaderStart = bufferIndex;
|
||||
bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
|
||||
WordCount = buffer[bufferIndex++];
|
||||
if (WordCount != 0)
|
||||
{
|
||||
int n;
|
||||
if ((n = ReadParameterWordsWireFormat(buffer, bufferIndex)) != WordCount * 2)
|
||||
{
|
||||
if (Log.Level >= 5)
|
||||
{
|
||||
Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned "
|
||||
+ n);
|
||||
}
|
||||
}
|
||||
bufferIndex += WordCount * 2;
|
||||
}
|
||||
ByteCount = ReadInt2(buffer, bufferIndex);
|
||||
bufferIndex += 2;
|
||||
if (ByteCount != 0)
|
||||
{
|
||||
int n;
|
||||
if ((n = ReadBytesWireFormat(buffer, bufferIndex)) != ByteCount)
|
||||
{
|
||||
if (Log.Level >= 5)
|
||||
{
|
||||
Log.WriteLine("byteCount=" + ByteCount + " but readBytesWireFormat returned " + n
|
||||
);
|
||||
}
|
||||
}
|
||||
// Don't think we can rely on n being correct here. Must use byteCount.
|
||||
// Last paragraph of section 3.13.3 eludes to this.
|
||||
bufferIndex += ByteCount;
|
||||
}
|
||||
Length = bufferIndex - start;
|
||||
return Length;
|
||||
}
|
||||
|
||||
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
|
||||
{
|
||||
Array.Copy(Header, 0, dst, dstIndex, Header.Length);
|
||||
dst[dstIndex + SmbConstants.CmdOffset] = Command;
|
||||
dst[dstIndex + SmbConstants.FlagsOffset] = Flags;
|
||||
WriteInt2(Flags2, dst, dstIndex + SmbConstants.FlagsOffset + 1);
|
||||
dstIndex += SmbConstants.TidOffset;
|
||||
WriteInt2(Tid, dst, dstIndex);
|
||||
WriteInt2(Pid, dst, dstIndex + 2);
|
||||
WriteInt2(Uid, dst, dstIndex + 4);
|
||||
WriteInt2(Mid, dst, dstIndex + 6);
|
||||
return SmbConstants.HeaderLength;
|
||||
}
|
||||
|
||||
internal virtual int ReadHeaderWireFormat(byte[] buffer, int bufferIndex)
|
||||
{
|
||||
Command = buffer[bufferIndex + SmbConstants.CmdOffset];
|
||||
ErrorCode = ReadInt4(buffer, bufferIndex + SmbConstants.ErrorCodeOffset);
|
||||
Flags = buffer[bufferIndex + SmbConstants.FlagsOffset];
|
||||
Flags2 = ReadInt2(buffer, bufferIndex + SmbConstants.FlagsOffset + 1);
|
||||
Tid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset);
|
||||
Pid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 2);
|
||||
Uid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 4);
|
||||
Mid = ReadInt2(buffer, bufferIndex + SmbConstants.TidOffset + 6);
|
||||
return SmbConstants.HeaderLength;
|
||||
}
|
||||
|
||||
internal virtual bool IsResponse()
|
||||
{
|
||||
return (Flags & SmbConstants.FlagsResponse) == SmbConstants.FlagsResponse;
|
||||
}
|
||||
|
||||
internal abstract int WriteParameterWordsWireFormat(byte[] dst, int dstIndex);
|
||||
|
||||
internal abstract int WriteBytesWireFormat(byte[] dst, int dstIndex);
|
||||
|
||||
internal abstract int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
|
||||
);
|
||||
|
||||
internal abstract int ReadBytesWireFormat(byte[] buffer, int bufferIndex);
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return Mid;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return obj is ServerMessageBlock && ((ServerMessageBlock)obj)
|
||||
.Mid == Mid;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string c;
|
||||
switch (Command)
|
||||
{
|
||||
case SmbComNegotiate:
|
||||
{
|
||||
c = "SMB_COM_NEGOTIATE";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComSessionSetupAndx:
|
||||
{
|
||||
c = "SMB_COM_SESSION_SETUP_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComTreeConnectAndx:
|
||||
{
|
||||
c = "SMB_COM_TREE_CONNECT_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComQueryInformation:
|
||||
{
|
||||
c = "SMB_COM_QUERY_INFORMATION";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComCheckDirectory:
|
||||
{
|
||||
c = "SMB_COM_CHECK_DIRECTORY";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComTransaction:
|
||||
{
|
||||
c = "SMB_COM_TRANSACTION";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComTransaction2:
|
||||
{
|
||||
c = "SMB_COM_TRANSACTION2";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComTransactionSecondary:
|
||||
{
|
||||
c = "SMB_COM_TRANSACTION_SECONDARY";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComFindClose2:
|
||||
{
|
||||
c = "SMB_COM_FIND_CLOSE2";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComTreeDisconnect:
|
||||
{
|
||||
c = "SMB_COM_TREE_DISCONNECT";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComLogoffAndx:
|
||||
{
|
||||
c = "SMB_COM_LOGOFF_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComEcho:
|
||||
{
|
||||
c = "SMB_COM_ECHO";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComMove:
|
||||
{
|
||||
c = "SMB_COM_MOVE";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComRename:
|
||||
{
|
||||
c = "SMB_COM_RENAME";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComDelete:
|
||||
{
|
||||
c = "SMB_COM_DELETE";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComDeleteDirectory:
|
||||
{
|
||||
c = "SMB_COM_DELETE_DIRECTORY";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComNtCreateAndx:
|
||||
{
|
||||
c = "SMB_COM_NT_CREATE_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComOpenAndx:
|
||||
{
|
||||
c = "SMB_COM_OPEN_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComReadAndx:
|
||||
{
|
||||
c = "SMB_COM_READ_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComClose:
|
||||
{
|
||||
c = "SMB_COM_CLOSE";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComWriteAndx:
|
||||
{
|
||||
c = "SMB_COM_WRITE_ANDX";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComCreateDirectory:
|
||||
{
|
||||
c = "SMB_COM_CREATE_DIRECTORY";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComNtTransact:
|
||||
{
|
||||
c = "SMB_COM_NT_TRANSACT";
|
||||
break;
|
||||
}
|
||||
|
||||
case SmbComNtTransactSecondary:
|
||||
{
|
||||
c = "SMB_COM_NT_TRANSACT_SECONDARY";
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
c = "UNKNOWN";
|
||||
break;
|
||||
}
|
||||
}
|
||||
string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode);
|
||||
return "command=" + c + ",received=" + Received + ",errorCode=" + str
|
||||
+ ",flags=0x" + Hexdump.ToHexString(Flags & 0xFF, 4) + ",flags2=0x"
|
||||
+ Hexdump.ToHexString(Flags2, 4) + ",signSeq=" + SignSeq + ",tid=" + Tid + ",pid="
|
||||
+ Pid + ",uid=" + Uid + ",mid=" + Mid + ",wordCount=" + WordCount + ",byteCount="
|
||||
+ ByteCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
257
Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs
Normal file
257
Emby.Server.Implementations/IO/SharpCifs/Smb/SigningDigest.cs
Normal file
@@ -0,0 +1,257 @@
|
||||
// This code is derived from jcifs smb client library <jcifs at samba dot org>
|
||||
// Ported by J. Arturo <webmaster at komodosoft dot net>
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or
|
||||
// modify it under the terms of the GNU Lesser General Public
|
||||
// License as published by the Free Software Foundation; either
|
||||
// version 2.1 of the License, or (at your option) any later version.
|
||||
//
|
||||
// This library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
using System;
|
||||
using SharpCifs.Util;
|
||||
using SharpCifs.Util.Sharpen;
|
||||
|
||||
namespace SharpCifs.Smb
|
||||
{
|
||||
/// <summary>To filter 0 len updates and for debugging</summary>
|
||||
public class SigningDigest
|
||||
{
|
||||
internal static LogStream Log = LogStream.GetInstance();
|
||||
|
||||
private MessageDigest _digest;
|
||||
|
||||
private byte[] _macSigningKey;
|
||||
|
||||
private bool _bypass;
|
||||
|
||||
private int _updates;
|
||||
|
||||
private int _signSequence;
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
public SigningDigest(byte[] macSigningKey, bool bypass)
|
||||
{
|
||||
try
|
||||
{
|
||||
_digest = MessageDigest.GetInstance("MD5");
|
||||
}
|
||||
catch (NoSuchAlgorithmException ex)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, Log);
|
||||
}
|
||||
throw new SmbException("MD5", ex);
|
||||
}
|
||||
this._macSigningKey = macSigningKey;
|
||||
this._bypass = bypass;
|
||||
_updates = 0;
|
||||
_signSequence = 0;
|
||||
if (Log.Level >= 5)
|
||||
{
|
||||
Log.WriteLine("macSigningKey:");
|
||||
Hexdump.ToHexdump(Log, macSigningKey, 0, macSigningKey.Length);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
|
||||
public SigningDigest(SmbTransport transport, NtlmPasswordAuthentication auth)
|
||||
{
|
||||
try
|
||||
{
|
||||
_digest = MessageDigest.GetInstance("MD5");
|
||||
}
|
||||
catch (NoSuchAlgorithmException ex)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, Log);
|
||||
}
|
||||
throw new SmbException("MD5", ex);
|
||||
}
|
||||
try
|
||||
{
|
||||
switch (SmbConstants.LmCompatibility)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
{
|
||||
_macSigningKey = new byte[40];
|
||||
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
|
||||
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
|
||||
, 16, 24);
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 4:
|
||||
case 5:
|
||||
{
|
||||
_macSigningKey = new byte[16];
|
||||
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
{
|
||||
_macSigningKey = new byte[40];
|
||||
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
|
||||
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
|
||||
, 16, 24);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new SmbException(string.Empty, ex);
|
||||
}
|
||||
if (Log.Level >= 5)
|
||||
{
|
||||
Log.WriteLine("LM_COMPATIBILITY=" + SmbConstants.LmCompatibility);
|
||||
Hexdump.ToHexdump(Log, _macSigningKey, 0, _macSigningKey.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void Update(byte[] input, int offset, int len)
|
||||
{
|
||||
if (Log.Level >= 5)
|
||||
{
|
||||
Log.WriteLine("update: " + _updates + " " + offset + ":" + len);
|
||||
Hexdump.ToHexdump(Log, input, offset, Math.Min(len, 256));
|
||||
Log.Flush();
|
||||
}
|
||||
if (len == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_digest.Update(input, offset, len);
|
||||
_updates++;
|
||||
}
|
||||
|
||||
public virtual byte[] Digest()
|
||||
{
|
||||
byte[] b;
|
||||
b = _digest.Digest();
|
||||
if (Log.Level >= 5)
|
||||
{
|
||||
Log.WriteLine("digest: ");
|
||||
Hexdump.ToHexdump(Log, b, 0, b.Length);
|
||||
Log.Flush();
|
||||
}
|
||||
_updates = 0;
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Performs MAC signing of the SMB.</summary>
|
||||
/// <remarks>
|
||||
/// Performs MAC signing of the SMB. This is done as follows.
|
||||
/// The signature field of the SMB is overwritted with the sequence number;
|
||||
/// The MD5 digest of the MAC signing key + the entire SMB is taken;
|
||||
/// The first 8 bytes of this are placed in the signature field.
|
||||
/// </remarks>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="offset">The starting offset at which the SMB header begins.</param>
|
||||
/// <param name="length">The length of the SMB data starting at offset.</param>
|
||||
internal virtual void Sign(byte[] data, int offset, int length, ServerMessageBlock
|
||||
request, ServerMessageBlock response)
|
||||
{
|
||||
request.SignSeq = _signSequence;
|
||||
if (response != null)
|
||||
{
|
||||
response.SignSeq = _signSequence + 1;
|
||||
response.VerifyFailed = false;
|
||||
}
|
||||
try
|
||||
{
|
||||
Update(_macSigningKey, 0, _macSigningKey.Length);
|
||||
int index = offset + SmbConstants.SignatureOffset;
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
data[index + i] = 0;
|
||||
}
|
||||
ServerMessageBlock.WriteInt4(_signSequence, data, index);
|
||||
Update(data, offset, length);
|
||||
Array.Copy(Digest(), 0, data, index, 8);
|
||||
if (_bypass)
|
||||
{
|
||||
_bypass = false;
|
||||
Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index,
|
||||
8);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (Log.Level > 0)
|
||||
{
|
||||
Runtime.PrintStackTrace(ex, Log);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_signSequence += 2;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Performs MAC signature verification.</summary>
|
||||
/// <remarks>
|
||||
/// Performs MAC signature verification. This calculates the signature
|
||||
/// of the SMB and compares it to the signature field on the SMB itself.
|
||||
/// </remarks>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="offset">The starting offset at which the SMB header begins.</param>
|
||||
/// <param name="length">The length of the SMB data starting at offset.</param>
|
||||
internal virtual bool Verify(byte[] data, int offset, ServerMessageBlock response
|
||||
)
|
||||
{
|
||||
Update(_macSigningKey, 0, _macSigningKey.Length);
|
||||
int index = offset;
|
||||
Update(data, index, SmbConstants.SignatureOffset);
|
||||
index += SmbConstants.SignatureOffset;
|
||||
byte[] sequence = new byte[8];
|
||||
ServerMessageBlock.WriteInt4(response.SignSeq, sequence, 0);
|
||||
Update(sequence, 0, sequence.Length);
|
||||
index += 8;
|
||||
if (response.Command == ServerMessageBlock.SmbComReadAndx)
|
||||
{
|
||||
SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
|
||||
int length = response.Length - raxr.DataLength;
|
||||
Update(data, index, length - SmbConstants.SignatureOffset - 8);
|
||||
Update(raxr.B, raxr.Off, raxr.DataLength);
|
||||
}
|
||||
else
|
||||
{
|
||||
Update(data, index, response.Length - SmbConstants.SignatureOffset - 8);
|
||||
}
|
||||
byte[] signature = Digest();
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
if (signature[i] != data[offset + SmbConstants.SignatureOffset + i])
|
||||
{
|
||||
if (Log.Level >= 2)
|
||||
{
|
||||
Log.WriteLine("signature verification failure");
|
||||
Hexdump.ToHexdump(Log, signature, 0, 8);
|
||||
Hexdump.ToHexdump(Log, data, offset + SmbConstants.SignatureOffset, 8);
|
||||
}
|
||||
return response.VerifyFailed = true;
|
||||
}
|
||||
}
|
||||
return response.VerifyFailed = false;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString
|
||||
(_macSigningKey, 0, _macSigningKey.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user