Merge pull request #5 from jellyfin/dev

Dev
This commit is contained in:
LogicalPhallacy 2019-01-05 16:22:18 -08:00 committed by GitHub
commit 8ff89fdc0c
444 changed files with 1465 additions and 45571 deletions

View File

@ -1 +1,5 @@
.git
.dockerignore
Dockerfile
CONTRIBUTORS.md
README.md

View File

@ -1,32 +1,12 @@
kind: pipeline
name: build:debian
name: build
steps:
- name: submodules
image: docker:git
commands:
- git submodule update --init --recursive
- name: build:debian
image: plugins/docker
group: build
settings:
repo: jellyfin/jellyfin
dry_run: true
dockerfile: Dockerfile.debian_package
---
kind: pipeline
name: build:docker
steps:
- name: submodules
image: docker:git
- name: build
image: microsoft/dotnet:2-sdk
commands:
- git submodule update --init --recursive
- name: build:docker
image: plugins/docker
group: build
settings:
repo: jellyfin/jellyfin
dry_run: true
- dotnet publish --configuration release --output /release

2
.gitignore vendored
View File

@ -1,5 +1,7 @@
!*
.directory
#################
## Eclipse
#################

28
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,28 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Jellyfin.Server/bin/Debug/netcoreapp2.1/jellyfin.dll",
"args": [],
"cwd": "${workspaceFolder}/Jellyfin.Server",
// For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
"console": "internalConsole",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
,]
}

15
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Jellyfin.Server/Jellyfin.Server.csproj"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@ -8,6 +8,9 @@
- [flemse](https://github.com/flemse)
- [bfayers](https://github.com/bfayers)
- [Bond_009](https://github.com/Bond-009)
- [AnthonyLavado](https://github.com/anthonylavado)
- [sparky8251](https://github.com/sparky8251)
- [LeoVerto](https://github.com/LeoVerto]
# Emby Contributors

View File

@ -10,9 +10,15 @@ RUN export DOTNET_CLI_TELEMETRY_OPTOUT=1 \
FROM microsoft/dotnet:${DOTNET_VERSION}-runtime
COPY --from=builder /jellyfin /jellyfin
EXPOSE 8096
RUN apt update \
&& apt install -y ffmpeg
VOLUME /config /media
ARG FFMPEG_URL=https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.0.3-64bit-static.tar.xz
RUN apt update \
&& apt install -y xz-utils \
&& curl ${FFMPEG_URL} | tar Jxf - -C /usr/bin --wildcards --strip-components=1 ffmpeg*/ffmpeg ffmpeg*/ffprobe \
&& apt remove -y xz-utils
ENTRYPOINT if [ -n "$PUID$PGUID" ]; \
then echo "PUID/PGID are deprecated. Use Docker user param." >&2; exit 1; \
else dotnet /jellyfin/jellyfin.dll -programdata /config; fi

View File

@ -119,7 +119,7 @@ namespace Emby.Dlna.Ssdp
}
};
EventHelper.FireEventIfNotNull(DeviceDiscoveredInternal, this, args, _logger);
DeviceDiscoveredInternal?.Invoke(this, args);
}
private void _DeviceLocator_DeviceUnavailable(object sender, DeviceUnavailableEventArgs e)
@ -139,7 +139,7 @@ namespace Emby.Dlna.Ssdp
}
};
EventHelper.FireEventIfNotNull(DeviceLeft, this, args, _logger);
DeviceLeft?.Invoke(this, args);
}
public void Dispose()

View File

@ -1,19 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ImageMagickSharp\ImageMagickSharp\ImageMagickSharp.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="fonts\robotoregular.ttf" />
</ItemGroup>
</Project>

View File

@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Emby.Drawing.ImageMagick
{
internal static class ImageHelpers
{
internal static List<string> ProjectPaths(string[] paths, int count)
{
if (count <= 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (paths.Length == 0)
{
throw new ArgumentOutOfRangeException("paths");
}
var list = new List<string>();
AddToList(list, paths, count);
return list.Take(count).ToList();
}
private static void AddToList(List<string> list, string[] paths, int count)
{
while (list.Count < count)
{
foreach (var path in paths)
{
list.Add(path);
if (list.Count >= count)
{
return;
}
}
}
}
}
}

View File

@ -1,354 +0,0 @@
using System.Threading.Tasks;
using ImageMagickSharp;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Drawing;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.System;
namespace Emby.Drawing.ImageMagick
{
public class ImageMagickEncoder : IImageEncoder, IDisposable
{
private readonly ILogger _logger;
private readonly IApplicationPaths _appPaths;
private readonly Func<IHttpClient> _httpClientFactory;
private readonly IFileSystem _fileSystem;
private readonly IEnvironmentInfo _environment;
public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths, Func<IHttpClient> httpClientFactory, IFileSystem fileSystem, IEnvironmentInfo environment)
{
_logger = logger;
_appPaths = appPaths;
_httpClientFactory = httpClientFactory;
_fileSystem = fileSystem;
_environment = environment;
LogVersion();
}
public string[] SupportedInputFormats
{
get
{
// Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
return new[]
{
"tiff",
"tif",
"jpeg",
"jpg",
"png",
"aiff",
"cr2",
"crw",
"dng",
// Remove until supported
//"nef",
"orf",
"pef",
"arw",
"webp",
"gif",
"bmp",
"erf",
"raf",
"rw2",
"nrw"
};
}
}
public ImageFormat[] SupportedOutputFormats
{
get
{
if (_webpAvailable)
{
return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
}
return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
}
}
private void LogVersion()
{
_logger.LogInformation("ImageMagick version: " + GetVersion());
TestWebp();
Wand.SetMagickThreadCount(1);
}
public static string GetVersion()
{
return Wand.VersionString;
}
private bool _webpAvailable = true;
private void TestWebp()
{
try
{
var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(tmpPath));
using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
{
wand.SaveImage(tmpPath);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error loading webp");
_webpAvailable = false;
}
}
public ImageSize GetImageSize(string path)
{
CheckDisposed();
using (var wand = new MagickWand())
{
wand.PingImage(path);
var img = wand.CurrentImage;
return new ImageSize
{
Width = img.Width,
Height = img.Height
};
}
}
private bool HasTransparency(string path)
{
var ext = Path.GetExtension(path);
return string.Equals(ext, ".png", StringComparison.OrdinalIgnoreCase) ||
string.Equals(ext, ".webp", StringComparison.OrdinalIgnoreCase);
}
public string EncodeImage(string inputPath, DateTime dateModified, string outputPath, bool autoOrient, ImageOrientation? orientation, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
{
// Even if the caller specified 100, don't use it because it takes forever
quality = Math.Min(quality, 99);
if (string.IsNullOrEmpty(options.BackgroundColor) || !HasTransparency(inputPath))
{
using (var originalImage = new MagickWand(inputPath))
{
if (options.CropWhiteSpace)
{
originalImage.CurrentImage.TrimImage(10);
}
var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
if (!options.CropWhiteSpace && options.HasDefaultOptions(inputPath, originalImageSize) && !autoOrient)
{
// Just spit out the original file if all the options are default
return inputPath;
}
var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
var width = Convert.ToInt32(Math.Round(newImageSize.Width));
var height = Convert.ToInt32(Math.Round(newImageSize.Height));
ScaleImage(originalImage, width, height, options.Blur ?? 0);
if (autoOrient)
{
AutoOrientImage(originalImage);
}
AddForegroundLayer(originalImage, options);
DrawIndicator(originalImage, width, height, options);
originalImage.CurrentImage.CompressionQuality = quality;
originalImage.CurrentImage.StripImage();
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
originalImage.SaveImage(outputPath);
}
}
else
{
using (var originalImage = new MagickWand(inputPath))
{
var originalImageSize = new ImageSize(originalImage.CurrentImage.Width, originalImage.CurrentImage.Height);
var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
var width = Convert.ToInt32(Math.Round(newImageSize.Width));
var height = Convert.ToInt32(Math.Round(newImageSize.Height));
using (var wand = new MagickWand(width, height, options.BackgroundColor))
{
ScaleImage(originalImage, width, height, options.Blur ?? 0);
if (autoOrient)
{
AutoOrientImage(originalImage);
}
wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
AddForegroundLayer(wand, options);
DrawIndicator(wand, width, height, options);
wand.CurrentImage.CompressionQuality = quality;
wand.CurrentImage.StripImage();
wand.SaveImage(outputPath);
}
}
}
return outputPath;
}
private void AddForegroundLayer(MagickWand wand, ImageProcessingOptions options)
{
if (string.IsNullOrEmpty(options.ForegroundLayer))
{
return;
}
Double opacity;
if (!Double.TryParse(options.ForegroundLayer, out opacity)) opacity = .4;
using (var pixel = new PixelWand("#000", opacity))
using (var overlay = new MagickWand(wand.CurrentImage.Width, wand.CurrentImage.Height, pixel))
{
wand.CurrentImage.CompositeImage(overlay, CompositeOperator.OverCompositeOp, 0, 0);
}
}
private void AutoOrientImage(MagickWand wand)
{
wand.CurrentImage.AutoOrientImage();
}
public static void RotateImage(MagickWand wand, float angle)
{
using (var pixelWand = new PixelWand("none", 1))
{
wand.CurrentImage.RotateImage(pixelWand, angle);
}
}
private void ScaleImage(MagickWand wand, int width, int height, int blur)
{
var useResize = blur > 1;
if (useResize)
{
wand.CurrentImage.ResizeImage(width, height, FilterTypes.GaussianFilter, blur);
}
else
{
wand.CurrentImage.ScaleImage(width, height);
}
}
/// <summary>
/// Draws the indicator.
/// </summary>
/// <param name="wand">The wand.</param>
/// <param name="imageWidth">Width of the image.</param>
/// <param name="imageHeight">Height of the image.</param>
/// <param name="options">The options.</param>
private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
{
if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
{
return;
}
try
{
if (options.AddPlayedIndicator)
{
var currentImageSize = new ImageSize(imageWidth, imageHeight);
var task = new PlayedIndicatorDrawer(_appPaths, _httpClientFactory(), _fileSystem).DrawPlayedIndicator(wand, currentImageSize);
Task.WaitAll(task);
}
else if (options.UnplayedCount.HasValue)
{
var currentImageSize = new ImageSize(imageWidth, imageHeight);
new UnplayedCountIndicator(_appPaths, _fileSystem).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
}
if (options.PercentPlayed > 0)
{
new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error drawing indicator overlay");
}
}
public void CreateImageCollage(ImageCollageOptions options)
{
double ratio = options.Width;
ratio /= options.Height;
if (ratio >= 1.4)
{
new StripCollageBuilder(_appPaths, _fileSystem).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
}
else if (ratio >= .9)
{
new StripCollageBuilder(_appPaths, _fileSystem).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
}
else
{
new StripCollageBuilder(_appPaths, _fileSystem).BuildPosterCollage(options.InputPaths, options.OutputPath, options.Width, options.Height);
}
}
public string Name
{
get { return "ImageMagick"; }
}
private bool _disposed;
public void Dispose()
{
_disposed = true;
Wand.CloseEnvironment();
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
public bool SupportsImageCollageCreation
{
get
{
return true;
}
}
public bool SupportsImageEncoding
{
get { return true; }
}
}
}

View File

@ -1,40 +0,0 @@
using ImageMagickSharp;
using System;
namespace Emby.Drawing.ImageMagick
{
public class PercentPlayedDrawer
{
private const int IndicatorHeight = 8;
public void Process(MagickWand wand, double percent)
{
var currentImage = wand.CurrentImage;
var height = currentImage.Height;
using (var draw = new DrawingWand())
{
using (PixelWand pixel = new PixelWand())
{
var endX = currentImage.Width - 1;
var endY = height - 1;
pixel.Color = "black";
pixel.Opacity = 0.4;
draw.FillColor = pixel;
draw.DrawRectangle(0, endY - IndicatorHeight, endX, endY);
double foregroundWidth = endX;
foregroundWidth *= percent;
foregroundWidth /= 100;
pixel.Color = "#52B54B";
pixel.Opacity = 0;
draw.FillColor = pixel;
draw.DrawRectangle(0, endY - IndicatorHeight, Convert.ToInt32(Math.Round(foregroundWidth)), endY);
wand.CurrentImage.DrawImage(draw);
}
}
}
}
}

View File

@ -1,125 +0,0 @@
using ImageMagickSharp;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Drawing;
using System;
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
namespace Emby.Drawing.ImageMagick
{
public class PlayedIndicatorDrawer
{
private const int FontSize = 52;
private const int OffsetFromTopRightCorner = 38;
private readonly IApplicationPaths _appPaths;
private readonly IHttpClient _iHttpClient;
private readonly IFileSystem _fileSystem;
public PlayedIndicatorDrawer(IApplicationPaths appPaths, IHttpClient iHttpClient, IFileSystem fileSystem)
{
_appPaths = appPaths;
_iHttpClient = iHttpClient;
_fileSystem = fileSystem;
}
public async Task DrawPlayedIndicator(MagickWand wand, ImageSize imageSize)
{
var x = imageSize.Width - OffsetFromTopRightCorner;
using (var draw = new DrawingWand())
{
using (PixelWand pixel = new PixelWand())
{
pixel.Color = "#52B54B";
pixel.Opacity = 0.2;
draw.FillColor = pixel;
draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20);
pixel.Opacity = 0;
pixel.Color = "white";
draw.FillColor = pixel;
draw.Font = await DownloadFont("webdings.ttf", "https://github.com/MediaBrowser/Emby.Resources/raw/master/fonts/webdings.ttf", _appPaths, _iHttpClient, _fileSystem).ConfigureAwait(false);
draw.FontSize = FontSize;
draw.FontStyle = FontStyleType.NormalStyle;
draw.TextAlignment = TextAlignType.CenterAlign;
draw.FontWeight = FontWeightType.RegularStyle;
draw.TextAntialias = true;
draw.DrawAnnotation(x + 4, OffsetFromTopRightCorner + 14, "a");
draw.FillColor = pixel;
wand.CurrentImage.DrawImage(draw);
}
}
}
internal static string ExtractFont(string name, IApplicationPaths paths, IFileSystem fileSystem)
{
var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name);
if (fileSystem.FileExists(filePath))
{
return filePath;
}
var namespacePath = typeof(PlayedIndicatorDrawer).Namespace + ".fonts." + name;
var tempPath = Path.Combine(paths.TempDirectory, Guid.NewGuid().ToString("N") + ".ttf");
fileSystem.CreateDirectory(fileSystem.GetDirectoryName(tempPath));
using (var stream = typeof(PlayedIndicatorDrawer).Assembly.GetManifestResourceStream(namespacePath))
{
using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
stream.CopyTo(fileStream);
}
}
fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath));
try
{
fileSystem.CopyFile(tempPath, filePath, false);
}
catch (IOException)
{
}
return tempPath;
}
internal static async Task<string> DownloadFont(string name, string url, IApplicationPaths paths, IHttpClient httpClient, IFileSystem fileSystem)
{
var filePath = Path.Combine(paths.ProgramDataPath, "fonts", name);
if (fileSystem.FileExists(filePath))
{
return filePath;
}
var tempPath = await httpClient.GetTempFile(new HttpRequestOptions
{
Url = url,
Progress = new SimpleProgress<double>()
}).ConfigureAwait(false);
fileSystem.CreateDirectory(fileSystem.GetDirectoryName(filePath));
try
{
fileSystem.CopyFile(tempPath, filePath, false);
}
catch (IOException)
{
}
return tempPath;
}
}
}

View File

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

View File

@ -1,202 +0,0 @@
using ImageMagickSharp;
using MediaBrowser.Common.Configuration;
using System;
using System.Collections.Generic;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
namespace Emby.Drawing.ImageMagick
{
public class StripCollageBuilder
{
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
public StripCollageBuilder(IApplicationPaths appPaths, IFileSystem fileSystem)
{
_appPaths = appPaths;
_fileSystem = fileSystem;
}
public void BuildPosterCollage(string[] paths, string outputPath, int width, int height)
{
using (var wand = BuildPosterCollageWand(paths, width, height))
{
wand.SaveImage(outputPath);
}
}
public void BuildSquareCollage(string[] paths, string outputPath, int width, int height)
{
using (var wand = BuildSquareCollageWand(paths, width, height))
{
wand.SaveImage(outputPath);
}
}
public void BuildThumbCollage(string[] paths, string outputPath, int width, int height)
{
using (var wand = BuildThumbCollageWand(paths, width, height))
{
wand.SaveImage(outputPath);
}
}
private MagickWand BuildPosterCollageWand(string[] paths, int width, int height)
{
var inputPaths = ImageHelpers.ProjectPaths(paths, 3);
using (var wandImages = new MagickWand(inputPaths.ToArray()))
{
var wand = new MagickWand(width, height);
wand.OpenImage("gradient:#111111-#111111");
using (var draw = new DrawingWand())
{
var iSlice = Convert.ToInt32(width * 0.3);
int iTrans = Convert.ToInt32(height * .25);
int iHeight = Convert.ToInt32(height * .65);
var horizontalImagePadding = Convert.ToInt32(width * 0.0366);
foreach (var element in wandImages.ImageList)
{
using (var blackPixelWand = new PixelWand(ColorName.Black))
{
int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
element.Gravity = GravityType.CenterGravity;
element.BackgroundColor = blackPixelWand;
element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
int ix = (int)Math.Abs((iWidth - iSlice) / 2);
element.CropImage(iSlice, iHeight, ix, 0);
element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
}
}
wandImages.SetFirstIterator();
using (var wandList = wandImages.AppendImages())
{
wandList.CurrentImage.TrimImage(1);
using (var mwr = wandList.CloneMagickWand())
{
using (var blackPixelWand = new PixelWand(ColorName.Black))
{
using (var greyPixelWand = new PixelWand(ColorName.Grey70))
{
mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
mwr.CurrentImage.FlipImage();
mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
{
mwg.OpenImage("gradient:black-none");
var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
wandList.AddImage(mwr);
int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .05));
}
}
}
}
}
}
return wand;
}
}
private MagickWand BuildThumbCollageWand(string[] paths, int width, int height)
{
var inputPaths = ImageHelpers.ProjectPaths(paths, 4);
using (var wandImages = new MagickWand(inputPaths.ToArray()))
{
var wand = new MagickWand(width, height);
wand.OpenImage("gradient:#111111-#111111");
using (var draw = new DrawingWand())
{
var iSlice = Convert.ToInt32(width * 0.24125);
int iTrans = Convert.ToInt32(height * .25);
int iHeight = Convert.ToInt32(height * .70);
var horizontalImagePadding = Convert.ToInt32(width * 0.0125);
foreach (var element in wandImages.ImageList)
{
using (var blackPixelWand = new PixelWand(ColorName.Black))
{
int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
element.Gravity = GravityType.CenterGravity;
element.BackgroundColor = blackPixelWand;
element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
int ix = (int)Math.Abs((iWidth - iSlice) / 2);
element.CropImage(iSlice, iHeight, ix, 0);
element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
}
}
wandImages.SetFirstIterator();
using (var wandList = wandImages.AppendImages())
{
wandList.CurrentImage.TrimImage(1);
using (var mwr = wandList.CloneMagickWand())
{
using (var blackPixelWand = new PixelWand(ColorName.Black))
{
using (var greyPixelWand = new PixelWand(ColorName.Grey70))
{
mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
mwr.CurrentImage.FlipImage();
mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
{
mwg.OpenImage("gradient:black-none");
var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
wandList.AddImage(mwr);
int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .045));
}
}
}
}
}
}
return wand;
}
}
private MagickWand BuildSquareCollageWand(string[] paths, int width, int height)
{
var inputPaths = ImageHelpers.ProjectPaths(paths, 4);
var outputWand = new MagickWand(width, height, new PixelWand("none", 1));
var imageIndex = 0;
var cellWidth = width/2;
var cellHeight = height/2;
for (var x = 0; x < 2; x++)
{
for (var y = 0; y < 2; y++)
{
using (var temp = new MagickWand(inputPaths[imageIndex]))
{
temp.CurrentImage.ScaleImage(cellWidth, cellHeight);
// draw this image into the strip at the next position
var xPos = x*cellWidth;
var yPos = y*cellHeight;
outputWand.CurrentImage.CompositeImage(temp, CompositeOperator.OverCompositeOp, xPos, yPos);
}
imageIndex++;
}
}
return outputWand;
}
}
}

View File

@ -1,73 +0,0 @@
using ImageMagickSharp;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Drawing;
using System.Globalization;
using MediaBrowser.Model.IO;
namespace Emby.Drawing.ImageMagick
{
public class UnplayedCountIndicator
{
private const int OffsetFromTopRightCorner = 38;
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
public UnplayedCountIndicator(IApplicationPaths appPaths, IFileSystem fileSystem)
{
_appPaths = appPaths;
_fileSystem = fileSystem;
}
public void DrawUnplayedCountIndicator(MagickWand wand, ImageSize imageSize, int count)
{
var x = imageSize.Width - OffsetFromTopRightCorner;
var text = count.ToString(CultureInfo.InvariantCulture);
using (var draw = new DrawingWand())
{
using (PixelWand pixel = new PixelWand())
{
pixel.Color = "#52B54B";
pixel.Opacity = 0.2;
draw.FillColor = pixel;
draw.DrawCircle(x, OffsetFromTopRightCorner, x - 20, OffsetFromTopRightCorner - 20);
pixel.Opacity = 0;
pixel.Color = "white";
draw.FillColor = pixel;
draw.Font = PlayedIndicatorDrawer.ExtractFont("robotoregular.ttf", _appPaths, _fileSystem);
draw.FontStyle = FontStyleType.NormalStyle;
draw.TextAlignment = TextAlignType.CenterAlign;
draw.FontWeight = FontWeightType.RegularStyle;
draw.TextAntialias = true;
var fontSize = 30;
var y = OffsetFromTopRightCorner + 11;
if (text.Length == 1)
{
x += 1;
}
else if (text.Length == 2)
{
x += 1;
}
else if (text.Length >= 3)
{
//x += 1;
y -= 2;
fontSize = 24;
}
draw.FontSize = fontSize;
draw.DrawAnnotation(x, y, text);
draw.FillColor = pixel;
wand.CurrentImage.DrawImage(draw);
}
}
}
}
}

View File

@ -1,110 +0,0 @@
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
namespace Emby.Drawing.Net
{
public static class DynamicImageHelpers
{
public static void CreateThumbCollage(List<string> files,
IFileSystem fileSystem,
string file,
int width,
int height)
{
const int numStrips = 4;
files = ImageHelpers.ProjectPaths(files, numStrips);
const int rows = 1;
int cols = numStrips;
int cellWidth = 2 * (width / 3);
int cellHeight = height;
var index = 0;
using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
{
using (var graphics = Graphics.FromImage(img))
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
// SourceCopy causes the image to be blank in OSX
//graphics.CompositingMode = CompositingMode.SourceCopy;
for (var row = 0; row < rows; row++)
{
for (var col = 0; col < cols; col++)
{
var x = col * (cellWidth / 2);
var y = row * cellHeight;
if (files.Count > index)
{
using (var imgtemp = Image.FromFile(files[index]))
{
graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight);
}
}
index++;
}
}
img.Save(file);
}
}
}
public static void CreateSquareCollage(List<string> files,
IFileSystem fileSystem,
string file,
int width,
int height)
{
files = ImageHelpers.ProjectPaths(files, 4);
const int rows = 2;
const int cols = 2;
int singleSize = width / 2;
var index = 0;
using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
{
using (var graphics = Graphics.FromImage(img))
{
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
// SourceCopy causes the image to be blank in OSX
//graphics.CompositingMode = CompositingMode.SourceCopy;
for (var row = 0; row < rows; row++)
{
for (var col = 0; col < cols; col++)
{
var x = col * singleSize;
var y = row * singleSize;
using (var imgtemp = Image.FromFile(files[index]))
{
graphics.DrawImage(imgtemp, x, y, singleSize, singleSize);
}
index++;
}
}
img.Save(file);
}
}
}
}
}

View File

@ -1,17 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj" />
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj" />
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Include="empty.png" />
</ItemGroup>
</Project>

View File

@ -1,282 +0,0 @@
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Model.Drawing;
using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
using ImageFormat = MediaBrowser.Model.Drawing.ImageFormat;
using Emby.Drawing;
namespace Emby.Drawing.Net
{
public class GDIImageEncoder : IImageEncoder
{
private readonly IFileSystem _fileSystem;
private readonly ILogger _logger;
public GDIImageEncoder(IFileSystem fileSystem, ILogger logger)
{
_fileSystem = fileSystem;
_logger = logger;
LogInfo();
}
private void LogInfo()
{
_logger.LogInformation("GDIImageEncoder starting");
using (var stream = GetType().Assembly.GetManifestResourceStream(GetType().Namespace + ".empty.png"))
{
using (var img = Image.FromStream(stream))
{
}
}
_logger.LogInformation("GDIImageEncoder started");
}
public string[] SupportedInputFormats
{
get
{
return new[]
{
"png",
"jpeg",
"jpg",
"gif",
"bmp"
};
}
}
public ImageFormat[] SupportedOutputFormats
{
get
{
return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
}
}
public ImageSize GetImageSize(string path)
{
using (var image = Image.FromFile(path))
{
return new ImageSize
{
Width = image.Width,
Height = image.Height
};
}
}
private Image GetImage(string path, bool cropWhitespace)
{
if (cropWhitespace)
{
using (var originalImage = (Bitmap)Image.FromFile(path))
{
return originalImage.CropWhitespace();
}
}
return Image.FromFile(path);
}
public void EncodeImage(string inputPath, ImageSize? originalImageSize, string outputPath, bool autoOrient, int quality, ImageProcessingOptions options, ImageFormat selectedOutputFormat)
{
using (var originalImage = GetImage(inputPath, options.CropWhiteSpace))
{
if (options.CropWhiteSpace || !originalImageSize.HasValue)
{
originalImageSize = new ImageSize(originalImage.Width, originalImage.Height);
}
var newImageSize = ImageHelper.GetNewImageSize(options, originalImageSize);
var newWidth = Convert.ToInt32(Math.Round(newImageSize.Width));
var newHeight = Convert.ToInt32(Math.Round(newImageSize.Height));
// Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
// Also, Webp only supports Format32bppArgb and Format32bppRgb
var pixelFormat = selectedOutputFormat == ImageFormat.Webp
? PixelFormat.Format32bppArgb
: PixelFormat.Format32bppPArgb;
using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat))
{
// Mono throw an exeception if assign 0 to SetResolution
if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
{
// Preserve the original resolution
thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
}
using (var thumbnailGraph = Graphics.FromImage(thumbnail))
{
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
// SourceCopy causes the image to be blank in OSX
//thumbnailGraph.CompositingMode = !hasPostProcessing ?
// CompositingMode.SourceCopy :
// CompositingMode.SourceOver;
SetBackgroundColor(thumbnailGraph, options);
thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat);
// Save to the cache location
using (var cacheFileStream = _fileSystem.GetFileStream(outputPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, false))
{
// Save to the memory stream
thumbnail.Save(outputFormat, cacheFileStream, quality);
}
}
}
}
}
/// <summary>
/// Sets the color of the background.
/// </summary>
/// <param name="graphics">The graphics.</param>
/// <param name="options">The options.</param>
private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
{
var color = options.BackgroundColor;
if (!string.IsNullOrEmpty(color))
{
Color drawingColor;
try
{
drawingColor = ColorTranslator.FromHtml(color);
}
catch
{
drawingColor = ColorTranslator.FromHtml("#" + color);
}
graphics.Clear(drawingColor);
}
}
/// <summary>
/// Draws the indicator.
/// </summary>
/// <param name="graphics">The graphics.</param>
/// <param name="imageWidth">Width of the image.</param>
/// <param name="imageHeight">Height of the image.</param>
/// <param name="options">The options.</param>
private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
{
if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
{
return;
}
try
{
if (options.AddPlayedIndicator)
{
var currentImageSize = new Size(imageWidth, imageHeight);
new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize);
}
else if (options.UnplayedCount.HasValue)
{
var currentImageSize = new Size(imageWidth, imageHeight);
new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value);
}
if (options.PercentPlayed > 0)
{
var currentImageSize = new Size(imageWidth, imageHeight);
new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error drawing indicator overlay");
}
}
/// <summary>
/// Gets the output format.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="outputFormat">The output format.</param>
/// <returns>ImageFormat.</returns>
private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageFormat outputFormat)
{
switch (outputFormat)
{
case ImageFormat.Bmp:
return System.Drawing.Imaging.ImageFormat.Bmp;
case ImageFormat.Gif:
return System.Drawing.Imaging.ImageFormat.Gif;
case ImageFormat.Jpg:
return System.Drawing.Imaging.ImageFormat.Jpeg;
case ImageFormat.Png:
return System.Drawing.Imaging.ImageFormat.Png;
default:
return image.RawFormat;
}
}
public void CreateImageCollage(ImageCollageOptions options)
{
double ratio = options.Width;
ratio /= options.Height;
if (ratio >= 1.4)
{
DynamicImageHelpers.CreateThumbCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
}
else if (ratio >= .9)
{
DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
}
else
{
DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Width);
}
}
public void Dispose()
{
}
public string Name
{
get { return "GDI"; }
}
public bool SupportsImageCollageCreation
{
get { return true; }
}
public bool SupportsImageEncoding
{
get { return true; }
}
}
}

View File

@ -1,217 +0,0 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
namespace Emby.Drawing.Net
{
public static class ImageExtensions
{
/// <summary>
/// Saves the image.
/// </summary>
/// <param name="outputFormat">The output format.</param>
/// <param name="image">The image.</param>
/// <param name="toStream">To stream.</param>
/// <param name="quality">The quality.</param>
public static void Save(this Image image, ImageFormat outputFormat, Stream toStream, int quality)
{
// Use special save methods for jpeg and png that will result in a much higher quality image
// All other formats use the generic Image.Save
if (ImageFormat.Jpeg.Equals(outputFormat))
{
SaveAsJpeg(image, toStream, quality);
}
else if (ImageFormat.Png.Equals(outputFormat))
{
image.Save(toStream, ImageFormat.Png);
}
else
{
image.Save(toStream, outputFormat);
}
}
/// <summary>
/// Saves the JPEG.
/// </summary>
/// <param name="image">The image.</param>
/// <param name="target">The target.</param>
/// <param name="quality">The quality.</param>
public static void SaveAsJpeg(this Image image, Stream target, int quality)
{
using (var encoderParameters = new EncoderParameters(1))
{
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters);
}
}
private static readonly ImageCodecInfo[] Encoders = ImageCodecInfo.GetImageEncoders();
/// <summary>
/// Gets the image codec info.
/// </summary>
/// <param name="mimeType">Type of the MIME.</param>
/// <returns>ImageCodecInfo.</returns>
private static ImageCodecInfo GetImageCodecInfo(string mimeType)
{
foreach (var encoder in Encoders)
{
if (string.Equals(encoder.MimeType, mimeType, StringComparison.OrdinalIgnoreCase))
{
return encoder;
}
}
return Encoders.Length == 0 ? null : Encoders[0];
}
/// <summary>
/// Crops an image by removing whitespace and transparency from the edges
/// </summary>
/// <param name="bmp">The BMP.</param>
/// <returns>Bitmap.</returns>
/// <exception cref="System.Exception"></exception>
public static Bitmap CropWhitespace(this Bitmap bmp)
{
var width = bmp.Width;
var height = bmp.Height;
var topmost = 0;
for (int row = 0; row < height; ++row)
{
if (IsAllWhiteRow(bmp, row, width))
topmost = row;
else break;
}
int bottommost = 0;
for (int row = height - 1; row >= 0; --row)
{
if (IsAllWhiteRow(bmp, row, width))
bottommost = row;
else break;
}
int leftmost = 0, rightmost = 0;
for (int col = 0; col < width; ++col)
{
if (IsAllWhiteColumn(bmp, col, height))
leftmost = col;
else
break;
}
for (int col = width - 1; col >= 0; --col)
{
if (IsAllWhiteColumn(bmp, col, height))
rightmost = col;
else
break;
}
if (rightmost == 0) rightmost = width; // As reached left
if (bottommost == 0) bottommost = height; // As reached top.
var croppedWidth = rightmost - leftmost;
var croppedHeight = bottommost - topmost;
if (croppedWidth == 0) // No border on left or right
{
leftmost = 0;
croppedWidth = width;
}
if (croppedHeight == 0) // No border on top or bottom
{
topmost = 0;
croppedHeight = height;
}
// Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
var thumbnail = new Bitmap(croppedWidth, croppedHeight, PixelFormat.Format32bppPArgb);
// Preserve the original resolution
TrySetResolution(thumbnail, bmp.HorizontalResolution, bmp.VerticalResolution);
using (var thumbnailGraph = Graphics.FromImage(thumbnail))
{
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
thumbnailGraph.CompositingMode = CompositingMode.SourceCopy;
thumbnailGraph.DrawImage(bmp,
new RectangleF(0, 0, croppedWidth, croppedHeight),
new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
GraphicsUnit.Pixel);
}
return thumbnail;
}
/// <summary>
/// Tries the set resolution.
/// </summary>
/// <param name="bmp">The BMP.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
private static void TrySetResolution(Bitmap bmp, float x, float y)
{
if (x > 0 && y > 0)
{
bmp.SetResolution(x, y);
}
}
/// <summary>
/// Determines whether or not a row of pixels is all whitespace
/// </summary>
/// <param name="bmp">The BMP.</param>
/// <param name="row">The row.</param>
/// <param name="width">The width.</param>
/// <returns><c>true</c> if [is all white row] [the specified BMP]; otherwise, <c>false</c>.</returns>
private static bool IsAllWhiteRow(Bitmap bmp, int row, int width)
{
for (var i = 0; i < width; ++i)
{
if (!IsWhiteSpace(bmp.GetPixel(i, row)))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether or not a column of pixels is all whitespace
/// </summary>
/// <param name="bmp">The BMP.</param>
/// <param name="col">The col.</param>
/// <param name="height">The height.</param>
/// <returns><c>true</c> if [is all white column] [the specified BMP]; otherwise, <c>false</c>.</returns>
private static bool IsAllWhiteColumn(Bitmap bmp, int col, int height)
{
for (var i = 0; i < height; ++i)
{
if (!IsWhiteSpace(bmp.GetPixel(col, i)))
{
return false;
}
}
return true;
}
/// <summary>
/// Determines if a color is whitespace
/// </summary>
/// <param name="color">The color.</param>
/// <returns><c>true</c> if [is white space] [the specified color]; otherwise, <c>false</c>.</returns>
private static bool IsWhiteSpace(Color color)
{
return (color.R == 255 && color.G == 255 && color.B == 255) || color.A == 0;
}
}
}

View File

@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Emby.Drawing.Net
{
internal static class ImageHelpers
{
internal static List<string> ProjectPaths(List<string> paths, int count)
{
if (count <= 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (paths.Count == 0)
{
throw new ArgumentOutOfRangeException("paths");
}
var list = new List<string>();
AddToList(list, paths, count);
return list.Take(count).ToList();
}
private static void AddToList(List<string> list, List<string> paths, int count)
{
while (list.Count < count)
{
foreach (var path in paths)
{
list.Add(path);
if (list.Count >= count)
{
return;
}
}
}
}
}
}

View File

@ -1,34 +0,0 @@
using System;
using System.Drawing;
namespace Emby.Drawing.Net
{
public class PercentPlayedDrawer
{
private const int IndicatorHeight = 8;
public void Process(Graphics graphics, Size imageSize, double percent)
{
var y = imageSize.Height - IndicatorHeight;
using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 0, 0, 0)))
{
const int innerX = 0;
var innerY = y;
var innerWidth = imageSize.Width;
var innerHeight = imageSize.Height;
graphics.FillRectangle(backdroundBrush, innerX, innerY, innerWidth, innerHeight);
using (var foregroundBrush = new SolidBrush(Color.FromArgb(82, 181, 75)))
{
double foregroundWidth = innerWidth;
foregroundWidth *= percent;
foregroundWidth /= 100;
graphics.FillRectangle(foregroundBrush, innerX, innerY, Convert.ToInt32(Math.Round(foregroundWidth)), innerHeight);
}
}
}
}
}

View File

@ -1,32 +0,0 @@
using System.Drawing;
namespace Emby.Drawing.Net
{
public class PlayedIndicatorDrawer
{
private const int IndicatorHeight = 40;
public const int IndicatorWidth = 40;
private const int FontSize = 40;
private const int OffsetFromTopRightCorner = 10;
public void DrawPlayedIndicator(Graphics graphics, Size imageSize)
{
var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75)))
{
graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight);
x = imageSize.Width - 45 - OffsetFromTopRightCorner;
using (var font = new Font("Webdings", FontSize, FontStyle.Regular, GraphicsUnit.Pixel))
{
using (var fontBrush = new SolidBrush(Color.White))
{
graphics.DrawString("a", font, fontBrush, x, OffsetFromTopRightCorner - 2);
}
}
}
}
}
}

View File

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

View File

@ -1,50 +0,0 @@
using System.Drawing;
namespace Emby.Drawing.Net
{
public class UnplayedCountIndicator
{
private const int IndicatorHeight = 41;
public const int IndicatorWidth = 41;
private const int OffsetFromTopRightCorner = 10;
public void DrawUnplayedCountIndicator(Graphics graphics, Size imageSize, int count)
{
var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75)))
{
graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight);
var text = count.ToString();
x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
var y = OffsetFromTopRightCorner + 6;
var fontSize = 24;
if (text.Length == 1)
{
x += 10;
}
else if (text.Length == 2)
{
x += 3;
}
else if (text.Length == 3)
{
x += 1;
y += 1;
fontSize = 20;
}
using (var font = new Font("Sans-Serif", fontSize, FontStyle.Regular, GraphicsUnit.Pixel))
{
using (var fontBrush = new SolidBrush(Color.White))
{
graphics.DrawString(text, font, fontBrush, x, y);
}
}
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 B

View File

@ -548,9 +548,7 @@ namespace Emby.Drawing.Skia
using (var resizedBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
{
// scale image
var resizeMethod = SKBitmapResizeMethod.Lanczos3;
bitmap.Resize(resizedBitmap, resizeMethod);
bitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
// If all we're doing is resizing then we can stop now
if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
@ -558,10 +556,13 @@ namespace Emby.Drawing.Skia
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
using (var outputStream = new SKFileWStream(outputPath))
{
resizedBitmap.Encode(outputStream, skiaOutputFormat, quality);
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()))
{
pixmap.Encode(outputStream, skiaOutputFormat, quality);
return outputPath;
}
}
}
// create bitmap to use for canvas drawing used to draw into bitmap
using (var saveBitmap = new SKBitmap(width, height))//, bitmap.ColorType, bitmap.AlphaType))
@ -593,8 +594,7 @@ namespace Emby.Drawing.Skia
// If foreground layer present then draw
if (hasForegroundColor)
{
Double opacity;
if (!Double.TryParse(options.ForegroundLayer, out opacity))
if (!Double.TryParse(options.ForegroundLayer, out double opacity))
{
opacity = .4;
}
@ -610,7 +610,10 @@ namespace Emby.Drawing.Skia
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
using (var outputStream = new SKFileWStream(outputPath))
{
saveBitmap.Encode(outputStream, skiaOutputFormat, quality);
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), saveBitmap.GetPixels()))
{
pixmap.Encode(outputStream, skiaOutputFormat, quality);
}
}
}
}

View File

@ -49,7 +49,10 @@ namespace Emby.Drawing.Skia
{
using (var outputStream = new SKFileWStream(outputPath))
{
bitmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
{
pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
}
}
}
}
@ -60,7 +63,10 @@ namespace Emby.Drawing.Skia
{
using (var outputStream = new SKFileWStream(outputPath))
{
bitmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
using (var pixmap = new SKPixmap(new SKImageInfo(width, height), bitmap.GetPixels()))
{
pixmap.Encode(outputStream, GetEncodedFormat(outputPath), 90);
}
}
}
}
@ -83,9 +89,8 @@ namespace Emby.Drawing.Skia
for (int i = 0; i < 4; i++)
{
int newIndex;
using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex))
using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex))
{
imageIndex = newIndex;
@ -98,7 +103,7 @@ namespace Emby.Drawing.Skia
int iWidth = (int)Math.Abs(iHeight * currentBitmap.Width / currentBitmap.Height);
using (var resizeBitmap = new SKBitmap(iWidth, iHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
{
currentBitmap.Resize(resizeBitmap, SKBitmapResizeMethod.Lanczos3);
currentBitmap.ScalePixels(resizeBitmap, SKFilterQuality.High);
// crop image
int ix = (int)Math.Abs((iWidth - iSlice) / 2);
using (var image = SKImage.FromBitmap(resizeBitmap))
@ -116,7 +121,7 @@ namespace Emby.Drawing.Skia
using (var reflectionBitmap = new SKBitmap(croppedBitmap.Width, croppedBitmap.Height / 2, croppedBitmap.ColorType, croppedBitmap.AlphaType))
{
// resize to half height
croppedBitmap.Resize(reflectionBitmap, SKBitmapResizeMethod.Lanczos3);
currentBitmap.ScalePixels(reflectionBitmap, SKFilterQuality.High);
using (var flippedBitmap = new SKBitmap(reflectionBitmap.Width, reflectionBitmap.Height, reflectionBitmap.ColorType, reflectionBitmap.AlphaType))
using (var flippedCanvas = new SKCanvas(flippedBitmap))
@ -164,8 +169,7 @@ namespace Emby.Drawing.Skia
currentIndex = 0;
}
SKEncodedOrigin origin;
bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out origin);
bitmap = SkiaEncoder.Decode(paths[currentIndex], false, _fileSystem, null, out SKEncodedOrigin origin);
imagesTested[currentIndex] = 0;
@ -194,9 +198,8 @@ namespace Emby.Drawing.Skia
{
for (var y = 0; y < 2; y++)
{
int newIndex;
using (var currentBitmap = GetNextValidImage(paths, imageIndex, out newIndex))
using (var currentBitmap = GetNextValidImage(paths, imageIndex, out int newIndex))
{
imageIndex = newIndex;
@ -208,7 +211,7 @@ namespace Emby.Drawing.Skia
using (var resizedBitmap = new SKBitmap(cellWidth, cellHeight, currentBitmap.ColorType, currentBitmap.AlphaType))
{
// scale image
currentBitmap.Resize(resizedBitmap, SKBitmapResizeMethod.Lanczos3);
currentBitmap.ScalePixels(resizedBitmap, SKFilterQuality.High);
// draw this image into the strip at the next position
var xPos = x * cellWidth;

View File

@ -1,5 +1,4 @@
using MediaBrowser.Common.Events;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Events;
using Microsoft.Extensions.Logging;
@ -30,7 +29,7 @@ namespace Emby.Server.Implementations.Activity
_repo.Create(entry);
EventHelper.FireEventIfNotNull(EntryCreated, this, new GenericEventArgs<ActivityLogEntry>(entry), _logger);
EntryCreated?.Invoke(this, new GenericEventArgs<ActivityLogEntry>(entry));
}
public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, bool? hasUserId, int? startIndex, int? limit)

View File

@ -1,5 +1,4 @@
using System;
using System.IO;
using System.IO;
using MediaBrowser.Common.Configuration;
namespace Emby.Server.Implementations.AppBase
@ -13,10 +12,11 @@ namespace Emby.Server.Implementations.AppBase
/// <summary>
/// Initializes a new instance of the <see cref="BaseApplicationPaths"/> class.
/// </summary>
protected BaseApplicationPaths(string programDataPath, string appFolderPath)
protected BaseApplicationPaths(string programDataPath, string appFolderPath, string logDirectoryPath)
{
ProgramDataPath = programDataPath;
ProgramSystemPath = appFolderPath;
LogDirectoryPath = logDirectoryPath;
}
public string ProgramDataPath { get; private set; }
@ -106,6 +106,11 @@ namespace Emby.Server.Implementations.AppBase
}
}
/// <summary>
/// The _log directory
/// </summary>
private string _logDirectoryPath;
/// <summary>
/// Gets the path to the log directory
/// </summary>
@ -114,7 +119,18 @@ namespace Emby.Server.Implementations.AppBase
{
get
{
return Path.Combine(ProgramDataPath, "logs");
if (string.IsNullOrEmpty(_logDirectoryPath))
{
_logDirectoryPath = Path.Combine(ProgramDataPath, "logs");
Directory.CreateDirectory(_logDirectoryPath);
}
return _logDirectoryPath;
}
set
{
_logDirectoryPath = value;
}
}

View File

@ -283,12 +283,11 @@ namespace Emby.Server.Implementations.AppBase
validatingStore.Validate(currentConfiguration, configuration);
}
EventHelper.FireEventIfNotNull(NamedConfigurationUpdating, this, new ConfigurationUpdateEventArgs
NamedConfigurationUpdating?.Invoke( this, new ConfigurationUpdateEventArgs
{
Key = key,
NewConfiguration = configuration
}, Logger);
});
_configurations.AddOrUpdate(key, configuration, (k, v) => configuration);
@ -305,12 +304,11 @@ namespace Emby.Server.Implementations.AppBase
protected virtual void OnNamedConfigurationUpdated(string key, object configuration)
{
EventHelper.FireEventIfNotNull(NamedConfigurationUpdated, this, new ConfigurationUpdateEventArgs
NamedConfigurationUpdated?.Invoke(this, new ConfigurationUpdateEventArgs
{
Key = key,
NewConfiguration = configuration
}, Logger);
});
}
public Type GetConfigurationType(string key)

View File

@ -368,7 +368,6 @@ namespace Emby.Server.Implementations
protected IAuthService AuthService { get; private set; }
public StartupOptions StartupOptions { get; private set; }
protected readonly string ReleaseAssetFilename;
internal IPowerManagement PowerManagement { get; private set; }
internal IImageEncoder ImageEncoder { get; private set; }
@ -393,7 +392,6 @@ namespace Emby.Server.Implementations
StartupOptions options,
IFileSystem fileSystem,
IPowerManagement powerManagement,
string releaseAssetFilename,
IEnvironmentInfo environmentInfo,
IImageEncoder imageEncoder,
ISystemEvents systemEvents,
@ -416,17 +414,13 @@ namespace Emby.Server.Implementations
ConfigurationManager = GetConfigurationManager();
// Initialize this early in case the -v command line option is used
Logger = LoggerFactory.CreateLogger("App");
StartupOptions = options;
ReleaseAssetFilename = releaseAssetFilename;
PowerManagement = powerManagement;
ImageEncoder = imageEncoder;
//SetBaseExceptionMessage();
fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
NetworkManager.NetworkChanged += NetworkManager_NetworkChanged;
@ -467,7 +461,7 @@ namespace Emby.Server.Implementations
{
get
{
return _version ?? (_version = GetType().GetTypeInfo().Assembly.GetName().Version);
return _version ?? (_version = typeof(ApplicationHost).Assembly.GetName().Version);
}
}
@ -644,15 +638,14 @@ namespace Emby.Server.Implementations
/// Gets the exports.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="manageLiftime">if set to <c>true</c> [manage liftime].</param>
/// <param name="manageLifetime">if set to <c>true</c> [manage lifetime].</param>
/// <returns>IEnumerable{``0}.</returns>
public IEnumerable<T> GetExports<T>(bool manageLifetime = true)
{
var parts = GetExportTypes<T>()
.Select(CreateInstanceSafe)
.Where(i => i != null)
.Cast<T>()
.ToList();
.Cast<T>();
if (manageLifetime)
{
@ -692,22 +685,10 @@ namespace Emby.Server.Implementations
return parts;
}
// TODO: @bond
/*
private void SetBaseExceptionMessage()
{
var builder = GetBaseExceptionMessage(ApplicationPaths);
builder.Insert(0, string.Format("Version: {0}{1}", ApplicationVersion, Environment.NewLine));
builder.Insert(0, "*** Error Report ***" + Environment.NewLine);
LoggerFactory.ExceptionMessagePrefix = builder.ToString();
}*/
/// <summary>
/// Runs the startup tasks.
/// </summary>
public async Task RunStartupTasks()
public Task RunStartupTasks()
{
Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
@ -739,7 +720,7 @@ namespace Emby.Server.Implementations
RunEntryPoints(entryPoints, false);
Logger.LogInformation("All entry points have started");
//LoggerFactory.RemoveConsoleOutput();
return Task.CompletedTask;
}
private void RunEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
@ -752,7 +733,7 @@ namespace Emby.Server.Implementations
}
var name = entryPoint.GetType().FullName;
Logger.LogInformation("Starting entry point {0}", name);
Logger.LogInformation("Starting entry point {Name}", name);
var now = DateTime.UtcNow;
try
{
@ -760,9 +741,9 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
Logger.LogError(ex, "Error in {name}", name);
Logger.LogError(ex, "Error while running entrypoint {Name}", name);
}
Logger.LogInformation("Entry point completed: {0}. Duration: {1} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos");
Logger.LogInformation("Entry point completed: {Name}. Duration: {Duration} seconds", name, (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture), "ImageInfos");
}
}
@ -800,27 +781,6 @@ namespace Emby.Server.Implementations
JsonSerializer = CreateJsonSerializer();
OnLoggerLoaded(true);
//LoggerFactory.LoggerLoaded += (s, e) => OnLoggerLoaded(false);
DiscoverTypes();
SetHttpLimit();
RegisterResources();
FindParts();
}
protected virtual void OnLoggerLoaded(bool isFirstLoad)
{
Logger.LogInformation("Application version: {0}", ApplicationVersion);
if (!isFirstLoad)
{
LogEnvironmentInfo(Logger, ApplicationPaths, false);
}
if (Plugins != null)
{
var pluginBuilder = new StringBuilder();
@ -832,6 +792,14 @@ namespace Emby.Server.Implementations
Logger.LogInformation("Plugins: {plugins}", pluginBuilder.ToString());
}
DiscoverTypes();
SetHttpLimit();
RegisterResources();
FindParts();
}
protected virtual IHttpClient CreateHttpClient()
@ -982,9 +950,6 @@ namespace Emby.Server.Implementations
DeviceManager = new DeviceManager(AuthenticationRepository, JsonSerializer, LibraryManager, LocalizationManager, UserManager, FileSystemManager, LibraryMonitor, ServerConfigurationManager, LoggerFactory.CreateLogger("DeviceManager"), NetworkManager);
RegisterSingleInstance(DeviceManager);
var newsService = new Emby.Server.Implementations.News.NewsService(ApplicationPaths, JsonSerializer);
RegisterSingleInstance<INewsService>(newsService);
MediaSourceManager = new MediaSourceManager(ItemRepository, ApplicationPaths, LocalizationManager, UserManager, LibraryManager, LoggerFactory.CreateLogger("MediaSourceManager"), JsonSerializer, FileSystemManager, UserDataManager, TimerFactory, () => MediaEncoder);
RegisterSingleInstance(MediaSourceManager);
@ -1074,36 +1039,25 @@ namespace Emby.Server.Implementations
{
get
{
return "netframework";
return "netcore";
}
}
public static void LogEnvironmentInfo(ILogger Logger, IApplicationPaths appPaths, bool isStartup)
public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths, EnvironmentInfo.EnvironmentInfo environmentInfo)
{
Logger.LogInformation("Jellyfin:\n{ex}", GetBaseExceptionMessage(appPaths).ToString());
}
protected static StringBuilder GetBaseExceptionMessage(IApplicationPaths appPaths)
{
var builder = new StringBuilder();
// Distinct these to prevent users from reporting problems that aren't actually problems
var commandLineArgs = Environment
.GetCommandLineArgs()
.Distinct()
.ToArray();
.Distinct();
builder.AppendLine(string.Format("Command line: {0}", string.Join(" ", commandLineArgs)));
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));
builder.AppendLine(string.Format("User Interactive: {0}", Environment.UserInteractive));
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;
logger.LogInformation("Arguments: {Args}", commandLineArgs);
logger.LogInformation("Operating system: {OS} {OSVersion}", environmentInfo.OperatingSystemName, environmentInfo.OperatingSystemVersion);
logger.LogInformation("Architecture: {Architecture}", environmentInfo.SystemArchitecture);
logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
}
private void SetHttpLimit()
@ -1174,7 +1128,7 @@ namespace Emby.Server.Implementations
//localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
if (!localCert.HasPrivateKey)
{
Logger.LogError("No private key included in SSL cert {0}.", certificateLocation);
Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
return null;
}
@ -1182,7 +1136,7 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
Logger.LogError(ex, "Error loading cert from {certificateLocation}", certificateLocation);
Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
return null;
}
}
@ -1265,7 +1219,7 @@ namespace Emby.Server.Implementations
HttpClient,
ZipClient,
ProcessFactory,
5000, false,
5000,
EnvironmentInfo);
MediaEncoder = mediaEncoder;
@ -1340,7 +1294,6 @@ namespace Emby.Server.Implementations
{
if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
{
RegisterServerWithAdministratorAccess();
ServerConfigurationManager.Configuration.IsPortAuthorized = true;
ConfigurationManager.SaveConfiguration();
}
@ -1411,12 +1364,11 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
Logger.LogError(ex, "Error getting plugin Id from {pluginName}.", plugin.GetType().FullName);
Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
}
}
var hasPluginConfiguration = plugin as IHasPluginConfiguration;
if (hasPluginConfiguration != null)
if (plugin is IHasPluginConfiguration hasPluginConfiguration)
{
hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
}
@ -1772,7 +1724,7 @@ namespace Emby.Server.Implementations
return list.ToList();
}
protected abstract List<Assembly> GetAssembliesWithPartsInternal();
protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
/// <summary>
/// Gets the plugin assemblies.
@ -1835,13 +1787,13 @@ namespace Emby.Server.Implementations
{
var result = Version.Parse(FileVersionInfo.GetVersionInfo(path).FileVersion);
Logger.LogInformation("File {0} has version {1}", path, result);
Logger.LogInformation("File {Path} has version {Version}", path, result);
return result;
}
catch (Exception ex)
{
Logger.LogError(ex, "Error getting version number from {path}", path);
Logger.LogError(ex, "Error getting version number from {Path}", path);
return new Version(1, 0);
}
@ -2255,32 +2207,6 @@ namespace Emby.Server.Implementations
protected abstract void ShutdownInternal();
/// <summary>
/// Registers the server with administrator access.
/// </summary>
private void RegisterServerWithAdministratorAccess()
{
Logger.LogInformation("Requesting administrative access to authorize http server");
try
{
AuthorizeServer();
}
catch (NotImplementedException)
{
}
catch (Exception ex)
{
Logger.LogError(ex, "Error authorizing server");
}
}
protected virtual void AuthorizeServer()
{
throw new NotImplementedException();
}
public event EventHandler HasUpdateAvailableChanged;
private bool _hasUpdateAvailable;
@ -2295,7 +2221,7 @@ namespace Emby.Server.Implementations
if (fireEvent)
{
EventHelper.FireEventIfNotNull(HasUpdateAvailableChanged, this, EventArgs.Empty, Logger);
HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
}
}
}
@ -2311,56 +2237,6 @@ namespace Emby.Server.Implementations
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 async Task<CheckForUpdateResult> CheckForApplicationUpdate(CancellationToken cancellationToken, IProgress<double> progress)
{
var updateLevel = SystemUpdateLevel;
var cacheLength = updateLevel == PackageVersionClass.Release ?
TimeSpan.FromHours(12) :
TimeSpan.FromMinutes(5);
try
{
var result = await new GithubUpdater(HttpClient, JsonSerializer).CheckForUpdateResult("MediaBrowser",
"Emby.Releases",
ApplicationVersion,
updateLevel,
ReleaseAssetFilename,
"MBServer",
UpdateTargetFileName,
cacheLength,
cancellationToken).ConfigureAwait(false);
HasUpdateAvailable = result.IsUpdateAvailable;
return result;
}
catch (HttpException ex)
{
// users are overreacting to this occasionally failing
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.Forbidden)
{
HasUpdateAvailable = false;
return new CheckForUpdateResult
{
IsUpdateAvailable = false
};
}
throw;
}
}
protected virtual string UpdateTargetFileName
{
get { return "Mbserver.zip"; }
}
/// <summary>
/// Updates the application.
/// </summary>
@ -2461,11 +2337,10 @@ namespace Emby.Server.Implementations
{
Logger.LogInformation("Application has been updated to version {0}", package.versionStr);
EventHelper.FireEventIfNotNull(ApplicationUpdated, this, new GenericEventArgs<PackageVersionInfo>
ApplicationUpdated?.Invoke(this, new GenericEventArgs<PackageVersionInfo>
{
Argument = package
}, Logger);
});
NotifyPendingRestart();
}
@ -2494,15 +2369,14 @@ namespace Emby.Server.Implementations
{
var type = GetType();
//LoggerFactory.AddConsoleOutput();
Logger.LogInformation("Disposing " + type.Name);
Logger.LogInformation("Disposing {Type}", type.Name);
var parts = DisposableParts.Distinct().Where(i => i.GetType() != type).ToList();
DisposableParts.Clear();
foreach (var part in parts)
{
Logger.LogInformation("Disposing " + part.GetType().Name);
Logger.LogInformation("Disposing {Type}", part.GetType().Name);
try
{
@ -2510,58 +2384,11 @@ namespace Emby.Server.Implementations
}
catch (Exception ex)
{
Logger.LogError(ex, "Error disposing {0}", part.GetType().Name);
Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
}
}
}
}
private Dictionary<string, string> _values;
public string GetValue(string name)
{
if (_values == null)
{
_values = LoadValues();
}
string value;
if (_values.TryGetValue(name, out value))
{
return value;
}
return null;
}
// TODO: @bond Remove?
private Dictionary<string, string> LoadValues()
{
Dictionary<string, string> values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
using (var stream = typeof(ApplicationHost).Assembly.GetManifestResourceStream(typeof(ApplicationHost).Namespace + ".values.txt"))
{
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrEmpty(line))
{
continue;
}
var index = line.IndexOf('=');
if (index != -1)
{
values[line.Substring(0, index)] = line.Substring(index + 1);
}
}
}
}
return values;
}
}
internal class CertificateInfo

View File

@ -901,7 +901,7 @@ namespace Emby.Server.Implementations.Channels
private T GetItemById<T>(string idString, string channelName, out bool isNew)
where T : BaseItem, new()
{
var id = GetIdToHash(idString, channelName).GetMBId(typeof(T));
var id = _libraryManager.GetNewItemId(GetIdToHash(idString, channelName), typeof(T));
T item = null;

View File

@ -155,12 +155,11 @@ namespace Emby.Server.Implementations.Collections
_providerManager.QueueRefresh(collection.Id, new MetadataRefreshOptions(new DirectoryService(_logger, _fileSystem)), RefreshPriority.High);
}
EventHelper.FireEventIfNotNull(CollectionCreated, this, new CollectionCreatedEventArgs
CollectionCreated?.Invoke(this, new CollectionCreatedEventArgs
{
Collection = collection,
Options = options
}, _logger);
});
return collection;
}
@ -230,12 +229,11 @@ namespace Emby.Server.Implementations.Collections
if (fireEvent)
{
EventHelper.FireEventIfNotNull(ItemsAddedToCollection, this, new CollectionModifiedEventArgs
ItemsAddedToCollection?.Invoke(this, new CollectionModifiedEventArgs
{
Collection = collection,
ItemsChanged = itemList
}, _logger);
});
}
}
}
@ -288,12 +286,11 @@ namespace Emby.Server.Implementations.Collections
ForceSave = true
}, RefreshPriority.High);
EventHelper.FireEventIfNotNull(ItemsRemovedFromCollection, this, new CollectionModifiedEventArgs
ItemsRemovedFromCollection?.Invoke(this, new CollectionModifiedEventArgs
{
Collection = collection,
ItemsChanged = itemList
}, _logger);
});
}
public IEnumerable<BaseItem> CollapseItemsWithinBoxSets(IEnumerable<BaseItem> items, User user)

View File

@ -1,22 +1,15 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Emby.Server.Implementations.AppBase;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.IO;
using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.Configuration
{
@ -143,7 +136,7 @@ namespace Emby.Server.Implementations.Configuration
ValidateMetadataPath(newConfig);
ValidateSslCertificate(newConfig);
EventHelper.FireEventIfNotNull(ConfigurationUpdating, this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig }, Logger);
ConfigurationUpdating?.Invoke(this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig });
base.ReplaceConfiguration(newConfiguration);
}

View File

@ -1,5 +1,4 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Library;
@ -146,6 +145,7 @@ namespace Emby.Server.Implementations.Devices
}).Items;
// TODO: DeviceQuery doesn't seem to be used from client. Not even Swagger.
if (query.SupportsSync.HasValue)
{
var val = query.SupportsSync.Value;
@ -253,14 +253,14 @@ namespace Emby.Server.Implementations.Devices
if (CameraImageUploaded != null)
{
EventHelper.FireEventIfNotNull(CameraImageUploaded, this, new GenericEventArgs<CameraImageUploadInfo>
CameraImageUploaded?.Invoke(this, new GenericEventArgs<CameraImageUploadInfo>
{
Argument = new CameraImageUploadInfo
{
Device = device,
FileInfo = file
}
}, _logger);
});
}
}

View File

@ -1,131 +0,0 @@
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Extensions;
namespace Emby.Server.Implementations.EntryPoints
{
/// <summary>
/// Class UsageEntryPoint
/// </summary>
public class UsageEntryPoint : IServerEntryPoint
{
private readonly IServerApplicationHost _applicationHost;
private readonly IHttpClient _httpClient;
private readonly ILogger _logger;
private readonly ISessionManager _sessionManager;
private readonly IUserManager _userManager;
private readonly IServerConfigurationManager _config;
private readonly ConcurrentDictionary<Guid, ClientInfo> _apps = new ConcurrentDictionary<Guid, ClientInfo>();
public UsageEntryPoint(ILogger logger, IServerApplicationHost applicationHost, IHttpClient httpClient, ISessionManager sessionManager, IUserManager userManager, IServerConfigurationManager config)
{
_logger = logger;
_applicationHost = applicationHost;
_httpClient = httpClient;
_sessionManager = sessionManager;
_userManager = userManager;
_config = config;
_sessionManager.SessionStarted += _sessionManager_SessionStarted;
}
void _sessionManager_SessionStarted(object sender, SessionEventArgs e)
{
var session = e.SessionInfo;
if (!string.IsNullOrEmpty(session.Client) &&
!string.IsNullOrEmpty(session.DeviceName) &&
!string.IsNullOrEmpty(session.DeviceId) &&
!string.IsNullOrEmpty(session.ApplicationVersion))
{
var keys = new List<string>
{
session.Client,
session.DeviceName,
session.DeviceId,
session.ApplicationVersion
};
var key = string.Join("_", keys.ToArray()).GetMD5();
ClientInfo info;
if (!_apps.TryGetValue(key, out info))
{
info = new ClientInfo
{
AppName = session.Client,
AppVersion = session.ApplicationVersion,
DeviceName = session.DeviceName,
DeviceId = session.DeviceId
};
_apps[key] = info;
if (_config.Configuration.EnableAnonymousUsageReporting)
{
Task.Run(() => ReportNewSession(info));
}
}
}
}
private async Task ReportNewSession(ClientInfo client)
{
try
{
await new UsageReporter(_applicationHost, _httpClient, _logger)
.ReportAppUsage(client, CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending anonymous usage statistics.");
}
}
public async void Run()
{
await Task.Delay(5000).ConfigureAwait(false);
OnTimerFired();
}
/// <summary>
/// Called when [timer fired].
/// </summary>
private async void OnTimerFired()
{
if (!_config.Configuration.EnableAnonymousUsageReporting)
{
return;
}
try
{
await new UsageReporter(_applicationHost, _httpClient, _logger)
.ReportServerUsage(CancellationToken.None)
.ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending anonymous usage statistics.");
}
}
public void Dispose()
{
_sessionManager.SessionStarted -= _sessionManager_SessionStarted;
}
}
}

View File

@ -1,130 +0,0 @@
using MediaBrowser.Common;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Connect;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
public class UsageReporter
{
private readonly IServerApplicationHost _applicationHost;
private readonly IHttpClient _httpClient;
private readonly ILogger _logger;
private const string MbAdminUrl = "https://www.mb3admin.local/admin/";
public UsageReporter(IServerApplicationHost applicationHost, IHttpClient httpClient, ILogger logger)
{
_applicationHost = applicationHost;
_httpClient = httpClient;
_logger = logger;
}
public async Task ReportServerUsage(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var data = new Dictionary<string, string>
{
{ "feature", _applicationHost.Name },
{ "mac", _applicationHost.SystemId },
{ "serverid", _applicationHost.SystemId },
{ "deviceid", _applicationHost.SystemId },
{ "ver", _applicationHost.ApplicationVersion.ToString() },
{ "platform", _applicationHost.OperatingSystemDisplayName }
};
data["plugins"] = string.Join(",", _applicationHost.Plugins.Select(i => i.Id).ToArray());
var logErrors = false;
#if DEBUG
logErrors = true;
#endif
var options = new HttpRequestOptions
{
Url = MbAdminUrl + "service/registration/ping",
CancellationToken = cancellationToken,
// Seeing block length errors
EnableHttpCompression = false,
LogRequest = false,
LogErrors = logErrors,
BufferContent = false
};
options.SetPostData(data);
using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
{
}
}
public async Task ReportAppUsage(ClientInfo app, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(app.DeviceId))
{
throw new ArgumentException("Client info must have a device Id");
}
_logger.LogInformation("App Activity: app: {0}, version: {1}, deviceId: {2}, deviceName: {3}",
app.AppName ?? "Unknown App",
app.AppVersion ?? "Unknown",
app.DeviceId,
app.DeviceName ?? "Unknown");
cancellationToken.ThrowIfCancellationRequested();
var data = new Dictionary<string, string>
{
{ "feature", app.AppName ?? "Unknown App" },
{ "serverid", _applicationHost.SystemId },
{ "deviceid", app.DeviceId },
{ "mac", app.DeviceId },
{ "ver", app.AppVersion ?? "Unknown" },
{ "platform", app.DeviceName },
};
var logErrors = false;
#if DEBUG
logErrors = true;
#endif
var options = new HttpRequestOptions
{
Url = MbAdminUrl + "service/registration/ping",
CancellationToken = cancellationToken,
// Seeing block length errors
EnableHttpCompression = false,
LogRequest = false,
LogErrors = logErrors,
BufferContent = false
};
options.SetPostData(data);
using (var response = await _httpClient.SendAsync(options, "POST").ConfigureAwait(false))
{
}
}
}
public class ClientInfo
{
public string AppName { get; set; }
public string AppVersion { get; set; }
public string DeviceName { get; set; }
public string DeviceId { get; set; }
}
}

View File

@ -1,46 +1,33 @@
using System;
using System.IO;
using MediaBrowser.Model.System;
using System.Runtime.InteropServices;
namespace Emby.Server.Implementations.EnvironmentInfo
{
// TODO: Rework @bond
public class EnvironmentInfo : IEnvironmentInfo
{
private Architecture? _customArchitecture;
private MediaBrowser.Model.System.OperatingSystem? _customOperatingSystem;
public virtual MediaBrowser.Model.System.OperatingSystem OperatingSystem
public EnvironmentInfo(MediaBrowser.Model.System.OperatingSystem operatingSystem)
{
get
{
if (_customOperatingSystem.HasValue)
{
return _customOperatingSystem.Value;
OperatingSystem = operatingSystem;
}
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;
}
set
{
_customOperatingSystem = value;
}
}
public MediaBrowser.Model.System.OperatingSystem OperatingSystem { get; private set; }
public string OperatingSystemName
{
get
{
return Environment.OSVersion.Platform.ToString();
switch (OperatingSystem)
{
case MediaBrowser.Model.System.OperatingSystem.Android: return "Android";
case MediaBrowser.Model.System.OperatingSystem.BSD: return "BSD";
case MediaBrowser.Model.System.OperatingSystem.Linux: return "Linux";
case MediaBrowser.Model.System.OperatingSystem.OSX: return "macOS";
case MediaBrowser.Model.System.OperatingSystem.Windows: return "Windows";
default: throw new Exception($"Unknown OS {OperatingSystem}");
}
}
}
@ -60,22 +47,7 @@ namespace Emby.Server.Implementations.EnvironmentInfo
}
}
public Architecture SystemArchitecture
{
get
{
if (_customArchitecture.HasValue)
{
return _customArchitecture.Value;
}
return Environment.Is64BitOperatingSystem ? MediaBrowser.Model.System.Architecture.X64 : MediaBrowser.Model.System.Architecture.X86;
}
set
{
_customArchitecture = value;
}
}
public Architecture SystemArchitecture { get { return RuntimeInformation.OSArchitecture; } }
public string GetEnvironmentVariable(string name)
{

View File

@ -5,18 +5,16 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.Cache;
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 Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
using MediaBrowser.Controller.IO;
namespace Emby.Server.Implementations.HttpClientManager
{
@ -125,59 +123,38 @@ namespace Emby.Server.Implementations.HttpClientManager
private WebRequest GetRequest(HttpRequestOptions options, string method)
{
var url = options.Url;
string url = options.Url;
var uriAddress = new Uri(url);
var userInfo = uriAddress.UserInfo;
Uri uriAddress = new Uri(url);
string userInfo = uriAddress.UserInfo;
if (!string.IsNullOrWhiteSpace(userInfo))
{
_logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url);
url = url.Replace(userInfo + "@", string.Empty);
}
var request = CreateWebRequest(url);
var httpWebRequest = request as HttpWebRequest;
WebRequest request = CreateWebRequest(url);
if (httpWebRequest != null)
if (request is HttpWebRequest httpWebRequest)
{
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;
if (options.DecompressionMethod.HasValue
&& options.DecompressionMethod.Value == CompressionMethod.Gzip)
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
}
}
else
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
}
}
httpWebRequest.KeepAlive = options.EnableKeepAlive;
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;
@ -189,6 +166,11 @@ namespace Emby.Server.Implementations.HttpClientManager
}
}
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
request.Method = method;
request.Timeout = options.TimeoutMs;
if (!string.IsNullOrWhiteSpace(userInfo))
{
var parts = userInfo.Split(':');
@ -215,7 +197,7 @@ namespace Emby.Server.Implementations.HttpClientManager
{
var hasUserAgent = false;
foreach (var header in options.RequestHeaders.ToList())
foreach (var header in options.RequestHeaders)
{
if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
{
@ -379,10 +361,7 @@ namespace Emby.Server.Implementations.HttpClientManager
{
try
{
// TODO: We can always put this in the options object if needed
var requestEncoding = Encoding.UTF8;
var bytes = options.RequestContentBytes ?? requestEncoding.GetBytes(options.RequestContent ?? string.Empty);
var bytes = options.RequestContentBytes ?? Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
@ -392,7 +371,6 @@ namespace Emby.Server.Implementations.HttpClientManager
}
httpWebRequest.ContentType = contentType;
httpWebRequest.ContentLength = bytes.Length;
(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
}
@ -409,10 +387,7 @@ namespace Emby.Server.Implementations.HttpClientManager
if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
{
if (options.ResourcePool != null)
{
options.ResourcePool.Release();
}
options.ResourcePool?.Release();
throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
}
@ -457,7 +432,6 @@ namespace Emby.Server.Implementations.HttpClientManager
using (var stream = httpResponse.GetResponseStream())
{
var memoryStream = new MemoryStream();
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
memoryStream.Position = 0;
@ -476,10 +450,7 @@ namespace Emby.Server.Implementations.HttpClientManager
}
finally
{
if (options.ResourcePool != null)
{
options.ResourcePool.Release();
}
options.ResourcePool?.Release();
}
}
@ -488,13 +459,9 @@ namespace Emby.Server.Implementations.HttpClientManager
var responseInfo = new HttpResponseInfo(disposable)
{
Content = content,
StatusCode = httpResponse.StatusCode,
ContentType = httpResponse.ContentType,
ContentLength = contentLength,
ResponseUrl = httpResponse.ResponseUri.ToString()
};
@ -511,11 +478,8 @@ namespace Emby.Server.Implementations.HttpClientManager
var responseInfo = new HttpResponseInfo
{
TempFilePath = tempFile,
StatusCode = httpResponse.StatusCode,
ContentType = httpResponse.ContentType,
ContentLength = contentLength
};
@ -619,24 +583,22 @@ namespace Emby.Server.Implementations.HttpClientManager
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
if (contentLength.HasValue)
{
using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
{
await httpResponse.GetResponseStream().CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
}
}
else
{
// 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);
}
}
options.Progress.Report(100);
@ -650,10 +612,7 @@ namespace Emby.Server.Implementations.HttpClientManager
}
finally
{
if (options.ResourcePool != null)
{
options.ResourcePool.Release();
}
options.ResourcePool?.Release();
}
}
@ -810,8 +769,11 @@ namespace Emby.Server.Implementations.HttpClientManager
var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
if (!isSuccessful)
if (isSuccessful)
{
return;
}
if (options.LogErrorResponseBody)
{
try
@ -834,12 +796,12 @@ namespace Emby.Server.Implementations.HttpClientManager
}
}
throw new HttpException(response.StatusDescription)
{
StatusCode = response.StatusCode
};
}
}
private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
{
@ -859,15 +821,12 @@ namespace Emby.Server.Implementations.HttpClientManager
private static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
if (timedOut && state != null)
{
WebRequest request = (WebRequest)state;
if (state != null)
{
request.Abort();
}
}
}
private class TaskCallback
{
@ -880,13 +839,13 @@ namespace Emby.Server.Implementations.HttpClientManager
public void OnError(Task<WebResponse> task)
{
if (task.Exception != null)
if (task.Exception == null)
{
taskCompletion.TrySetException(task.Exception);
taskCompletion.TrySetException(Enumerable.Empty<Exception>());
}
else
{
taskCompletion.TrySetException(new List<Exception>());
taskCompletion.TrySetException(task.Exception);
}
}
}

View File

@ -8,7 +8,6 @@ using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@ -16,17 +15,12 @@ using Emby.Server.Implementations.Services;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Security;
using MediaBrowser.Controller;
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Model.Services;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Text;
using System.Net.Sockets;
using Emby.Server.Implementations.Net;
using MediaBrowser.Common.Events;
using MediaBrowser.Model.Events;
namespace Emby.Server.Implementations.HttpServer
@ -184,7 +178,7 @@ namespace Emby.Server.Implementations.HttpServer
if (WebSocketConnected != null)
{
EventHelper.FireEventIfNotNull(WebSocketConnected, this, new GenericEventArgs<IWebSocketConnection>(connection), _logger);
WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
}
}

View File

@ -1,5 +1,4 @@
using System.Text;
using MediaBrowser.Common.Events;
using MediaBrowser.Controller.Net;
using Microsoft.Extensions.Logging;
using MediaBrowser.Model.Net;
@ -118,7 +117,7 @@ namespace Emby.Server.Implementations.HttpServer
void socket_Closed(object sender, EventArgs e)
{
EventHelper.FireEventIfNotNull(Closed, this, EventArgs.Empty, _logger);
Closed?.Invoke(this, EventArgs.Empty);
}
/// <summary>

View File

@ -2,14 +2,9 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.IO;
using MediaBrowser.Common.Events;
using MediaBrowser.Common.Progress;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Extensions;
using Microsoft.Extensions.Logging;
@ -133,7 +128,7 @@ namespace Emby.Server.Implementations.IO
Logger.LogDebug("Timer stopped.");
DisposeTimer();
EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger);
Completed?.Invoke(this, EventArgs.Empty);
try
{

View File

@ -24,7 +24,6 @@ namespace Emby.Server.Implementations.IO
private string _tempPath;
private SharpCifsFileSystem _sharpCifsFileSystem;
private IEnvironmentInfo _environmentInfo;
private bool _isEnvironmentCaseInsensitive;
@ -43,8 +42,6 @@ namespace Emby.Server.Implementations.IO
SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
_sharpCifsFileSystem = new SharpCifsFileSystem(environmentInfo.OperatingSystem);
_isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
}
@ -233,11 +230,6 @@ namespace Emby.Server.Implementations.IO
/// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
public FileSystemMetadata GetFileSystemInfo(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileSystemInfo(path);
}
// Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
if (Path.HasExtension(path))
{
@ -273,11 +265,6 @@ namespace Emby.Server.Implementations.IO
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
public FileSystemMetadata GetFileInfo(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileInfo(path);
}
var fileInfo = new FileInfo(path);
return GetFileSystemMetadata(fileInfo);
@ -293,11 +280,6 @@ namespace Emby.Server.Implementations.IO
/// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
public FileSystemMetadata GetDirectoryInfo(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectoryInfo(path);
}
var fileInfo = new DirectoryInfo(path);
return GetFileSystemMetadata(fileInfo);
@ -460,11 +442,6 @@ namespace Emby.Server.Implementations.IO
/// <returns>FileStream.</returns>
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
}
if (_supportsAsyncFileStreams && isAsync)
{
return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous);
@ -475,11 +452,6 @@ namespace Emby.Server.Implementations.IO
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
}
var defaultBufferSize = 4096;
return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions));
}
@ -550,12 +522,6 @@ namespace Emby.Server.Implementations.IO
return;
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.SetHidden(path, isHidden);
return;
}
var info = GetExtendedFileSystemInfo(path);
if (info.Exists && info.IsHidden != isHidden)
@ -580,12 +546,6 @@ namespace Emby.Server.Implementations.IO
return;
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.SetReadOnly(path, isReadOnly);
return;
}
var info = GetExtendedFileSystemInfo(path);
if (info.Exists && info.IsReadOnly != isReadOnly)
@ -610,12 +570,6 @@ namespace Emby.Server.Implementations.IO
return;
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.SetAttributes(path, isHidden, isReadOnly);
return;
}
var info = GetExtendedFileSystemInfo(path);
if (!info.Exists)
@ -688,11 +642,6 @@ namespace Emby.Server.Implementations.IO
private char GetDirectorySeparatorChar(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectorySeparatorChar(path);
}
return Path.DirectorySeparatorChar;
}
@ -732,11 +681,6 @@ namespace Emby.Server.Implementations.IO
public string GetDirectoryName(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectoryName(path);
}
return Path.GetDirectoryName(path);
}
@ -747,11 +691,6 @@ namespace Emby.Server.Implementations.IO
throw new ArgumentNullException("path");
}
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.NormalizePath(path);
}
if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
{
return path;
@ -794,11 +733,6 @@ namespace Emby.Server.Implementations.IO
{
// Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return true;
}
if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
!path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
@ -812,35 +746,17 @@ namespace Emby.Server.Implementations.IO
public void DeleteFile(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.DeleteFile(path);
return;
}
SetAttributes(path, false, false);
File.Delete(path);
}
public void DeleteDirectory(string path, bool recursive)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.DeleteDirectory(path, recursive);
return;
}
Directory.Delete(path, recursive);
}
public void CreateDirectory(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.CreateDirectory(path);
return;
}
Directory.CreateDirectory(path);
}
@ -863,11 +779,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectories(path, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
@ -880,11 +791,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// On linux and osx the search pattern is case sensitive
@ -914,11 +820,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive);
}
var directoryInfo = new DirectoryInfo(path);
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
@ -938,29 +839,16 @@ namespace Emby.Server.Implementations.IO
public string[] ReadAllLines(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllLines(path);
}
return File.ReadAllLines(path);
}
public void WriteAllLines(string path, IEnumerable<string> lines)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllLines(path, lines);
return;
}
File.WriteAllLines(path, lines);
}
public Stream OpenRead(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.OpenRead(path);
}
return File.OpenRead(path);
}
@ -977,128 +865,61 @@ namespace Emby.Server.Implementations.IO
public void CopyFile(string source, string target, bool overwrite)
{
var enableSharpCifsForSource = _sharpCifsFileSystem.IsEnabledForPath(source);
if (enableSharpCifsForSource != _sharpCifsFileSystem.IsEnabledForPath(target))
{
CopyFileUsingStreams(source, target, overwrite);
return;
}
if (enableSharpCifsForSource)
{
_sharpCifsFileSystem.CopyFile(source, target, overwrite);
return;
}
File.Copy(source, target, overwrite);
}
public void MoveFile(string source, string target)
{
if (_sharpCifsFileSystem.IsEnabledForPath(source))
{
_sharpCifsFileSystem.MoveFile(source, target);
return;
}
File.Move(source, target);
}
public void MoveDirectory(string source, string target)
{
if (_sharpCifsFileSystem.IsEnabledForPath(source))
{
_sharpCifsFileSystem.MoveDirectory(source, target);
return;
}
Directory.Move(source, target);
}
public bool DirectoryExists(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.DirectoryExists(path);
}
return Directory.Exists(path);
}
public bool FileExists(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.FileExists(path);
}
return File.Exists(path);
}
public string ReadAllText(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllText(path);
}
return File.ReadAllText(path);
}
public byte[] ReadAllBytes(string path)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllBytes(path);
}
return File.ReadAllBytes(path);
}
public void WriteAllText(string path, string text, Encoding encoding)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllText(path, text, encoding);
return;
}
File.WriteAllText(path, text, encoding);
}
public void WriteAllText(string path, string text)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllText(path, text);
return;
}
File.WriteAllText(path, text);
}
public void WriteAllBytes(string path, byte[] bytes)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
_sharpCifsFileSystem.WriteAllBytes(path, bytes);
return;
}
File.WriteAllBytes(path, bytes);
}
public string ReadAllText(string path, Encoding encoding)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.ReadAllText(path, encoding);
}
return File.ReadAllText(path, encoding);
}
public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateDirectories(path, "*", searchOption);
}
@ -1110,11 +931,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
// On linux and osx the search pattern is case sensitive
@ -1144,11 +960,6 @@ namespace Emby.Server.Implementations.IO
public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
{
if (_sharpCifsFileSystem.IsEnabledForPath(path))
{
return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive);
}
var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
}

View File

@ -1,409 +0,0 @@
// 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)
{
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;
}
}
}

View File

@ -1,102 +0,0 @@
// 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);
}
}
}

View File

@ -1,122 +0,0 @@
// 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;
}
}
}

View File

@ -1,40 +0,0 @@
// 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);
}
}

View File

@ -1,48 +0,0 @@
// 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" };
}
}

View File

@ -1,93 +0,0 @@
// 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();
}
}
}

View File

@ -1,332 +0,0 @@
// 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)
{
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;
}
}
}

View File

@ -1,150 +0,0 @@
// 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);
}
}

View File

@ -1,135 +0,0 @@
// 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();
}
}
}
}

View File

@ -1,29 +0,0 @@
// 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);
}
}

View File

@ -1,43 +0,0 @@
// 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()
{
}
}
}

View File

@ -1,34 +0,0 @@
// 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];
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,43 +0,0 @@
// 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;
}
}
}

View File

@ -1,29 +0,0 @@
// 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;
}
}
}

View File

@ -1,29 +0,0 @@
// 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;
}
}
}

View File

@ -1,34 +0,0 @@
// 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;
}
}
}

View File

@ -1,35 +0,0 @@
// 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;
}
}
}

View File

@ -1,30 +0,0 @@
// 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;
}
}
}

View File

@ -1,28 +0,0 @@
// 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;
}
}
}

View File

@ -1,28 +0,0 @@
// 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;
}
}
}

View File

@ -1,28 +0,0 @@
// 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;
}
}
}

View File

@ -1,28 +0,0 @@
// 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;
}
}
}

View File

@ -1,55 +0,0 @@
// 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;
}
}
}

View File

@ -1,43 +0,0 @@
// 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;
}
}
}

View File

@ -1,616 +0,0 @@
// 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();
}
}
}
}

View File

@ -1,579 +0,0 @@
// 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);
}
}
}
}
}
}

View File

@ -1,40 +0,0 @@
// 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()
{
}
}
}

View File

@ -1,41 +0,0 @@
// 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()
{
}
}
}

View File

@ -1,49 +0,0 @@
// 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()
{
}
}
}

View File

@ -1,734 +0,0 @@
// 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();
}
}
}
}

View File

@ -1,305 +0,0 @@
// 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();
}
}
}

View File

@ -1,32 +0,0 @@
// 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)
{
}
}
}

View File

@ -1,40 +0,0 @@
// 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();
}
}
}

View File

@ -1,40 +0,0 @@
// 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();
}
}
}

View File

@ -1,27 +0,0 @@
// 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);
}
}

View File

@ -1,40 +0,0 @@
// 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();
}
}
}

View File

@ -1,40 +0,0 @@
// 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();
}
}
}

View File

@ -1,285 +0,0 @@
// 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();
}
}
}
}
}

View File

@ -1,148 +0,0 @@
// 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);
}
}
}

View File

@ -1,65 +0,0 @@
// 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);
}
}
}

View File

@ -1,202 +0,0 @@
// 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);
}
}
}
}
}
}
}

View File

@ -1,269 +0,0 @@
// 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)
{
}
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();
}
}
}

View File

@ -1,52 +0,0 @@
// 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() + "]";
}
}
}

View File

@ -1,68 +0,0 @@
// 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
+ "]";
}
}
}

View File

@ -1,664 +0,0 @@
// 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)
{
}
_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;
}
}
}

View File

@ -1,448 +0,0 @@
// 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;
}
}
}

View File

@ -1,920 +0,0 @@
// 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:\&gt;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. &lt;a
/// href="../../../nbtcodes.html"&gt;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();
}
}
}

View File

@ -1,164 +0,0 @@
// 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);
}
}
}

View File

@ -1,59 +0,0 @@
// 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() + "]";
}
}
}

View File

@ -1,140 +0,0 @@
// 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() + "]";
}
}
}

View File

@ -1,63 +0,0 @@
// 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;
}
}
}

View File

@ -1,54 +0,0 @@
// 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;
}
}
}

View File

@ -1,156 +0,0 @@
// 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
);
}
}

View File

@ -1,197 +0,0 @@
// 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));
}
}

View File

@ -1,140 +0,0 @@
// 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();
}
}

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