initial commit
Some checks failed
BlockStorage/repertory_osx/pipeline/head There was a failure building this commit
BlockStorage/repertory_windows/pipeline/head This commit looks good
BlockStorage/repertory_linux_builds/pipeline/head This commit looks good

This commit is contained in:
2022-03-05 00:30:50 -06:00
commit 3ff46723b8
626 changed files with 178600 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "airfs", "airfs.vcxproj", "{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Debug|x64.ActiveCfg = Debug|x64
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Debug|x64.Build.0 = Debug|x64
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Debug|x86.ActiveCfg = Debug|Win32
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Debug|x86.Build.0 = Debug|Win32
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Release|x64.ActiveCfg = Release|x64
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Release|x64.Build.0 = Release|x64
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Release|x86.ActiveCfg = Release|Win32
{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,182 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{CA441CE7-C4DE-4B5E-AA72-D4D483413EF0}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>airfs</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="airfs.cpp" />
<ClCompile Include="persistence.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="common.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="airfs.cpp">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="persistence.cpp">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="common.h">
<Filter>Source</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,210 @@
/**
* @file common.h
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
/*
* Airfs is based on Memfs with changes contributed by John Oberschelp.
* The contributed changes are under joint copyright by Bill Zissimopoulos
* and John Oberschelp per the Contributor Agreement found at the
* root of this project.
*/
#include <winfsp/winfsp.h>
#include <io.h>
#include <sddl.h>
#include <stdio.h>
#include <stdint.h>
#define PROGNAME "airfs"
#define ROUND_UP( bytes, units ) (((bytes) + (units) - 1) / (units) * (units))
#define ROUND_DOWN( bytes, units ) (((bytes) ) / (units) * (units))
#define MINIMUM_ALLOCSIZE 196
#define MAXIMUM_ALLOCSIZE ROUND_DOWN(10*1024*1024, MINIMUM_ALLOCSIZE)
#define SECTOR_SIZE 512
#define SECTORS_PER_ALLOCATION_UNIT 1
#define ALLOCATION_UNIT ( SECTOR_SIZE * SECTORS_PER_ALLOCATION_UNIT )
#define INFO(format, ...) FspServiceLog(EVENTLOG_INFORMATION_TYPE , format, __VA_ARGS__)
#define WARN(format, ...) FspServiceLog(EVENTLOG_WARNING_TYPE , format, __VA_ARGS__)
#define FAIL(format, ...) FspServiceLog(EVENTLOG_ERROR_TYPE , format, __VA_ARGS__)
#define AIRFS_MAX_PATH 512
#define FILEBLOCK_OVERHEAD 40 // size of ( P + E + L + R + FileOffset ) = 8 * 5 = 40
#define ARG_TO_S(v) if (arge > ++argp) v = *argp; else goto usage
#define ARG_TO_4(v) if (arge > ++argp) v = (int32_t) wcstoll_default(*argp, v); else goto usage
#define ARG_TO_8(v) if (arge > ++argp) v = wcstoll_default(*argp, v); else goto usage
enum StorageFileAccessType {ZERO=0,READ,WRITE};
enum Neighbor {LT=-2,LE=-1,EQ=0,GE=1,GT=2};
struct NODE;
typedef NODE* NODE_;
typedef int CompareFunction (void* key, NODE_);
inline NTSTATUS GetLastErrorAsStatus()
{
return FspNtStatusFromWin32(GetLastError());
}
inline UINT64 SystemTime()
{
FILETIME FileTime;
GetSystemTimeAsFileTime(&FileTime);
return ((PLARGE_INTEGER)&FileTime)->QuadPart;
}
static int64_t wcstoll_default(wchar_t *w, int64_t deflt)
{
wchar_t *endp;
int64_t i = wcstoll(w, &endp, 0);
return L'\0' != w[0] && L'\0' == *endp ? i : deflt;
}
//////////////////////////////////////////////////////////////////////
//
// Where<T> Class: This class manages an offset within our memory-mapped
// volume to another location within our memory-mapped volume. Because it is
// a self-relative offset, this delta is constant regardless of where in
// memory the file system is mapped, so we can always reobtain its address.
// A delta of 0 is the special case for "null".
//
template <class T> class Where
{
int64_t delta;
public:
Where() = default;
~Where() = default;
Where(T t) : delta( t ?( (char*)t -(char*)this ):0) {}
Where(Where& w) : delta( w.delta?( ((char*)&w+w.delta)-(char*)this ):0) {}
operator bool () { return delta != 0; }
operator T () { return (T) ( delta?( (char*)this+delta ):0); }
T operator -> () { return (T) ( delta?( (char*)this+delta ):0); }
operator void* () { return (void*)( delta?( (char*)this+delta ):0); }
bool operator == (Where& rhs) { return (char*)this+delta == (char*)&rhs+rhs.delta; }
bool operator != (Where& rhs) { return (char*)this+delta != (char*)&rhs+rhs.delta; }
bool operator == (T rhs) { return (char*)this+delta == (char*)rhs; }
bool operator != (T rhs) { return (char*)this+delta != (char*)rhs; }
Where& operator = (Where& rhs) { delta = rhs.delta?( ((char*)&rhs+rhs.delta) - ((char*)this) ):0; return *this; }
Where& operator = (void* rhs) { delta = rhs ?( (char*)rhs - ((char*)this) ):0; return *this; }
char* Address () { return (char*)this+delta; }
};
//////////////////////////////////////////////////////////////////////
//
// The header for an Airfs volume
//
typedef struct
{
char Signature[8]; // Airfs\0\0\0
char MapFormatVersion[4]; // Major.Minor.Patch.Build
char filler[4];
Where<NODE_> Root;
Where<NODE_> Available;
UINT64 VolumeSize;
UINT64 FreeSize;
WCHAR VolumeLabel[32];
UINT16 VolumeLabelLength;
UINT16 filler1,filler2,filler3;
UINT32 CaseInsensitive;
UINT32 filler4;
int64_t VolumeLength;
FSP_FSCTL_VOLUME_PARAMS VolumeParams;
FSP_FILE_SYSTEM *FileSystem;
HANDLE MapFileHandle;
HANDLE MapHandle;
} AIRFS, *AIRFS_;
//////////////////////////////////////////////////////////////////////
//
// Information per file or directory
//
struct NODE
{
Where<NODE_> P,L,R,E; // Sorted sibling tree: Parent, Left, Right, and Equal
union
{
Where<WCHAR*> Name;
int64_t FileOffset;
};
Where<NODE_> Parent;
Where<NODE_> Children;
FSP_FSCTL_FILE_INFO FileInfo;
uint64_t SecurityDescriptorSize;
Where<char*> SecurityDescriptor;
Where<NODE_> FileBlocks;
uint64_t ReparseDataSize;
Where<char*> ReparseData;
volatile LONG RefCount;
Where<NODE_> Streams;
BOOLEAN IsAStream;
};
//////////////////////////////////////////////////////////////////////
class SpinLock
{
LONG C; // Counter
HANDLE S; // Semaphore
public:
SpinLock() { C = 0; S = CreateSemaphore(NULL, 0, 1, NULL); }
~SpinLock() { CloseHandle(S); }
void Acquire() { if (_InterlockedIncrement(&C) > 1) WaitForSingleObject(S, INFINITE); }
void Release() { if (_InterlockedDecrement(&C) > 0) ReleaseSemaphore(S, 1, NULL); }
};
//////////////////////////////////////////////////////////////////////
void Airprint (const char * format, ...);
int SizeCmp (void* key, NODE_);
int ExactNameCmp (void* key, NODE_);
int CaselessNameCmp (void* key, NODE_);
NODE_ Find (Where<NODE_> &root, void* key, CompareFunction);
NODE_ Near (Where<NODE_> &root, void* key, CompareFunction, Neighbor);
void Attach (Where<NODE_> &root, NODE_ attach, CompareFunction, void* key);
void Detach (Where<NODE_> &root, NODE_ detach);
NODE_ First (NODE_ start);
NODE_ Last (NODE_ start);
NODE_ Next (NODE_);
NODE_ Prev (NODE_);
NTSTATUS StorageStartup (AIRFS_ &, WCHAR* MapName, WCHAR* StorageFileName, int64_t Length);
NTSTATUS StorageShutdown (AIRFS_);
void* StorageAllocate (AIRFS_, int64_t RequestedSize);
void* StorageReallocate (AIRFS_, void* Reallocate, int64_t RequestedSize);
void StorageFree (AIRFS_, void* Release);
NTSTATUS StorageSetFileCapacity (AIRFS_, NODE_, int64_t MinimumRequiredCapacity);
void StorageAccessFile (StorageFileAccessType, NODE_, int64_t Offset, int64_t NumBytes, char* Address);
static_assert(AIRFS_MAX_PATH > MAX_PATH, "AIRFS_MAX_PATH must be greater than MAX_PATH.");
static_assert(sizeof NODE + sizeof int32_t == MINIMUM_ALLOCSIZE, "MINIMUM_ALLOCSIZE should be 196.");
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,594 @@
/**
* @file persistence.cpp
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
/*
* Airfs is based on Memfs with changes contributed by John Oberschelp.
* The contributed changes are under joint copyright by Bill Zissimopoulos
* and John Oberschelp per the Contributor Agreement found at the
* root of this project.
*/
/*
* Airfs uses a memory-mapped file per volume to achieve persistence.
* The primary advantage of this is that volume loads and saves are automatic.
* The two primary disadvantages, and our workarounds are:
* 1. We can't use standard containers or memory management,
* so the below Rubbertree and Storage functions are used instead.
* 2. Each process will map the volume to an arbitrary address,
* so Where<T> offsets are used in place of pointers.
*/
#include "common.h"
SpinLock StorageLock, AirprintLock, SetLock;
int SizeCmp ( void* key, NODE_ x)
{
return *(int32_t*)key - ((int32_t*)x)[-1];
}
int BlockCmp ( void* key, NODE_ x)
{
int64_t left = *(int64_t*)key;
int64_t right = x->FileOffset;
return left == right ? 0 : (left < right ? -1 : 1);
}
int CaselessNameCmp ( void* key, NODE_ x)
{
WCHAR* c1 = (WCHAR*) key;
WCHAR* c2 = x->Name;
return _wcsicmp(c1,c2);
}
int ExactNameCmp ( void* key, NODE_ x)
{
WCHAR* c1 = (WCHAR*) key;
WCHAR* c2 = x->Name;
return wcscmp(c1,c2);
}
//////////////////////////////////////////////////////////////////////
void Airprint (const char * format, ...)
{
AirprintLock.Acquire();
va_list args;
va_start(args, format);
char szBuffer[512];
sprintf_s(szBuffer, 511, "Airfs %5.5f ----", SystemTime() / 10'000'000.0);
vsnprintf(szBuffer+25, 511-25, format, args);
OutputDebugStringA(szBuffer);
va_end(args);
AirprintLock.Release();
}
//////////////////////////////////////////////////////////////////////
//
// Rubbertree (because it is flexible!)
// Implements a sorted set of elements, using a binary tree.
// Has a function, Near, that finds nodes at or adjacent to a key.
// Attach, Find, and Near use splay to improve random access times.
// First, Last, Next, and Prev do not, to improve sequential access times.
// Replacing each Where<NODE_> with NODE_ would make this a pointer-based tree.
// In addition to Left, Right, and Parent references, each node has an Equal
// reference that may be used to keep "equivalent" nodes. This is used by
// our memory heap manager's tree of available memory blocks, sorted by size.
//--------------------------------------------------------------------
inline void rotateL(Where<NODE_> &root, NODE_ x)
{
NODE_ y = x->R, p = x->P;
if (x->R = y->L) y->L->P = x;
if (!(y->P = p))
root = y;
else
{
if (x == p->L) p->L = y;
else p->R = y;
}
(y->L = x)->P = y;
}
//--------------------------------------------------------------------
inline void rotateR(Where<NODE_> &root, NODE_ y)
{
NODE_ x = y->L, p = y->P;
if (y->L = x->R) x->R->P = y;
if (!(x->P = p))
root = x;
else
{
if (y == p->L) p->L = x;
else p->R = x;
}
(x->R = y)->P = x;
}
//--------------------------------------------------------------------
static void splay(Where<NODE_> &root, NODE_ x)
{
while (NODE_ p = x->P)
{
if (!p->P)
{
if (p->L == x) rotateR(root, p);
else rotateL(root, p);
}
else
{
if (p == p->P->R)
{
if (p->R == x) rotateL(root, p->P);
else rotateR(root, p);
rotateL(root, x->P);
}
else
{
if (p->L == x) rotateR(root, p->P);
else rotateL(root, p);
rotateR(root, x->P);
}
}
}
}
//--------------------------------------------------------------------
inline int seek(Where<NODE_> &root, NODE_ &x, void* key, CompareFunction CMP)
{
x = root;
for (;;)
{
int diff = CMP(key, x);
if (diff < 0)
{
if (!x->L) return -1;
x = x->L;
}
else if (diff > 0)
{
if (!x->R) return 1;
x = x->R;
}
else return 0;
}
}
//--------------------------------------------------------------------
inline NODE_ next(NODE_ x)
{
if (x->R) { x = x->R; while (x->L) x = x->L; return x; }
NODE_ p = x->P;
while (p && x == p->R) { x = p; p = p->P; }
return p;
}
//--------------------------------------------------------------------
inline NODE_ prev(NODE_ x)
{
if (x->L) { x = x->L; while (x->R) x = x->R; return x; }
NODE_ p = x->P;
while (p && x == p->L) { x = p; p = p->P; }
return p;
}
//--------------------------------------------------------------------
NODE_ First(NODE_ x)
{
SetLock.Acquire();
if (x) while (x->L) x = x->L;
SetLock.Release();
return x;
}
//--------------------------------------------------------------------
NODE_ Last(NODE_ x)
{
SetLock.Acquire();
if (x) while (x->R) x = x->R;
SetLock.Release();
return x;
}
//--------------------------------------------------------------------
NODE_ Next(NODE_ x)
{
SetLock.Acquire();
x = next(x);
SetLock.Release();
return x;
}
//--------------------------------------------------------------------
NODE_ Prev(NODE_ x)
{
SetLock.Acquire();
x = prev(x);
SetLock.Release();
return x;
}
//--------------------------------------------------------------------
NODE_ Near(Where<NODE_> &root, void* key, CompareFunction CMP, Neighbor want)
{
// Return a node relative to (just <, <=, ==, >=, or >) a key.
if (!root) return 0;
SetLock.Acquire();
NODE_ x;
int dir = seek(root, x, key, CMP);
if ((dir == 0 && want == GT) || (dir > 0 && want >= GE)) x = next(x);
else
if ((dir == 0 && want == LT) || (dir < 0 && want <= LE)) x = prev(x);
else
if (dir != 0 && want == EQ) x = 0;
if (x) splay(root, x);
SetLock.Release();
return x;
}
//--------------------------------------------------------------------
NODE_ Find(Where<NODE_> &root, void* key, CompareFunction CMP)
{
if (!root) return 0;
SetLock.Acquire();
NODE_ x;
int direction = seek(root, x, key, CMP);
splay(root, x);
SetLock.Release();
return direction?0:x;
}
//--------------------------------------------------------------------
void Attach(Where<NODE_> &root, NODE_ x, CompareFunction CMP, void* key)
{
SetLock.Acquire();
if (!root)
{
root = x;
x->P = x->L = x->R = x->E = 0;
SetLock.Release();
return;
}
NODE_ f;
int diff = seek(root, f, key, CMP);
if (!diff)
{
if (x->L = f->L) x->L->P = x;
if (x->R = f->R) x->R->P = x;
NODE_ p = f->P;
if (x->P = p) { if (p->L == f) p->L = x; else p->R = x; }
else root = x;
(x->E = f)->P = x;
f->L = f->R = 0;
splay(root, x);
SetLock.Release();
return;
}
if (diff < 0) f->L = x; else f->R = x;
x->P = f;
x->L = x->R = x->E = 0;
splay(root, x);
SetLock.Release();
}
//--------------------------------------------------------------------
void Detach(Where<NODE_> &root, NODE_ x)
{
SetLock.Acquire();
NODE_ e = x->E, p = x->P;
if (p && p->E == x) { if (p->E = e) e->P = p; }
else if (e)
{
if (e->L = x->L) e->L->P = e;
if (e->R = x->R) e->R->P = e;
if (e->P = p) { if (p->L == x) p->L = e; else p->R = e; }
else root = e;
}
else if (!x->L)
{
if (p) { if ( p->L == x) p->L = x->R; else p->R = x->R; }
else root = x->R;
if (x->R) x->R->P = p;
}
else if (!x->R)
{
if (p) { if ( p->L == x) p->L = x->L; else p->R = x->L; }
else root = x->L;
if (x->L) x->L->P = p;
}
else
{
e = x->L;
if (e->R)
{
do { e = e->R; } while (e->R);
if (e->P->R = e->L) e->L->P = e->P;
(e->L = x->L)->P = e;
}
(e->R = x->R)->P = e;
if (e->P = x->P) { if (e->P->L == x) e->P->L = e; else e->P->R = e; }
else root = e;
}
SetLock.Release();
}
//////////////////////////////////////////////////////////////////////
//
// Storage Functions for our memory-mapped file-based persistent volumes
//--------------------------------------------------------------------
void* StorageAllocate(AIRFS_ Airfs, int64_t RequestedSize)
{
if (!RequestedSize) return 0;
if (RequestedSize + sizeof int32_t > MAXIMUM_ALLOCSIZE) return 0;
StorageLock.Acquire();
int32_t RoundedSize = (int32_t) ROUND_UP(RequestedSize, MINIMUM_ALLOCSIZE - sizeof int32_t);
int32_t SplitableSize = RoundedSize + MINIMUM_ALLOCSIZE;
// See if we have a freed node of the size we requested.
NODE_ NewItem = Near(Airfs->Available, &RoundedSize, SizeCmp, GE);
if (NewItem)
{
int32_t FoundSize = ((int32_t*)NewItem)[-1];
if (FoundSize < SplitableSize)
{
Detach(Airfs->Available, NewItem);
Airfs->FreeSize -= FoundSize;
StorageLock.Release();
return NewItem;
}
}
// If not, see if we can downsize a larger freed element.
NewItem = Near(Airfs->Available, &SplitableSize, SizeCmp, GE);
if (NewItem)
{
int32_t FoundSize = ((int32_t*)NewItem)[-1];
Detach(Airfs->Available, NewItem);
Airfs->FreeSize -= FoundSize;
char* Addr = (char*)NewItem + RoundedSize + sizeof int32_t;
NODE_ Remainder = (NODE_) Addr;
int32_t RemainderSize = FoundSize - (RoundedSize + sizeof int32_t);
((int32_t*)Remainder)[-1] = RemainderSize;
Attach(Airfs->Available, Remainder, SizeCmp, &RemainderSize);
Airfs->FreeSize += RemainderSize;
((int32_t*)NewItem)[-1] = RoundedSize;
StorageLock.Release();
return NewItem;
}
// If not, give up.
StorageLock.Release();
return 0;
}
//--------------------------------------------------------------------
void* StorageReallocate(AIRFS_ Airfs, void* OldAlloc, int64_t RequestedSize)
{
if (!OldAlloc)
{
return StorageAllocate(Airfs, RequestedSize);
}
if (!RequestedSize)
{
StorageFree(Airfs, OldAlloc);
return 0;
}
int32_t OldSize = ((int32_t*)OldAlloc)[-1];
void* NewAlloc = StorageAllocate(Airfs, RequestedSize);
if (!NewAlloc) return 0;
memcpy(NewAlloc, OldAlloc, min(RequestedSize, OldSize));
StorageFree(Airfs, OldAlloc);
return NewAlloc;
}
//--------------------------------------------------------------------
void StorageFree(AIRFS_ Airfs, void* r)
{
if (!r) return;
StorageLock.Acquire();
NODE_ release = (NODE_) r;
int32_t Size = ((int32_t*)r)[-1];
Attach(Airfs->Available, release, SizeCmp, &Size);
Airfs->FreeSize += Size;
StorageLock.Release();
}
//--------------------------------------------------------------------
void StorageAccessFile(StorageFileAccessType Type, NODE_ Node, int64_t AccessOffset, int64_t NumBytes, char* MemoryAddress)
{
StorageLock.Acquire();
NODE_ Block = Near(Node->FileBlocks, &AccessOffset, BlockCmp, LE);
for (;;)
{
int32_t BlockSize = ((int32_t*)Block)[-1];
int64_t BlockOffset = Block->FileOffset;
int64_t BlockIndex = AccessOffset - BlockOffset + FILEBLOCK_OVERHEAD;
int64_t BlockNum = min(BlockSize-BlockIndex, NumBytes);
switch (Type)
{
case ZERO : { memset((char*)Block + BlockIndex, 0, BlockNum); break; }
case READ : { memcpy(MemoryAddress, (char*)Block + BlockIndex, BlockNum); break; }
case WRITE : { memcpy((char*)Block + BlockIndex, MemoryAddress, BlockNum); break; }
}
NumBytes -= BlockNum;
if (!NumBytes) break;
MemoryAddress += BlockNum;
AccessOffset += BlockNum;
Block = Next(Block);
}
StorageLock.Release();
}
//--------------------------------------------------------------------
NTSTATUS StorageSetFileCapacity(AIRFS_ Airfs, NODE_ Node, int64_t minimumRequiredCapacity)
{
StorageLock.Acquire();
int64_t TargetCapacity = ROUND_UP(minimumRequiredCapacity, ALLOCATION_UNIT);
NODE_ Block = Last(Node->FileBlocks);
int32_t BlockSize = Block ? ((int32_t*)Block)[-1] : 0;
int64_t CurrentCapacity = Block ? Block->FileOffset + BlockSize - FILEBLOCK_OVERHEAD: 0;
int64_t Add = TargetCapacity - CurrentCapacity;
while (Add > 0)
{
// Add a block if we can, preferably as large or larger than we need.
Add += FILEBLOCK_OVERHEAD;
Block = Near(Airfs->Available, &Add, SizeCmp, GE);
if (!Block) Block = Near(Airfs->Available, &Add, SizeCmp, LT);
Add -= FILEBLOCK_OVERHEAD;
if (Block)
{
Detach(Airfs->Available, Block);
BlockSize = ((int32_t*)Block)[-1];
Airfs->FreeSize -= BlockSize;
Block->FileOffset = CurrentCapacity;
Attach(Node->FileBlocks, Block, BlockCmp, &CurrentCapacity);
CurrentCapacity += BlockSize - FILEBLOCK_OVERHEAD;
Add -= BlockSize - FILEBLOCK_OVERHEAD;
continue;
}
StorageLock.Release();
return STATUS_INSUFFICIENT_RESOURCES;
}
// Throw away any trailing blocks that are no longer needed.
while (Add < 0)
{
Block = Last(Node->FileBlocks);
BlockSize = ((int32_t*)Block)[-1];
if (BlockSize - FILEBLOCK_OVERHEAD > -Add) break;
Add += BlockSize - FILEBLOCK_OVERHEAD;
Detach(Node->FileBlocks, Block);
Attach(Airfs->Available, Block, SizeCmp, &BlockSize);
Airfs->FreeSize += BlockSize;
}
// Possibly downsize the last block.
if (Add < 0)
{
Block = Last(Node->FileBlocks);
int32_t OldBlockSize = ((int32_t*)Block)[-1];
int32_t NewBlockSize = OldBlockSize - (int32_t) ROUND_DOWN(-Add, MINIMUM_ALLOCSIZE);
if (NewBlockSize < MINIMUM_ALLOCSIZE) NewBlockSize = MINIMUM_ALLOCSIZE;
int32_t RemainderBlockSize = OldBlockSize - NewBlockSize - sizeof int32_t;
if (RemainderBlockSize >= MINIMUM_ALLOCSIZE) // i.e. if not too near the end
{
char* Addr = (char*)Block + NewBlockSize + sizeof int32_t;
NODE_ Remainder = (NODE_) Addr;
((int32_t*)Remainder)[-1] = RemainderBlockSize;
Attach(Airfs->Available, Remainder, SizeCmp, &RemainderBlockSize);
Airfs->FreeSize += RemainderBlockSize;
((int32_t*)Block)[-1] = NewBlockSize;
}
}
StorageLock.Release();
return 0;
}
//--------------------------------------------------------------------
NTSTATUS StorageStartup(AIRFS_ &Airfs, WCHAR* MapName, WCHAR* StorageFileName, int64_t VolumeLength)
{
HANDLE MapFileHandle = INVALID_HANDLE_VALUE;
Airfs = 0;
// Open.
if (*StorageFileName)
{
MapFileHandle = CreateFileW(StorageFileName, GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE, 0, NULL, OPEN_ALWAYS, NULL, NULL);
if (MapFileHandle == INVALID_HANDLE_VALUE) return GetLastErrorAsStatus();
}
// Map.
HANDLE MapHandle = CreateFileMappingW(MapFileHandle, NULL, PAGE_EXECUTE_READWRITE, VolumeLength>>32, VolumeLength & 0xFFFFFFFF, MapName);
if (!MapHandle) return GetLastErrorAsStatus();
// Point.
char* MappedAddress = (char*) MapViewOfFile(MapHandle, FILE_MAP_ALL_ACCESS, 0, 0, VolumeLength);
if (!MappedAddress) return GetLastErrorAsStatus();
// Keep.
Airfs = (AIRFS_) MappedAddress;
Airfs->MapFileHandle = MapFileHandle;
Airfs->MapHandle = MapHandle;
Airfs->VolumeLength = VolumeLength;
return 0;
}
//--------------------------------------------------------------------
NTSTATUS StorageShutdown(AIRFS_ Airfs)
{
BOOL Ok;
NTSTATUS Result = 0;
HANDLE M = Airfs->MapHandle;
HANDLE F = Airfs->MapFileHandle;
Ok = FlushViewOfFile(Airfs, 0); if (!Ok && !Result) Result = GetLastErrorAsStatus();
if (F != INVALID_HANDLE_VALUE)
{
Ok = FlushFileBuffers(F); if (!Ok && !Result) Result = GetLastErrorAsStatus();
// TODO: Set and write a flag something like Airfs->UpdatesCompleted here?
}
Ok = UnmapViewOfFile(Airfs); if (!Ok && !Result) Result = GetLastErrorAsStatus();
if (M)
{
Ok = CloseHandle(M); if (!Ok && !Result) Result = GetLastErrorAsStatus();
}
if (F != INVALID_HANDLE_VALUE)
{
Ok = CloseHandle(F); if (!Ok && !Result) Result = GetLastErrorAsStatus();
}
return Result;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,18 @@
usage:
@echo "make cygfuse|winfsp-fuse" 1>&2
@echo "" 1>&2
@echo " cygfuse Link with CYGFUSE" 1>&2
@echo " winfsp-fuse Link with WinFsp-FUSE" 1>&2
@exit 2
cygfuse: memfs-cygfuse
winfsp-fuse: memfs-winfsp-fuse
memfs-cygfuse: memfs-fuse.cpp
g++ $^ -o $@ -g -Wall -std=gnu++17 `pkg-config fuse --cflags --libs`
memfs-winfsp-fuse: export PKG_CONFIG_PATH=$(PWD)/winfsp.install/lib
memfs-winfsp-fuse: memfs-fuse.cpp
ln -nsf "`regtool --wow32 get '/HKLM/Software/WinFsp/InstallDir' | cygpath -au -f -`" winfsp.install
g++ $^ -o $@ -g -Wall -std=gnu++17 `pkg-config fuse --cflags --libs`

View File

@ -0,0 +1,7 @@
`Memfs-fuse` is an in-memory FUSE file system.
It can be built with the following tools:
- Using Visual Studio (`memfs-fuse.sln`).
- Using Cygwin GCC and linking directly with the WinFsp DLL (`make winfsp-fuse`).
- Using Cygwin GCC and linking to CYGFUSE (`make cygfuse`).

View File

@ -0,0 +1,104 @@
/**
* @file compat.h
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#ifndef COMPAT_H_INCLUDED
#define COMPAT_H_INCLUDED
#if defined(_WIN32) && defined(FSP_FUSE_SYM)
#include <winfsp/winfsp.h>
#undef fuse_main
#define fuse_main(argc, argv, ops, data)\
(FspLoad(0), fuse_main_real(argc, argv, ops, sizeof *(ops), data))
#endif
#if !defined(_WIN32) && !defined(fuse_stat)
#define fuse_uid_t uid_t
#define fuse_gid_t gid_t
#define fuse_pid_t pid_t
#define fuse_dev_t dev_t
#define fuse_mode_t mode_t
#define fuse_nlink_t nlink_t
#define fuse_off_t off_t
#define fuse_fsblkcnt_t fsblkcnt_t
#define fuse_fsfilcnt_t fsfilcnt_t
#define fuse_blksize_t blksize_t
#define fuse_blkcnt_t blkcnt_t
#define fuse_timespec timespec
#define fuse_stat stat
#define fuse_statvfs statvfs
#define fuse_flock flock
#define fuse_iovec iovec
#endif
#if !defined(S_IFMT)
#define S_IFMT 0170000
#endif
#if !defined(S_IFDIR)
#define S_IFDIR 0040000
#endif
#if !defined(S_IFCHR)
#define S_IFCHR 0020000
#endif
#if !defined(S_IFBLK)
#define S_IFBLK 0060000
#endif
#if !defined(S_IFREG)
#define S_IFREG 0100000
#endif
#if !defined(S_IFLNK)
#define S_IFLNK 0120000
#endif
#if !defined(S_IFSOCK)
#define S_IFSOCK 0140000
#endif
#if !defined(S_IFIFO)
#define S_IFIFO 0010000
#endif
#if defined(__APPLE__)
#define st_atim st_atimespec
#define st_ctim st_ctimespec
#define st_mtim st_mtimespec
#endif
#if defined(__APPLE__) || defined(__linux__) || defined(__CYGWIN__)
#include <sys/xattr.h>
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(_WIN32)
#define XATTR_CREATE 1
#define XATTR_REPLACE 2
#endif
#if !defined(ENOATTR)
#define ENOATTR ENODATA
#elif !defined(ENODATA)
#define ENODATA ENOATTR
#endif
#endif

View File

@ -0,0 +1,693 @@
/**
* @file memfs-fuse.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <cerrno>
#include <chrono>
#include <cstring>
#include <algorithm>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include <fuse.h>
#include "compat.h"
class memfs
{
public:
memfs() : _ino(1), _root(std::make_shared<node_t>(_ino, S_IFDIR | 00777, 0, 0))
{
}
int main(int argc, char *argv[])
{
static fuse_operations ops =
{
getattr,
0, // getdir
readlink,
mknod,
mkdir,
unlink,
rmdir,
symlink,
rename,
link,
chmod,
chown,
truncate,
0, // utime
open,
read,
write,
statfs,
flush,
release,
0, // fsync
setxattr,
getxattr,
listxattr,
removexattr,
opendir,
readdir,
releasedir,
0, // fsyncdir
init,
0, // destroy
0, // access
0, // create
ftruncate,
fgetattr,
0, // lock
utimens,
0, // bmap
0, // flag_nullpath_ok
0, // flag_nopath
0, // flag_utime_omit_ok
0, // flag_reserved
0, // ioctl
0, // poll
0, // write_buf
0, // read_buf
0, // flock
0, // fallocate
0, // reserved00
0, // reserved01
0, // reserved02
0, // statfs_x
0, // setvolname
0, // exchange
0, // getxtimes
0, // setbkuptime
0, // setchgtime
setcrtime,
#if defined(FSP_FUSE_USE_STAT_EX)
chflags,
#else
0, // chflags
#endif
0, // setattr_x
0, // fsetattr_x
};
return fuse_main(argc, argv, &ops, this);
}
private:
struct node_t
{
node_t(fuse_ino_t ino, fuse_mode_t mode, fuse_uid_t uid, fuse_gid_t gid, fuse_dev_t dev = 0)
: stat()
{
stat.st_ino = ino;
stat.st_mode = mode;
stat.st_nlink = 1;
stat.st_uid = uid;
stat.st_gid = gid;
stat.st_rdev = dev;
stat.st_atim = stat.st_mtim = stat.st_ctim = stat.st_birthtim = now();
}
void resize(size_t size, bool capacity)
{
if (capacity)
{
const size_t unit = 64 * 1024;
size_t newcap = (size + unit - 1) / unit * unit;
size_t oldcap = data.capacity();
if (newcap > oldcap)
data.reserve(newcap);
else if (newcap < oldcap)
{
data.resize(newcap);
data.shrink_to_fit();
}
}
data.resize(size);
stat.st_size = size;
}
struct fuse_stat stat;
std::vector<uint8_t> data;
std::unordered_map<std::string, std::shared_ptr<node_t>> childmap;
std::unordered_map<std::string, std::vector<uint8_t>> xattrmap;
};
static fuse_timespec now()
{
using namespace std::chrono;
auto now = system_clock::now();
auto sec = floor<seconds>(now);
auto nsec = floor<nanoseconds>(now) - floor<nanoseconds>(sec);
return fuse_timespec
{
static_cast<decltype(fuse_timespec::tv_sec)>(sec.time_since_epoch().count()),
/* std::chrono epoch is UNIX epoch in C++20 */
static_cast<decltype(fuse_timespec::tv_nsec)>(nsec.count()),
};
}
static memfs *getself()
{
return static_cast<memfs *>(fuse_get_context()->private_data);
}
static int getattr(const char *path, struct fuse_stat *stbuf)
{
return fgetattr(path, stbuf, nullptr);
}
static int fgetattr(const char *path, struct fuse_stat *stbuf, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
*stbuf = node->stat;
return 0;
}
static int readlink(const char *path, char *buf, size_t size)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (S_IFLNK != (node->stat.st_mode & S_IFMT))
return EINVAL;
size = (std::min)(size - 1, node->data.size());
std::memcpy(buf, node->data.data(), size);
buf[size] = '\0';
return 0;
}
static int mknod(const char *path, fuse_mode_t mode, fuse_dev_t dev)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->make_node(path, mode, dev);
}
static int mkdir(const char *path, fuse_mode_t mode)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->make_node(path, S_IFDIR | (mode & 07777), 0);
}
static int unlink(const char *path)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->remove_node(path, false);
}
static int rmdir(const char *path)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->remove_node(path, true);
}
static int symlink(const char *dstpath, const char *srcpath)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->make_node(srcpath, S_IFLNK | 00777, 0, dstpath);
}
static int rename(const char *oldpath, const char *newpath)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto oldlookup = self->lookup_node(oldpath);
auto oldprnt = std::get<0>(oldlookup);
auto oldname = std::get<1>(oldlookup);
auto oldnode = std::get<2>(oldlookup);
if (!oldnode)
return -ENOENT;
auto newlookup = self->lookup_node(newpath);
auto newprnt = std::get<0>(newlookup);
auto newname = std::get<1>(newlookup);
auto newnode = std::get<2>(newlookup);
if (!newprnt)
return -ENOENT;
if (newname.empty())
// guard against directory loop creation
return -EINVAL;
if (oldprnt == newprnt && oldname == newname)
return 0;
if (newnode)
{
if (int errc = self->remove_node(newpath, S_IFDIR == (oldnode->stat.st_mode & S_IFMT)))
return errc;
}
oldprnt->childmap.erase(oldname);
newprnt->childmap[newname] = oldnode;
return 0;
}
static int link(const char *oldpath, const char *newpath)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto oldlookup = self->lookup_node(oldpath);
auto oldnode = std::get<2>(oldlookup);
if (!oldnode)
return -ENOENT;
auto newlookup = self->lookup_node(newpath);
auto newprnt = std::get<0>(newlookup);
auto newname = std::get<1>(newlookup);
auto newnode = std::get<2>(newlookup);
if (!newprnt)
return -ENOENT;
if (newnode)
return -EEXIST;
oldnode->stat.st_nlink++;
newprnt->childmap[newname] = oldnode;
oldnode->stat.st_ctim = newprnt->stat.st_ctim = newprnt->stat.st_mtim = now();
return 0;
}
static int chmod(const char *path, fuse_mode_t mode)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
node->stat.st_mode = (node->stat.st_mode & S_IFMT) | (mode & 07777);
node->stat.st_ctim = now();
return 0;
}
static int chown(const char *path, fuse_uid_t uid, fuse_gid_t gid)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (-1 != uid)
node->stat.st_uid = uid;
if (-1 != gid)
node->stat.st_gid = gid;
node->stat.st_ctim = now();
return 0;
}
static int truncate(const char *path, fuse_off_t size)
{
return ftruncate(path, size, nullptr);
}
static int ftruncate(const char *path, fuse_off_t size,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
if (SIZE_MAX < size)
return -EFBIG;
node->resize(static_cast<size_t>(size), true);
node->stat.st_ctim = node->stat.st_mtim = now();
#if defined(FSP_FUSE_USE_STAT_EX)
node->stat.st_flags |= UF_ARCHIVE;
#endif
return 0;
}
static int open(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->open_node(path, false, fi);
}
static int read(const char *path, char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
fuse_off_t endoff = (std::min)(
off + static_cast<fuse_off_t>(size), static_cast<fuse_off_t>(node->data.size()));
if (off > endoff)
return 0;
std::memcpy(buf, node->data.data() + off, static_cast<int>(endoff - off));
node->stat.st_atim = now();
return static_cast<int>(endoff - off);
}
static int write(const char *path, const char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
fuse_off_t endoff = off + static_cast<fuse_off_t>(size);
if (SIZE_MAX < endoff)
return -EFBIG;
if (node->data.size() < endoff)
node->resize(static_cast<size_t>(endoff), true);
std::memcpy(node->data.data() + off, buf, static_cast<int>(endoff - off));
node->stat.st_ctim = node->stat.st_mtim = now();
#if defined(FSP_FUSE_USE_STAT_EX)
node->stat.st_flags |= UF_ARCHIVE;
#endif
return static_cast<int>(endoff - off);
}
static int statfs(const char *path, struct fuse_statvfs *stbuf)
{
std::memset(stbuf, 0, sizeof *stbuf);
return 0;
}
static int flush(const char *path, struct fuse_file_info *fi)
{
return -ENOSYS;
}
static int release(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->close_node(fi);
}
static int setxattr(const char *path, const char *name0, const char *value, size_t size,
int flags)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (0 == std::strcmp("com.apple.ResourceFork", name0))
return -ENOTSUP;
std::string name = name0;
if (XATTR_CREATE == flags)
{
if (node->xattrmap.end() != node->xattrmap.find(name))
return -EEXIST;
}
else if (XATTR_REPLACE == flags)
{
if (node->xattrmap.end() == node->xattrmap.find(name))
return -ENOATTR;
}
node->xattrmap[name].assign(value, value + size);
return 0;
}
static int getxattr(const char *path, const char *name0, char *value, size_t size)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (0 == std::strcmp("com.apple.ResourceFork", name0))
return -ENOTSUP;
std::string name = name0;
auto iter = node->xattrmap.find(name);
if (node->xattrmap.end() == iter)
return -ENOATTR;
if (0 != size)
{
if (iter->second.size() > size)
return -ERANGE;
std::memcpy(value, iter->second.data(), iter->second.size());
}
return static_cast<int>(iter->second.size());
}
static int listxattr(const char *path, char *namebuf, size_t size)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
size_t copysize = 0;
for (auto elem : node->xattrmap)
{
size_t namesize = elem.first.size() + 1;
if (0 != size)
{
if (copysize + namesize > size)
return -ERANGE;
std::memcpy(namebuf + copysize, elem.first.c_str(), namesize);
copysize += namesize;
}
}
return static_cast<int>(copysize);
}
static int removexattr(const char *path, const char *name0)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (0 == std::strcmp("com.apple.ResourceFork", name0))
return -ENOTSUP;
std::string name = name0;
return node->xattrmap.erase(name) ? 0 : -ENOATTR;
}
static int opendir(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->open_node(path, true, fi);
}
static int readdir(const char *path, void *buf, fuse_fill_dir_t filler, fuse_off_t off,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
filler(buf, ".", &node->stat, 0);
filler(buf, "..", nullptr, 0);
for (auto elem : node->childmap)
if (0 != filler(buf, elem.first.c_str(), &elem.second->stat, 0))
break;
return 0;
}
static int releasedir(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->close_node(fi);
}
static void *init(struct fuse_conn_info *conn)
{
#if defined(FSP_FUSE_CAP_READDIR_PLUS)
conn->want |= (conn->capable & FSP_FUSE_CAP_READDIR_PLUS);
#endif
#if defined(FSP_FUSE_USE_STAT_EX) && defined(FSP_FUSE_CAP_STAT_EX)
conn->want |= (conn->capable & FSP_FUSE_CAP_STAT_EX);
#endif
return getself();
}
static int utimens(const char *path, const struct fuse_timespec tmsp[2])
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (tmsp)
{
node->stat.st_ctim = now();
node->stat.st_atim = tmsp[0];
node->stat.st_mtim = tmsp[1];
}
else
node->stat.st_ctim = node->stat.st_atim = node->stat.st_mtim = now();
return 0;
}
static int setcrtime(const char *path, const struct fuse_timespec *tmsp)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (tmsp)
{
node->stat.st_ctim = now();
node->stat.st_birthtim = tmsp[0];
}
else
node->stat.st_ctim = node->stat.st_birthtim = now();
return 0;
}
#if defined(FSP_FUSE_USE_STAT_EX)
static int chflags(const char *path, uint32_t flags)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
node->stat.st_flags = flags;
node->stat.st_ctim = now();
return 0;
}
#endif
std::tuple<std::shared_ptr<node_t>, std::string, std::shared_ptr<node_t>>
lookup_node(const char *path, node_t *ancestor = nullptr)
{
auto prnt = _root;
std::string name;
auto node = prnt;
for (const char *part = path, *p; *part; part = p + !!(*p))
{
for (p = part; *p && '/' != *p; p++)
;
if (part == p)
continue;
prnt = node;
if (!node)
break;
name.assign(part, p);
auto iter = node->childmap.find(name);
node = node->childmap.end() != iter ? iter->second : nullptr;
if (ancestor && node.get() == ancestor)
{
name.assign(""); // special case loop condition
break;
}
}
return std::make_tuple(prnt, name, node);
}
int make_node(const char *path, fuse_mode_t mode, fuse_dev_t dev, const char *data = nullptr)
{
auto lookup = lookup_node(path);
auto prnt = std::get<0>(lookup);
auto name = std::get<1>(lookup);
auto node = std::get<2>(lookup);
if (!prnt)
return -ENOENT;
if (node)
return -EEXIST;
fuse_context *context = fuse_get_context();
node = std::make_shared<node_t>(++_ino, mode, context->uid, context->gid, dev);
#if defined(FSP_FUSE_USE_STAT_EX)
if (S_IFDIR != (mode & S_IFMT))
node->stat.st_flags |= UF_ARCHIVE;
#endif
if (data)
{
node->resize(std::strlen(data), false);
std::memcpy(node->data.data(), data, node->data.size());
}
prnt->childmap[name] = node;
prnt->stat.st_ctim = prnt->stat.st_mtim = node->stat.st_ctim;
return 0;
}
int remove_node(const char *path, bool dir)
{
auto lookup = lookup_node(path);
auto prnt = std::get<0>(lookup);
auto name = std::get<1>(lookup);
auto node = std::get<2>(lookup);
if (!node)
return -ENOENT;
if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT))
return -EISDIR;
if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT))
return -ENOTDIR;
if (0 < node->childmap.size())
return -ENOTEMPTY;
node->stat.st_nlink--;
prnt->childmap.erase(name);
node->stat.st_ctim = prnt->stat.st_ctim = prnt->stat.st_mtim = now();
return 0;
}
int open_node(const char *path, bool dir, struct fuse_file_info *fi)
{
auto node = std::get<2>(lookup_node(path));
if (!node)
return -ENOENT;
if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT))
return -EISDIR;
if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT))
return -ENOTDIR;
// A file descriptor is a raw pointer to a shared_ptr.
// This has the effect of incrementing the shared_ptr
// refcount, thus keeping an open node around even
// if the node is unlinked.
fi->fh = (uint64_t)(uintptr_t)new std::shared_ptr<node_t>(node);
return 0;
}
int close_node(struct fuse_file_info *fi)
{
delete (std::shared_ptr<node_t> *)(uintptr_t)fi->fh;
return 0;
}
std::shared_ptr<node_t> get_node(const char *path, struct fuse_file_info *fi = nullptr)
{
if (!fi)
return std::get<2>(lookup_node(path));
else
return *(std::shared_ptr<node_t> *)(uintptr_t)fi->fh;
}
private:
std::mutex _mutex;
fuse_ino_t _ino;
std::shared_ptr<node_t> _root;
};
int main(int argc, char *argv[])
{
return memfs().main(argc, argv);
}

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "memfs-fuse", "memfs-fuse.vcxproj", "{CF538F42-C714-4653-B351-E72FD7B0B217}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.ActiveCfg = Debug|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.Build.0 = Debug|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.ActiveCfg = Debug|Win32
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.Build.0 = Debug|Win32
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.ActiveCfg = Release|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.Build.0 = Release|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.ActiveCfg = Release|Win32
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,189 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{CF538F42-C714-4653-B351-E72FD7B0B217}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>memfsfuse</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="compat.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="memfs-fuse.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="compat.h">
<Filter>Source</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="memfs-fuse.cpp">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
usage:
@echo "make cygfuse3|winfsp-fuse3" 1>&2
@echo "" 1>&2
@echo " cygfuse3 Link with CYGFUSE3" 1>&2
@echo " winfsp-fuse3 Link with WinFsp-FUSE3" 1>&2
@exit 2
cygfuse3: memfs-cygfuse3
winfsp-fuse3: memfs-winfsp-fuse3
memfs-cygfuse3: memfs-fuse3.cpp
g++ $^ -o $@ -g -Wall -std=gnu++17 `pkg-config fuse3 --cflags --libs`
memfs-winfsp-fuse3: export PKG_CONFIG_PATH=$(PWD)/winfsp.install/lib
memfs-winfsp-fuse3: memfs-fuse3.cpp
ln -nsf "`regtool --wow32 get '/HKLM/Software/WinFsp/InstallDir' | cygpath -au -f -`" winfsp.install
g++ $^ -o $@ -g -Wall -std=gnu++17 `pkg-config fuse3 --cflags --libs`

View File

@ -0,0 +1,7 @@
`Memfs-fuse3` is an in-memory FUSE3 file system.
It can be built with the following tools:
- Using Visual Studio (`memfs-fuse3.sln`).
- Using Cygwin GCC and linking directly with the WinFsp DLL (`make winfsp-fuse3`).
- Using Cygwin GCC and linking to CYGFUSE3 (`make cygfuse3`).

View File

@ -0,0 +1,104 @@
/**
* @file compat.h
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#ifndef COMPAT_H_INCLUDED
#define COMPAT_H_INCLUDED
#if defined(_WIN32) && defined(FSP_FUSE_SYM)
#include <winfsp/winfsp.h>
#undef fuse_main
#define fuse_main(argc, argv, ops, data)\
(FspLoad(0), fuse_main_real(argc, argv, ops, sizeof *(ops), data))
#endif
#if !defined(_WIN32) && !defined(fuse_stat)
#define fuse_uid_t uid_t
#define fuse_gid_t gid_t
#define fuse_pid_t pid_t
#define fuse_dev_t dev_t
#define fuse_mode_t mode_t
#define fuse_nlink_t nlink_t
#define fuse_off_t off_t
#define fuse_fsblkcnt_t fsblkcnt_t
#define fuse_fsfilcnt_t fsfilcnt_t
#define fuse_blksize_t blksize_t
#define fuse_blkcnt_t blkcnt_t
#define fuse_timespec timespec
#define fuse_stat stat
#define fuse_statvfs statvfs
#define fuse_flock flock
#define fuse_iovec iovec
#endif
#if !defined(S_IFMT)
#define S_IFMT 0170000
#endif
#if !defined(S_IFDIR)
#define S_IFDIR 0040000
#endif
#if !defined(S_IFCHR)
#define S_IFCHR 0020000
#endif
#if !defined(S_IFBLK)
#define S_IFBLK 0060000
#endif
#if !defined(S_IFREG)
#define S_IFREG 0100000
#endif
#if !defined(S_IFLNK)
#define S_IFLNK 0120000
#endif
#if !defined(S_IFSOCK)
#define S_IFSOCK 0140000
#endif
#if !defined(S_IFIFO)
#define S_IFIFO 0010000
#endif
#if defined(__APPLE__)
#define st_atim st_atimespec
#define st_ctim st_ctimespec
#define st_mtim st_mtimespec
#endif
#if defined(__APPLE__) || defined(__linux__) || defined(__CYGWIN__)
#include <sys/xattr.h>
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(_WIN32)
#define XATTR_CREATE 1
#define XATTR_REPLACE 2
#endif
#if !defined(ENOATTR)
#define ENOATTR ENODATA
#elif !defined(ENODATA)
#define ENODATA ENOATTR
#endif
#endif

View File

@ -0,0 +1,619 @@
/**
* @file memfs-fuse3.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <cerrno>
#include <chrono>
#include <cstring>
#include <algorithm>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include <fuse.h>
#include "compat.h"
class memfs
{
public:
memfs() : _ino(1), _root(std::make_shared<node_t>(_ino, S_IFDIR | 00777, 0, 0))
{
}
int main(int argc, char *argv[])
{
static fuse_operations ops =
{
getattr,
readlink,
mknod,
mkdir,
unlink,
rmdir,
symlink,
rename,
link,
chmod,
chown,
truncate,
open,
read,
write,
statfs,
flush,
release,
0, // fsync
setxattr,
getxattr,
listxattr,
removexattr,
opendir,
readdir,
releasedir,
0, // fsyncdir
init,
0, // destroy
0, // access
0, // create
0, // lock
utimens,
0, // bmap
#if 0
ioctl,
#endif
};
return fuse_main(argc, argv, &ops, this);
}
private:
struct node_t
{
node_t(fuse_ino_t ino, fuse_mode_t mode, fuse_uid_t uid, fuse_gid_t gid, fuse_dev_t dev = 0)
: stat()
{
stat.st_ino = ino;
stat.st_mode = mode;
stat.st_nlink = 1;
stat.st_uid = uid;
stat.st_gid = gid;
stat.st_rdev = dev;
stat.st_atim = stat.st_mtim = stat.st_ctim = now();
}
void resize(size_t size, bool capacity)
{
if (capacity)
{
const size_t unit = 64 * 1024;
size_t newcap = (size + unit - 1) / unit * unit;
size_t oldcap = data.capacity();
if (newcap > oldcap)
data.reserve(newcap);
else if (newcap < oldcap)
{
data.resize(newcap);
data.shrink_to_fit();
}
}
data.resize(size);
stat.st_size = size;
}
struct fuse_stat stat;
std::vector<uint8_t> data;
std::unordered_map<std::string, std::shared_ptr<node_t>> childmap;
std::unordered_map<std::string, std::vector<uint8_t>> xattrmap;
};
static fuse_timespec now()
{
using namespace std::chrono;
auto now = system_clock::now();
auto sec = floor<seconds>(now);
auto nsec = floor<nanoseconds>(now) - floor<nanoseconds>(sec);
return fuse_timespec
{
static_cast<decltype(fuse_timespec::tv_sec)>(sec.time_since_epoch().count()),
/* std::chrono epoch is UNIX epoch in C++20 */
static_cast<decltype(fuse_timespec::tv_nsec)>(nsec.count()),
};
}
static memfs *getself()
{
return static_cast<memfs *>(fuse_get_context()->private_data);
}
static int getattr(const char *path, struct fuse_stat *stbuf, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
*stbuf = node->stat;
return 0;
}
static int readlink(const char *path, char *buf, size_t size)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (S_IFLNK != (node->stat.st_mode & S_IFMT))
return EINVAL;
size = (std::min)(size - 1, node->data.size());
std::memcpy(buf, node->data.data(), size);
buf[size] = '\0';
return 0;
}
static int mknod(const char *path, fuse_mode_t mode, fuse_dev_t dev)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->make_node(path, mode, dev);
}
static int mkdir(const char *path, fuse_mode_t mode)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->make_node(path, S_IFDIR | (mode & 07777), 0);
}
static int unlink(const char *path)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->remove_node(path, false);
}
static int rmdir(const char *path)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->remove_node(path, true);
}
static int symlink(const char *dstpath, const char *srcpath)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->make_node(srcpath, S_IFLNK | 00777, 0, dstpath);
}
static int rename(const char *oldpath, const char *newpath, unsigned int flags)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto oldlookup = self->lookup_node(oldpath);
auto oldprnt = std::get<0>(oldlookup);
auto oldname = std::get<1>(oldlookup);
auto oldnode = std::get<2>(oldlookup);
if (!oldnode)
return -ENOENT;
auto newlookup = self->lookup_node(newpath);
auto newprnt = std::get<0>(newlookup);
auto newname = std::get<1>(newlookup);
auto newnode = std::get<2>(newlookup);
if (!newprnt)
return -ENOENT;
if (newname.empty())
// guard against directory loop creation
return -EINVAL;
if (oldprnt == newprnt && oldname == newname)
return 0;
if (newnode)
{
if (int errc = self->remove_node(newpath, S_IFDIR == (oldnode->stat.st_mode & S_IFMT)))
return errc;
}
oldprnt->childmap.erase(oldname);
newprnt->childmap[newname] = oldnode;
return 0;
}
static int link(const char *oldpath, const char *newpath)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto oldlookup = self->lookup_node(oldpath);
auto oldnode = std::get<2>(oldlookup);
if (!oldnode)
return -ENOENT;
auto newlookup = self->lookup_node(newpath);
auto newprnt = std::get<0>(newlookup);
auto newname = std::get<1>(newlookup);
auto newnode = std::get<2>(newlookup);
if (!newprnt)
return -ENOENT;
if (newnode)
return -EEXIST;
oldnode->stat.st_nlink++;
newprnt->childmap[newname] = oldnode;
oldnode->stat.st_ctim = newprnt->stat.st_ctim = newprnt->stat.st_mtim = now();
return 0;
}
static int chmod(const char *path, fuse_mode_t mode,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
node->stat.st_mode = (node->stat.st_mode & S_IFMT) | (mode & 07777);
node->stat.st_ctim = now();
return 0;
}
static int chown(const char *path, fuse_uid_t uid, fuse_gid_t gid,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
if (-1 != uid)
node->stat.st_uid = uid;
if (-1 != gid)
node->stat.st_gid = gid;
node->stat.st_ctim = now();
return 0;
}
static int truncate(const char *path, fuse_off_t size,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
if (SIZE_MAX < size)
return -EFBIG;
node->resize(static_cast<size_t>(size), true);
node->stat.st_ctim = node->stat.st_mtim = now();
return 0;
}
static int open(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->open_node(path, false, fi);
}
static int read(const char *path, char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
fuse_off_t endoff = (std::min)(
off + static_cast<fuse_off_t>(size), static_cast<fuse_off_t>(node->data.size()));
if (off > endoff)
return 0;
std::memcpy(buf, node->data.data() + off, static_cast<int>(endoff - off));
node->stat.st_atim = now();
return static_cast<int>(endoff - off);
}
static int write(const char *path, const char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
fuse_off_t endoff = off + static_cast<fuse_off_t>(size);
if (SIZE_MAX < endoff)
return -EFBIG;
if (node->data.size() < endoff)
node->resize(static_cast<size_t>(endoff), true);
std::memcpy(node->data.data() + off, buf, static_cast<int>(endoff - off));
node->stat.st_ctim = node->stat.st_mtim = now();
return static_cast<int>(endoff - off);
}
static int statfs(const char *path, struct fuse_statvfs *stbuf)
{
std::memset(stbuf, 0, sizeof *stbuf);
return 0;
}
static int flush(const char *path, struct fuse_file_info *fi)
{
return -ENOSYS;
}
static int release(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->close_node(fi);
}
static int setxattr(const char *path, const char *name0, const char *value, size_t size,
int flags)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (0 == std::strcmp("com.apple.ResourceFork", name0))
return -ENOTSUP;
std::string name = name0;
if (XATTR_CREATE == flags)
{
if (node->xattrmap.end() != node->xattrmap.find(name))
return -EEXIST;
}
else if (XATTR_REPLACE == flags)
{
if (node->xattrmap.end() == node->xattrmap.find(name))
return -ENOATTR;
}
node->xattrmap[name].assign(value, value + size);
return 0;
}
static int getxattr(const char *path, const char *name0, char *value, size_t size)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (0 == std::strcmp("com.apple.ResourceFork", name0))
return -ENOTSUP;
std::string name = name0;
auto iter = node->xattrmap.find(name);
if (node->xattrmap.end() == iter)
return -ENOATTR;
if (0 != size)
{
if (iter->second.size() > size)
return -ERANGE;
std::memcpy(value, iter->second.data(), iter->second.size());
}
return static_cast<int>(iter->second.size());
}
static int listxattr(const char *path, char *namebuf, size_t size)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
size_t copysize = 0;
for (auto elem : node->xattrmap)
{
size_t namesize = elem.first.size() + 1;
if (0 != size)
{
if (copysize + namesize > size)
return -ERANGE;
std::memcpy(namebuf + copysize, elem.first.c_str(), namesize);
copysize += namesize;
}
}
return static_cast<int>(copysize);
}
static int removexattr(const char *path, const char *name0)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path);
if (!node)
return -ENOENT;
if (0 == std::strcmp("com.apple.ResourceFork", name0))
return -ENOTSUP;
std::string name = name0;
return node->xattrmap.erase(name) ? 0 : -ENOATTR;
}
static int opendir(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->open_node(path, true, fi);
}
static int readdir(const char *path, void *buf, fuse_fill_dir_t filler, fuse_off_t off,
struct fuse_file_info *fi, enum fuse_readdir_flags)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
filler(buf, ".", &node->stat, 0, FUSE_FILL_DIR_PLUS);
filler(buf, "..", nullptr, 0, FUSE_FILL_DIR_PLUS);
for (auto elem : node->childmap)
if (0 != filler(buf, elem.first.c_str(), &elem.second->stat, 0, FUSE_FILL_DIR_PLUS))
break;
return 0;
}
static int releasedir(const char *path, struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
return self->close_node(fi);
}
static void *init(struct fuse_conn_info *conn,
struct fuse_config *conf)
{
conn->want |= (conn->capable & FUSE_CAP_READDIRPLUS);
return getself();
}
static int utimens(const char *path, const struct fuse_timespec tmsp[2],
struct fuse_file_info *fi)
{
auto self = getself();
std::lock_guard<std::mutex> lock(self->_mutex);
auto node = self->get_node(path, fi);
if (!node)
return -ENOENT;
if (tmsp)
{
node->stat.st_ctim = now();
node->stat.st_atim = tmsp[0];
node->stat.st_mtim = tmsp[1];
}
else
node->stat.st_ctim = node->stat.st_atim = node->stat.st_mtim = now();
return 0;
}
#if 0
static int ioctl(const char *path, int cmd, void *arg, struct fuse_file_info *fi,
unsigned int flags, void *data)
{
return -ENOSYS;
}
#endif
std::tuple<std::shared_ptr<node_t>, std::string, std::shared_ptr<node_t>>
lookup_node(const char *path, node_t *ancestor = nullptr)
{
auto prnt = _root;
std::string name;
auto node = prnt;
for (const char *part = path, *p; *part; part = p + !!(*p))
{
for (p = part; *p && '/' != *p; p++)
;
if (part == p)
continue;
prnt = node;
if (!node)
break;
name.assign(part, p);
auto iter = node->childmap.find(name);
node = node->childmap.end() != iter ? iter->second : nullptr;
if (ancestor && node.get() == ancestor)
{
name.assign(""); // special case loop condition
break;
}
}
return std::make_tuple(prnt, name, node);
}
int make_node(const char *path, fuse_mode_t mode, fuse_dev_t dev, const char *data = nullptr)
{
auto lookup = lookup_node(path);
auto prnt = std::get<0>(lookup);
auto name = std::get<1>(lookup);
auto node = std::get<2>(lookup);
if (!prnt)
return -ENOENT;
if (node)
return -EEXIST;
fuse_context *context = fuse_get_context();
node = std::make_shared<node_t>(++_ino, mode, context->uid, context->gid, dev);
if (data)
{
node->resize(std::strlen(data), false);
std::memcpy(node->data.data(), data, node->data.size());
}
prnt->childmap[name] = node;
prnt->stat.st_ctim = prnt->stat.st_mtim = node->stat.st_ctim;
return 0;
}
int remove_node(const char *path, bool dir)
{
auto lookup = lookup_node(path);
auto prnt = std::get<0>(lookup);
auto name = std::get<1>(lookup);
auto node = std::get<2>(lookup);
if (!node)
return -ENOENT;
if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT))
return -EISDIR;
if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT))
return -ENOTDIR;
if (0 < node->childmap.size())
return -ENOTEMPTY;
node->stat.st_nlink--;
prnt->childmap.erase(name);
node->stat.st_ctim = prnt->stat.st_ctim = prnt->stat.st_mtim = now();
return 0;
}
int open_node(const char *path, bool dir, struct fuse_file_info *fi)
{
auto node = std::get<2>(lookup_node(path));
if (!node)
return -ENOENT;
if (!dir && S_IFDIR == (node->stat.st_mode & S_IFMT))
return -EISDIR;
if (dir && S_IFDIR != (node->stat.st_mode & S_IFMT))
return -ENOTDIR;
// A file descriptor is a raw pointer to a shared_ptr.
// This has the effect of incrementing the shared_ptr
// refcount, thus keeping an open node around even
// if the node is unlinked.
fi->fh = (uint64_t)(uintptr_t)new std::shared_ptr<node_t>(node);
return 0;
}
int close_node(struct fuse_file_info *fi)
{
delete (std::shared_ptr<node_t> *)(uintptr_t)fi->fh;
return 0;
}
std::shared_ptr<node_t> get_node(const char *path, struct fuse_file_info *fi = nullptr)
{
if (!fi)
return std::get<2>(lookup_node(path));
else
return *(std::shared_ptr<node_t> *)(uintptr_t)fi->fh;
}
private:
std::mutex _mutex;
fuse_ino_t _ino;
std::shared_ptr<node_t> _root;
};
int main(int argc, char *argv[])
{
return memfs().main(argc, argv);
}

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "memfs-fuse3", "memfs-fuse3.vcxproj", "{CF538F42-C714-4653-B351-E72FD7B0B217}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.ActiveCfg = Debug|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x64.Build.0 = Debug|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.ActiveCfg = Debug|Win32
{CF538F42-C714-4653-B351-E72FD7B0B217}.Debug|x86.Build.0 = Debug|Win32
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.ActiveCfg = Release|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x64.Build.0 = Release|x64
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.ActiveCfg = Release|Win32
{CF538F42-C714-4653-B351-E72FD7B0B217}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,189 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{CF538F42-C714-4653-B351-E72FD7B0B217}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>memfsfuse3</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4018</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="compat.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="memfs-fuse3.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="compat.h">
<Filter>Source</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="memfs-fuse3.cpp">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,241 @@
/**
* @file memfs-main.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <winfsp/winfsp.h>
#include "memfs.h"
#define PROGNAME "memfs"
#define info(format, ...) FspServiceLog(EVENTLOG_INFORMATION_TYPE, format, __VA_ARGS__)
#define warn(format, ...) FspServiceLog(EVENTLOG_WARNING_TYPE, format, __VA_ARGS__)
#define fail(format, ...) FspServiceLog(EVENTLOG_ERROR_TYPE, format, __VA_ARGS__)
#define argtos(v) if (arge > ++argp) v = *argp; else goto usage
#define argtol(v) if (arge > ++argp) v = wcstol_deflt(*argp, v); else goto usage
static ULONG wcstol_deflt(wchar_t *w, ULONG deflt)
{
wchar_t *endp;
ULONG ul = wcstol(w, &endp, 0);
return L'\0' != w[0] && L'\0' == *endp ? ul : deflt;
}
NTSTATUS SvcStart(FSP_SERVICE *Service, ULONG argc, PWSTR *argv)
{
wchar_t **argp, **arge;
ULONG DebugFlags = 0;
PWSTR DebugLogFile = 0;
ULONG Flags = MemfsDisk;
ULONG OtherFlags = 0;
ULONG FileInfoTimeout = INFINITE;
ULONG MaxFileNodes = 1024;
ULONG MaxFileSize = 16 * 1024 * 1024;
ULONG SlowioMaxDelay = 0; /* -M: maximum slow IO delay in millis */
ULONG SlowioPercentDelay = 0; /* -P: percent of slow IO to make pending */
ULONG SlowioRarefyDelay = 0; /* -R: adjust the rarity of pending slow IO */
PWSTR FileSystemName = 0;
PWSTR MountPoint = 0;
PWSTR VolumePrefix = 0;
PWSTR RootSddl = 0;
HANDLE DebugLogHandle = INVALID_HANDLE_VALUE;
MEMFS *Memfs = 0;
NTSTATUS Result;
for (argp = argv + 1, arge = argv + argc; arge > argp; argp++)
{
if (L'-' != argp[0][0])
break;
switch (argp[0][1])
{
case L'?':
goto usage;
case L'd':
argtol(DebugFlags);
break;
case L'D':
argtos(DebugLogFile);
break;
case L'f':
OtherFlags = MemfsFlushAndPurgeOnCleanup;
break;
case L'F':
argtos(FileSystemName);
break;
case L'i':
OtherFlags = MemfsCaseInsensitive;
break;
case L'm':
argtos(MountPoint);
break;
case L'M':
argtol(SlowioMaxDelay);
break;
case L'n':
argtol(MaxFileNodes);
break;
case L'P':
argtol(SlowioPercentDelay);
break;
case L'R':
argtol(SlowioRarefyDelay);
break;
case L'S':
argtos(RootSddl);
break;
case L's':
argtol(MaxFileSize);
break;
case L't':
argtol(FileInfoTimeout);
break;
case L'u':
argtos(VolumePrefix);
if (0 != VolumePrefix && L'\0' != VolumePrefix[0])
Flags = MemfsNet;
break;
default:
goto usage;
}
}
if (arge > argp)
goto usage;
if (MemfsDisk == Flags && 0 == MountPoint)
goto usage;
if (0 != DebugLogFile)
{
if (0 == wcscmp(L"-", DebugLogFile))
DebugLogHandle = GetStdHandle(STD_ERROR_HANDLE);
else
DebugLogHandle = CreateFileW(
DebugLogFile,
FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
0);
if (INVALID_HANDLE_VALUE == DebugLogHandle)
{
fail(L"cannot open debug log file");
goto usage;
}
FspDebugLogSetHandle(DebugLogHandle);
}
Result = MemfsCreateFunnel(
Flags | OtherFlags,
FileInfoTimeout,
MaxFileNodes,
MaxFileSize,
SlowioMaxDelay,
SlowioPercentDelay,
SlowioRarefyDelay,
FileSystemName,
VolumePrefix,
RootSddl,
&Memfs);
if (!NT_SUCCESS(Result))
{
fail(L"cannot create MEMFS");
goto exit;
}
FspFileSystemSetDebugLog(MemfsFileSystem(Memfs), DebugFlags);
if (0 != MountPoint && L'\0' != MountPoint[0])
{
Result = FspFileSystemSetMountPoint(MemfsFileSystem(Memfs),
L'*' == MountPoint[0] && L'\0' == MountPoint[1] ? 0 : MountPoint);
if (!NT_SUCCESS(Result))
{
fail(L"cannot mount MEMFS");
goto exit;
}
}
Result = MemfsStart(Memfs);
if (!NT_SUCCESS(Result))
{
fail(L"cannot start MEMFS");
goto exit;
}
MountPoint = FspFileSystemMountPoint(MemfsFileSystem(Memfs));
info(L"%s -t %ld -n %ld -s %ld%s%s%s%s%s%s",
L"" PROGNAME, FileInfoTimeout, MaxFileNodes, MaxFileSize,
RootSddl ? L" -S " : L"", RootSddl ? RootSddl : L"",
0 != VolumePrefix && L'\0' != VolumePrefix[0] ? L" -u " : L"",
0 != VolumePrefix && L'\0' != VolumePrefix[0] ? VolumePrefix : L"",
MountPoint ? L" -m " : L"", MountPoint ? MountPoint : L"");
Service->UserContext = Memfs;
Result = STATUS_SUCCESS;
exit:
if (!NT_SUCCESS(Result) && 0 != Memfs)
MemfsDelete(Memfs);
return Result;
usage:
static wchar_t usage[] = L""
"usage: %s OPTIONS\n"
"\n"
"options:\n"
" -d DebugFlags [-1: enable all debug logs]\n"
" -D DebugLogFile [file path; use - for stderr]\n"
" -i [case insensitive file system]\n"
" -f [flush and purge cache on cleanup]\n"
" -t FileInfoTimeout [millis]\n"
" -n MaxFileNodes\n"
" -s MaxFileSize [bytes]\n"
" -M MaxDelay [maximum slow IO delay in millis]\n"
" -P PercentDelay [percent of slow IO to make pending]\n"
" -R RarefyDelay [adjust the rarity of pending slow IO]\n"
" -F FileSystemName\n"
" -S RootSddl [file rights: FA, etc; NO generic rights: GA, etc.]\n"
" -u \\Server\\Share [UNC prefix (single backslash)]\n"
" -m MountPoint [X:|* (required if no UNC prefix)]\n";
fail(usage, L"" PROGNAME);
return STATUS_UNSUCCESSFUL;
}
NTSTATUS SvcStop(FSP_SERVICE *Service)
{
MEMFS *Memfs = Service->UserContext;
MemfsStop(Memfs);
MemfsDelete(Memfs);
return STATUS_SUCCESS;
}
int wmain(int argc, wchar_t **argv)
{
return FspServiceRun(L"" PROGNAME, SvcStart, SvcStop, 0);
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,79 @@
/**
* @file memfs.h
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#ifndef MEMFS_H_INCLUDED
#define MEMFS_H_INCLUDED
#include <winfsp/winfsp.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _MEMFS MEMFS;
enum
{
MemfsDisk = 0x00000000,
MemfsNet = 0x00000001,
MemfsDeviceMask = 0x0000000f,
MemfsCaseInsensitive = 0x80000000,
MemfsFlushAndPurgeOnCleanup = 0x40000000,
MemfsLegacyUnlinkRename = 0x20000000,
};
#define MemfsCreate(Flags, FileInfoTimeout, MaxFileNodes, MaxFileSize, VolumePrefix, RootSddl, PMemfs)\
MemfsCreateFunnel(\
Flags,\
FileInfoTimeout,\
MaxFileNodes,\
MaxFileSize,\
0/*SlowioMaxDelay*/,\
0/*SlowioPercentDelay*/,\
0/*SlowioRarefyDelay*/,\
0/*FileSystemName*/,\
VolumePrefix,\
RootSddl,\
PMemfs)
NTSTATUS MemfsCreateFunnel(
ULONG Flags,
ULONG FileInfoTimeout,
ULONG MaxFileNodes,
ULONG MaxFileSize,
ULONG SlowioMaxDelay,
ULONG SlowioPercentDelay,
ULONG SlowioRarefyDelay,
PWSTR FileSystemName,
PWSTR VolumePrefix,
PWSTR RootSddl,
MEMFS **PMemfs);
VOID MemfsDelete(MEMFS *Memfs);
NTSTATUS MemfsStart(MEMFS *Memfs);
VOID MemfsStop(MEMFS *Memfs);
FSP_FILE_SYSTEM *MemfsFileSystem(MEMFS *Memfs);
NTSTATUS MemfsHeapConfigure(SIZE_T InitialSize, SIZE_T MaximumSize, SIZE_T Alignment);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,394 @@
/**
* @file Program.cs
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using Fsp;
using VolumeInfo = Fsp.Interop.VolumeInfo;
using FileInfo = Fsp.Interop.FileInfo;
using NotifyInfo = Fsp.Interop.NotifyInfo;
using NotifyAction = Fsp.Interop.NotifyAction;
using NotifyFilter = Fsp.Interop.NotifyFilter;
namespace notifyfs
{
class Notifyfs : FileSystemBase
{
public override Int32 Init(Object Host)
{
_Host = (FileSystemHost)Host;
_Host.SectorSize = ALLOCATION_UNIT;
_Host.SectorsPerAllocationUnit = 1;
_Host.FileInfoTimeout = 1000;
_Host.CaseSensitiveSearch = false;
_Host.CasePreservedNames = true;
_Host.UnicodeOnDisk = true;
_Host.PersistentAcls = false;
_Host.PostCleanupWhenModifiedOnly = true;
_Host.VolumeCreationTime = 0;
_Host.VolumeSerialNumber = 0;
return STATUS_SUCCESS;
}
public override Int32 Mounted(Object Host)
{
_Timer = new Timer(this.Tick, null, 0, 1000);
return STATUS_SUCCESS;
}
public override void Unmounted(Object Host)
{
WaitHandle Event = new ManualResetEvent(false);
_Timer.Dispose(Event);
Event.WaitOne();
}
public override Int32 GetVolumeInfo(
out VolumeInfo VolumeInfo)
{
VolumeInfo = default(VolumeInfo);
return STATUS_SUCCESS;
}
public override Int32 GetSecurityByName(
String FileName,
out UInt32 FileAttributes/* or ReparsePointIndex */,
ref Byte[] SecurityDescriptor)
{
int Index = FileLookup(FileName);
if (-1 == Index)
{
FileAttributes = default(UInt32);
return STATUS_OBJECT_NAME_NOT_FOUND;
}
FileAttributes = 0 == Index ? (UInt32)System.IO.FileAttributes.Directory : 0;
if (null != SecurityDescriptor)
SecurityDescriptor = DefaultSecurity;
return STATUS_SUCCESS;
}
public override Int32 Open(
String FileName,
UInt32 CreateOptions,
UInt32 GrantedAccess,
out Object FileNode,
out Object FileDesc,
out FileInfo FileInfo,
out String NormalizedName)
{
FileNode = default(Object);
FileDesc = default(Object);
FileInfo = default(FileInfo);
NormalizedName = default(String);
int Index = FileLookup(FileName);
if (-1 == Index)
return STATUS_OBJECT_NAME_NOT_FOUND;
FileNode = Index;
FillFileInfo(Index, out FileInfo);
return STATUS_SUCCESS;
}
public override Int32 Read(
Object FileNode,
Object FileDesc,
IntPtr Buffer,
UInt64 Offset,
UInt32 Length,
out UInt32 BytesTransferred)
{
int Index = (int)FileNode;
UInt64 EndOffset;
Byte[] Contents = FileContents(Index);
if (Offset >= (UInt64)Contents.Length)
{
BytesTransferred = 0;
return STATUS_END_OF_FILE;
}
EndOffset = Offset + Length;
if (EndOffset > (UInt64)Contents.Length)
EndOffset = (UInt64)Contents.Length;
BytesTransferred = (UInt32)(EndOffset - Offset);
Marshal.Copy(Contents, (int)Offset, Buffer, (int)BytesTransferred);
return STATUS_SUCCESS;
}
public override Int32 GetFileInfo(
Object FileNode,
Object FileDesc,
out FileInfo FileInfo)
{
int Index = (int)FileNode;
FillFileInfo(Index, out FileInfo);
return STATUS_SUCCESS;
}
public override Boolean ReadDirectoryEntry(
Object FileNode,
Object FileDesc,
String Pattern,
String Marker,
ref Object Context,
out String FileName,
out FileInfo FileInfo)
{
IEnumerator<String> Enumerator = (IEnumerator<String>)Context;
if (null == Enumerator)
{
List<String> ChildrenFileNames = new List<String>();
for (int Index = 1, Count = FileCount(); Count >= Index; Index++)
ChildrenFileNames.Add(String.Format("{0}", Index));
Context = Enumerator = ChildrenFileNames.GetEnumerator();
}
while (Enumerator.MoveNext())
{
FileName = Enumerator.Current;
FillFileInfo(int.Parse(FileName), out FileInfo);
return true;
}
FileName = default(String);
FileInfo = default(FileInfo);
return false;
}
private static int CountFromTicks(int Ticks)
{
/*
* The formula below produces the periodic sequence:
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
* ...
*/
int div10 = (Ticks % 20) / 10;
int mod10 = Ticks % 10;
int mdv10 = 1 - div10;
int mmd10 = 10 - mod10;
return mdv10 * mod10 + div10 * mmd10;
}
private int FileCount()
{
int Ticks = Thread.VolatileRead(ref _Ticks);
return CountFromTicks(Ticks);
}
private int FileLookup(String FileName)
{
FileName = FileName.Substring(1);
if ("" == FileName)
return 0; /* root */
int Count = FileCount();
Boolean Valid = int.TryParse(FileName, out int Index);
if (!Valid || 0 >= Index || Index > Count)
return -1; /* not found */
return Index; /* regular file named 1, 2, ..., Count */
}
private static Byte[] FileContents(int Index)
{
if (0 == Index)
return EmptyByteArray;
return Encoding.UTF8.GetBytes(String.Format("{0}\n", Index));
}
private static void FillFileInfo(int Index, out FileInfo FileInfo)
{
FileInfo = default(FileInfo);
FileInfo.FileAttributes = 0 == Index ? (UInt32)System.IO.FileAttributes.Directory : 0;
FileInfo.FileSize = (UInt64)FileContents(Index).Length;
FileInfo.AllocationSize = (FileInfo.FileSize + ALLOCATION_UNIT - 1)
/ ALLOCATION_UNIT * ALLOCATION_UNIT;
FileInfo.CreationTime =
FileInfo.LastAccessTime =
FileInfo.LastWriteTime =
FileInfo.ChangeTime = (UInt64)DateTime.Now.ToFileTimeUtc();
}
private void Tick(Object Context)
{
int Ticks = Interlocked.Increment(ref _Ticks);
int OldCount = CountFromTicks(Ticks - 1);
int NewCount = CountFromTicks(Ticks);
NotifyInfo[] NotifyInfo = new NotifyInfo[1];
if (OldCount < NewCount)
{
NotifyInfo[0].FileName = String.Format("\\{0}", NewCount);
NotifyInfo[0].Action = NotifyAction.Added;
NotifyInfo[0].Filter = NotifyFilter.ChangeFileName;
Console.Error.WriteLine("CREATE \\{0}", NewCount);
}
else if (OldCount > NewCount)
{
NotifyInfo[0].FileName = String.Format("\\{0}", OldCount);
NotifyInfo[0].Action = NotifyAction.Removed;
NotifyInfo[0].Filter = NotifyFilter.ChangeFileName;
Console.Error.WriteLine("REMOVE \\{0}", OldCount);
}
if (OldCount != NewCount)
{
if (STATUS_SUCCESS == _Host.NotifyBegin(500))
{
_Host.Notify(NotifyInfo);
_Host.NotifyEnd();
}
}
}
static Notifyfs()
{
RawSecurityDescriptor RootSecurityDescriptor = new RawSecurityDescriptor(
"O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;WD)");
DefaultSecurity = new Byte[RootSecurityDescriptor.BinaryLength];
RootSecurityDescriptor.GetBinaryForm(DefaultSecurity, 0);
}
private const int ALLOCATION_UNIT = 4096;
private static readonly Byte[] EmptyByteArray = new Byte[0];
private static readonly Byte[] DefaultSecurity;
private FileSystemHost _Host;
private Timer _Timer;
private int _Ticks;
}
class NotifyfsService : Service
{
private class CommandLineUsageException : Exception
{
public CommandLineUsageException(String Message = null) : base(Message)
{
HasMessage = null != Message;
}
public bool HasMessage;
}
private const String PROGNAME = "notifyfs-dotnet";
public NotifyfsService() : base("NotifyfsService")
{
}
protected override void OnStart(String[] Args)
{
try
{
String VolumePrefix = null;
String MountPoint = null;
FileSystemHost Host = null;
Notifyfs Notifyfs = null;
int I;
for (I = 1; Args.Length > I; I++)
{
String Arg = Args[I];
if ('-' != Arg[0])
break;
switch (Arg[1])
{
case '?':
throw new CommandLineUsageException();
case 'm':
argtos(Args, ref I, ref MountPoint);
break;
case 'u':
argtos(Args, ref I, ref VolumePrefix);
break;
default:
throw new CommandLineUsageException();
}
}
if (Args.Length > I)
throw new CommandLineUsageException();
if (null == MountPoint)
throw new CommandLineUsageException();
FileSystemHost.SetDebugLogFile("-");
Host = new FileSystemHost(Notifyfs = new Notifyfs());
Host.Prefix = VolumePrefix;
if (0 > Host.Mount(MountPoint))
throw new IOException("cannot mount file system");
MountPoint = Host.MountPoint();
_Host = Host;
Log(EVENTLOG_INFORMATION_TYPE, String.Format("{0}{1}{2} -m {3}",
PROGNAME,
null != VolumePrefix && 0 < VolumePrefix.Length ? " -u " : "",
null != VolumePrefix && 0 < VolumePrefix.Length ? VolumePrefix : "",
MountPoint));
}
catch (CommandLineUsageException ex)
{
Log(EVENTLOG_ERROR_TYPE, String.Format(
"{0}" +
"usage: {1} OPTIONS\n" +
"\n" +
"options:\n" +
" -u \\Server\\Share [UNC prefix (single backslash)]\n" +
" -m MountPoint [X:|*|directory]\n",
ex.HasMessage ? ex.Message + "\n" : "",
PROGNAME));
throw;
}
catch (Exception ex)
{
Log(EVENTLOG_ERROR_TYPE, String.Format("{0}", ex.Message));
throw;
}
}
protected override void OnStop()
{
_Host.Unmount();
_Host = null;
}
private static void argtos(String[] Args, ref int I, ref String V)
{
if (Args.Length > ++I)
V = Args[I];
else
throw new CommandLineUsageException();
}
private FileSystemHost _Host;
}
class Program
{
static void Main(string[] args)
{
Environment.ExitCode = new NotifyfsService().Run();
}
}
}

View File

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DA7C383A-D10F-4FB0-BDCB-E7A7C5D068AA}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>notifyfs</RootNamespace>
<AssemblyName>notifyfs-dotnet</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath>
<BaseIntermediateOutputPath>$(SolutionDir)build\$(ProjectName).build\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath>
<BaseIntermediateOutputPath>$(SolutionDir)build\$(ProjectName).build\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="winfsp-msil">
<HintPath>$(MSBuildProgramFiles32)\WinFsp\bin\winfsp-msil.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5.2 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30717.126
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "notifyfs-dotnet", "notifyfs-dotnet.csproj", "{DA7C383A-D10F-4FB0-BDCB-E7A7C5D068AA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DA7C383A-D10F-4FB0-BDCB-E7A7C5D068AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DA7C383A-D10F-4FB0-BDCB-E7A7C5D068AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DA7C383A-D10F-4FB0-BDCB-E7A7C5D068AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DA7C383A-D10F-4FB0-BDCB-E7A7C5D068AA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {18D87005-09CA-40CF-9B51-139B486AB8D0}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,508 @@
/**
* @file notifyfs.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <winfsp/winfsp.h>
#include <sddl.h>
#define DEBUGFLAGS 0
//#define DEBUGFLAGS -1
#define PROGNAME "notifyfs"
#define ALLOCATION_UNIT 4096
#define info(format, ...) FspServiceLog(EVENTLOG_INFORMATION_TYPE, format, __VA_ARGS__)
#define warn(format, ...) FspServiceLog(EVENTLOG_WARNING_TYPE, format, __VA_ARGS__)
#define fail(format, ...) FspServiceLog(EVENTLOG_ERROR_TYPE, format, __VA_ARGS__)
typedef struct
{
FSP_FILE_SYSTEM *FileSystem;
PTP_TIMER Timer;
UINT32 Ticks;
} NOTIFYFS;
static PSECURITY_DESCRIPTOR DefaultSecurity;
static ULONG DefaultSecuritySize;
static UINT32 CountFromTicks(UINT32 Ticks)
{
/*
* The formula below produces the periodic sequence:
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
* ...
*/
UINT32 div10 = (Ticks % 20) / 10;
UINT32 mod10 = Ticks % 10;
UINT32 mdv10 = 1 - div10;
UINT32 mmd10 = 10 - mod10;
return mdv10 * mod10 + div10 * mmd10;
}
static UINT32 FileCount(NOTIFYFS *Notifyfs)
{
UINT32 Ticks = InterlockedOr(&Notifyfs->Ticks, 0);
return CountFromTicks(Ticks);
}
static UINT32 FileLookup(NOTIFYFS *Notifyfs, PWSTR FileName)
{
FileName++;
PWSTR Endp;
UINT32 Count = FileCount(Notifyfs);
UINT32 Index = wcstoul(FileName, &Endp, 10);
if ('\0' != *Endp || (FileName != Endp && (0 == Index || Index > Count)))
return -1; /* not found */
if (FileName == Endp)
return 0; /* root */
return Index; /* regular file named 1, 2, ..., Count */
}
static UINT32 FileContents(UINT32 Index, WCHAR P[32])
{
WCHAR Buffer[32];
if (0 == P)
P = Buffer;
if (0 == Index)
P[0] = '\0';
else
wsprintfW(P, L"%u\n", (unsigned)Index);
return lstrlenW(P);
}
static VOID FillFileInfo(UINT32 Index, FSP_FSCTL_FILE_INFO *FileInfo)
{
FILETIME SystemTime;
GetSystemTimeAsFileTime(&SystemTime);
memset(FileInfo, 0, sizeof FileInfo);
FileInfo->FileAttributes = 0 == Index ? FILE_ATTRIBUTE_DIRECTORY : 0;
FileInfo->FileSize = FileContents(Index, 0);
FileInfo->AllocationSize = (FileInfo->FileSize + ALLOCATION_UNIT - 1)
/ ALLOCATION_UNIT * ALLOCATION_UNIT;
FileInfo->CreationTime =
FileInfo->LastAccessTime =
FileInfo->LastWriteTime =
FileInfo->ChangeTime = *(PUINT64)&SystemTime;
}
static BOOLEAN AddDirInfo(PWSTR FileName, UINT32 Index,
PVOID Buffer, ULONG Length, PULONG PBytesTransferred)
{
union
{
UINT8 B[FIELD_OFFSET(FSP_FSCTL_DIR_INFO, FileNameBuf) + MAX_PATH * sizeof(WCHAR)];
FSP_FSCTL_DIR_INFO D;
} DirInfoBuf;
FSP_FSCTL_DIR_INFO *DirInfo = &DirInfoBuf.D;
memset(DirInfo->Padding, 0, sizeof DirInfo->Padding);
if (0 != FileName)
lstrcpyW(DirInfo->FileNameBuf, FileName);
else
wsprintfW(DirInfo->FileNameBuf, L"%u", (unsigned)Index);
DirInfo->Size = (UINT16)(sizeof(FSP_FSCTL_DIR_INFO) + wcslen(DirInfo->FileNameBuf) * sizeof(WCHAR));
FillFileInfo(Index, &DirInfo->FileInfo);
return FspFileSystemAddDirInfo(DirInfo, Buffer, Length, PBytesTransferred);
}
static NTSTATUS GetVolumeInfo(FSP_FILE_SYSTEM *FileSystem,
FSP_FSCTL_VOLUME_INFO *VolumeInfo)
{
memset(VolumeInfo, 0, sizeof *VolumeInfo);
return STATUS_SUCCESS;
}
static NTSTATUS GetSecurityByName(FSP_FILE_SYSTEM *FileSystem,
PWSTR FileName, PUINT32 PFileAttributes,
PSECURITY_DESCRIPTOR SecurityDescriptor, SIZE_T *PSecurityDescriptorSize)
{
NOTIFYFS *Notifyfs = (NOTIFYFS *)FileSystem->UserContext;
UINT32 Index;
Index = FileLookup(Notifyfs, FileName);
if (-1 == Index)
return STATUS_OBJECT_NAME_NOT_FOUND;
if (0 != PFileAttributes)
*PFileAttributes = 0 == Index ? FILE_ATTRIBUTE_DIRECTORY : 0;
if (0 != PSecurityDescriptorSize)
{
if (DefaultSecuritySize > *PSecurityDescriptorSize)
{
*PSecurityDescriptorSize = DefaultSecuritySize;
return STATUS_BUFFER_OVERFLOW;
}
*PSecurityDescriptorSize = DefaultSecuritySize;
if (0 != SecurityDescriptor)
memcpy(SecurityDescriptor, DefaultSecurity, DefaultSecuritySize);
}
return STATUS_SUCCESS;
}
static NTSTATUS Create(FSP_FILE_SYSTEM *FileSystem,
PWSTR FileName, UINT32 CreateOptions, UINT32 GrantedAccess,
UINT32 FileAttributes, PSECURITY_DESCRIPTOR SecurityDescriptor, UINT64 AllocationSize,
PVOID *PFileContext, FSP_FSCTL_FILE_INFO *FileInfo)
{
return STATUS_INVALID_DEVICE_REQUEST;
}
static NTSTATUS Open(FSP_FILE_SYSTEM *FileSystem,
PWSTR FileName, UINT32 CreateOptions, UINT32 GrantedAccess,
PVOID *PFileContext, FSP_FSCTL_FILE_INFO *FileInfo)
{
NOTIFYFS *Notifyfs = (NOTIFYFS *)FileSystem->UserContext;
FSP_FSCTL_TRANSACT_FULL_CONTEXT *FullContext = (PVOID)PFileContext;
UINT32 Index;
Index = FileLookup(Notifyfs, FileName);
if (-1 == Index)
return STATUS_OBJECT_NAME_NOT_FOUND;
FullContext->UserContext = Index;
FullContext->UserContext2 = 0;
FillFileInfo(Index, FileInfo);
return STATUS_SUCCESS;
}
static NTSTATUS Overwrite(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, UINT32 FileAttributes, BOOLEAN ReplaceFileAttributes, UINT64 AllocationSize,
FSP_FSCTL_FILE_INFO *FileInfo)
{
return STATUS_INVALID_DEVICE_REQUEST;
}
static NTSTATUS Read(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, PVOID Buffer, UINT64 Offset, ULONG Length,
PULONG PBytesTransferred)
{
NOTIFYFS *Notifyfs = (NOTIFYFS *)FileSystem->UserContext;
FSP_FSCTL_TRANSACT_FULL_CONTEXT *FullContext = FileContext;
UINT32 Index = (UINT32)FullContext->UserContext;
UINT64 EndOffset;
WCHAR ContentBuf[32];
UINT32 ContentLen;
ContentLen = FileContents(Index, ContentBuf);
if (Offset >= ContentLen)
return STATUS_END_OF_FILE;
EndOffset = Offset + Length;
if (EndOffset > ContentLen)
EndOffset = ContentLen;
memcpy(Buffer, (PUINT8)ContentBuf + Offset, (size_t)(EndOffset - Offset));
*PBytesTransferred = (ULONG)(EndOffset - Offset);
return STATUS_SUCCESS;
}
static NTSTATUS GetFileInfo(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext,
FSP_FSCTL_FILE_INFO *FileInfo)
{
NOTIFYFS *Notifyfs = (NOTIFYFS *)FileSystem->UserContext;
FSP_FSCTL_TRANSACT_FULL_CONTEXT *FullContext = FileContext;
UINT32 Index = (UINT32)FullContext->UserContext;
FillFileInfo(Index, FileInfo);
return STATUS_SUCCESS;
}
static NTSTATUS ReadDirectory(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, PWSTR Pattern, PWSTR Marker,
PVOID Buffer, ULONG Length, PULONG PBytesTransferred)
{
NOTIFYFS *Notifyfs = (NOTIFYFS *)FileSystem->UserContext;
UINT32 Count = FileCount(Notifyfs);
UINT32 Index;
Index = 0 == Marker ? 1 : wcstoul(Marker, 0, 10) + 1;
for (; Count >= Index; Index++)
if (!AddDirInfo(0, Index, Buffer, Length, PBytesTransferred))
break;
FspFileSystemAddDirInfo(0, Buffer, Length, PBytesTransferred);
return STATUS_SUCCESS;
}
static FSP_FILE_SYSTEM_INTERFACE NotifyfsInterface =
{
.GetVolumeInfo = GetVolumeInfo,
.GetSecurityByName = GetSecurityByName,
.Create = Create,
.Open = Open,
.Overwrite = Overwrite,
.Read = Read,
.GetFileInfo = GetFileInfo,
.ReadDirectory = ReadDirectory,
};
static VOID CALLBACK NotifyfsTick(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_TIMER Timer)
{
NOTIFYFS *Notifyfs = Context;
UINT32 Ticks = InterlockedIncrement(&Notifyfs->Ticks);
UINT32 OldCount = CountFromTicks(Ticks - 1);
UINT32 NewCount = CountFromTicks(Ticks);
union
{
UINT8 B[FIELD_OFFSET(FSP_FSCTL_NOTIFY_INFO, FileNameBuf) + MAX_PATH * sizeof(WCHAR)];
FSP_FSCTL_NOTIFY_INFO V;
} NotifyInfoBuf;
FSP_FSCTL_NOTIFY_INFO *NotifyInfo = &NotifyInfoBuf.V;
memset(NotifyInfo, 0, sizeof NotifyInfo);
if (OldCount < NewCount)
{
wsprintfW(NotifyInfo->FileNameBuf, L"\\%u", (unsigned)NewCount);
NotifyInfo->Size = (UINT16)(sizeof(FSP_FSCTL_NOTIFY_INFO) +
wcslen(NotifyInfo->FileNameBuf) * sizeof(WCHAR));
NotifyInfo->Action = FILE_ACTION_ADDED;
NotifyInfo->Filter = FILE_NOTIFY_CHANGE_FILE_NAME;
FspDebugLog("CREATE \\%u\n", (unsigned)NewCount);
}
else if (OldCount > NewCount)
{
wsprintfW(NotifyInfo->FileNameBuf, L"\\%u", (unsigned)OldCount);
NotifyInfo->Size = (UINT16)(sizeof(FSP_FSCTL_NOTIFY_INFO) +
wcslen(NotifyInfo->FileNameBuf) * sizeof(WCHAR));
NotifyInfo->Action = FILE_ACTION_REMOVED;
NotifyInfo->Filter = FILE_NOTIFY_CHANGE_FILE_NAME;
FspDebugLog("REMOVE \\%u\n", (unsigned)OldCount);
}
if (OldCount != NewCount)
{
if (STATUS_SUCCESS == FspFileSystemNotifyBegin(Notifyfs->FileSystem, 500))
{
FspFileSystemNotify(Notifyfs->FileSystem, NotifyInfo, NotifyInfo->Size);
FspFileSystemNotifyEnd(Notifyfs->FileSystem);
}
}
}
static VOID NotifyfsDelete(NOTIFYFS *Notifyfs);
static NTSTATUS NotifyfsCreate(PWSTR VolumePrefix, PWSTR MountPoint, NOTIFYFS **PNotifyfs)
{
FSP_FSCTL_VOLUME_PARAMS VolumeParams;
NOTIFYFS *Notifyfs = 0;
INT64 TimerDue;
NTSTATUS Result;
*PNotifyfs = 0;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
L"O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FA;;;WD)", SDDL_REVISION_1,
&DefaultSecurity, &DefaultSecuritySize))
{
Result = FspNtStatusFromWin32(GetLastError());
goto exit;
}
Notifyfs = malloc(sizeof *Notifyfs);
if (0 == Notifyfs)
{
Result = STATUS_INSUFFICIENT_RESOURCES;
goto exit;
}
memset(Notifyfs, 0, sizeof *Notifyfs);
memset(&VolumeParams, 0, sizeof VolumeParams);
VolumeParams.SectorSize = ALLOCATION_UNIT;
VolumeParams.SectorsPerAllocationUnit = 1;
VolumeParams.VolumeCreationTime = 0;
VolumeParams.VolumeSerialNumber = 0;
VolumeParams.FileInfoTimeout = 1000;
VolumeParams.CaseSensitiveSearch = 0;
VolumeParams.CasePreservedNames = 1;
VolumeParams.UnicodeOnDisk = 1;
VolumeParams.PersistentAcls = 0;
VolumeParams.PostCleanupWhenModifiedOnly = 1;
VolumeParams.UmFileContextIsFullContext = 1;
if (0 != VolumePrefix)
wcscpy_s(VolumeParams.Prefix, sizeof VolumeParams.Prefix / sizeof(WCHAR), VolumePrefix);
wcscpy_s(VolumeParams.FileSystemName, sizeof VolumeParams.FileSystemName / sizeof(WCHAR),
L"" PROGNAME);
Result = FspFileSystemCreate(
VolumeParams.Prefix[0] ? L"" FSP_FSCTL_NET_DEVICE_NAME : L"" FSP_FSCTL_DISK_DEVICE_NAME,
&VolumeParams,
&NotifyfsInterface,
&Notifyfs->FileSystem);
if (!NT_SUCCESS(Result))
goto exit;
Notifyfs->FileSystem->UserContext = Notifyfs;
FspFileSystemSetDebugLog(Notifyfs->FileSystem, DEBUGFLAGS);
Result = FspFileSystemSetMountPoint(Notifyfs->FileSystem, MountPoint);
if (!NT_SUCCESS(Result))
goto exit;
Notifyfs->Timer = CreateThreadpoolTimer(NotifyfsTick, Notifyfs, 0);
if (0 == Notifyfs->Timer)
{
Result = FspNtStatusFromWin32(GetLastError());
goto exit;
}
TimerDue = -1000;
SetThreadpoolTimer(Notifyfs->Timer, (PVOID)&TimerDue, 1000, 0);
Result = STATUS_SUCCESS;
exit:
if (NT_SUCCESS(Result))
*PNotifyfs = Notifyfs;
else if (0 != Notifyfs)
NotifyfsDelete(Notifyfs);
return Result;
}
static VOID NotifyfsDelete(NOTIFYFS *Notifyfs)
{
if (0 != Notifyfs->Timer)
{
SetThreadpoolTimer(Notifyfs->Timer, 0, 0, 0);
WaitForThreadpoolTimerCallbacks(Notifyfs->Timer, TRUE);
CloseThreadpoolTimer(Notifyfs->Timer);
}
if (0 != Notifyfs->FileSystem)
FspFileSystemDelete(Notifyfs->FileSystem);
free(Notifyfs);
}
static NTSTATUS SvcStart(FSP_SERVICE *Service, ULONG argc, PWSTR *argv)
{
#define argtos(v) if (arge > ++argp) v = *argp; else goto usage
wchar_t **argp, **arge;
PWSTR VolumePrefix = 0;
PWSTR MountPoint = 0;
NOTIFYFS *Notifyfs = 0;
NTSTATUS Result;
for (argp = argv + 1, arge = argv + argc; arge > argp; argp++)
{
if (L'-' != argp[0][0])
break;
switch (argp[0][1])
{
case L'?':
goto usage;
case L'm':
argtos(MountPoint);
break;
case L'u':
argtos(VolumePrefix);
break;
default:
goto usage;
}
}
if (arge > argp)
goto usage;
if (0 == MountPoint)
goto usage;
FspDebugLogSetHandle(GetStdHandle(STD_ERROR_HANDLE));
Result = NotifyfsCreate(VolumePrefix, MountPoint, &Notifyfs);
if (!NT_SUCCESS(Result))
{
fail(L"cannot create file system");
goto exit;
}
Result = FspFileSystemStartDispatcher(Notifyfs->FileSystem, 0);
if (!NT_SUCCESS(Result))
{
fail(L"cannot start file system");
goto exit;
}
MountPoint = FspFileSystemMountPoint(Notifyfs->FileSystem);
info(L"%s%s%s -m %s",
L"" PROGNAME,
0 != VolumePrefix && L'\0' != VolumePrefix[0] ? L" -u " : L"",
0 != VolumePrefix && L'\0' != VolumePrefix[0] ? VolumePrefix : L"",
MountPoint);
Service->UserContext = Notifyfs;
Result = STATUS_SUCCESS;
exit:
if (!NT_SUCCESS(Result) && 0 != Notifyfs)
NotifyfsDelete(Notifyfs);
return Result;
usage:;
static wchar_t usage[] = L""
"usage: %s OPTIONS\n"
"\n"
"options:\n"
" -u \\Server\\Share [UNC prefix (single backslash)]\n"
" -m MountPoint [X:|*|directory]\n";
fail(usage, L"" PROGNAME);
return STATUS_UNSUCCESSFUL;
#undef argtos
}
static NTSTATUS SvcStop(FSP_SERVICE *Service)
{
NOTIFYFS *Notifyfs = Service->UserContext;
FspFileSystemStopDispatcher(Notifyfs->FileSystem);
NotifyfsDelete(Notifyfs);
return STATUS_SUCCESS;
}
int wmain(int argc, wchar_t **argv)
{
if (!NT_SUCCESS(FspLoad(0)))
return ERROR_DELAY_LOAD_FAILED;
return FspServiceRun(L"" PROGNAME, SvcStart, SvcStop, 0);
}

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30717.126
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "notifyfs", "notifyfs.vcxproj", "{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Debug|x64.ActiveCfg = Debug|x64
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Debug|x64.Build.0 = Debug|x64
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Debug|x86.ActiveCfg = Debug|Win32
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Debug|x86.Build.0 = Debug|Win32
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Release|x64.ActiveCfg = Release|x64
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Release|x64.Build.0 = Release|x64
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Release|x86.ActiveCfg = Release|Win32
{4BA1DED0-4268-408A-A4E2-8E1A6D55A99C}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3CD0763B-2BFD-4D73-9539-13273788C41E}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,175 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{4ba1ded0-4268-408a-a4e2-8e1a6d55a99c}</ProjectGuid>
<RootNamespace>notifyfs</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="notifyfs.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="notifyfs.c">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -0,0 +1,859 @@
/**
* @file Program.cs
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using Fsp;
using VolumeInfo = Fsp.Interop.VolumeInfo;
using FileInfo = Fsp.Interop.FileInfo;
namespace passthrough
{
class Ptfs : FileSystemBase
{
protected const int ALLOCATION_UNIT = 4096;
protected static void ThrowIoExceptionWithHResult(Int32 HResult)
{
throw new IOException(null, HResult);
}
protected static void ThrowIoExceptionWithWin32(Int32 Error)
{
ThrowIoExceptionWithHResult(unchecked((Int32)(0x80070000 | Error)));
}
protected static void ThrowIoExceptionWithNtStatus(Int32 Status)
{
ThrowIoExceptionWithWin32((Int32)Win32FromNtStatus(Status));
}
protected class FileDesc
{
public FileStream Stream;
public DirectoryInfo DirInfo;
public DictionaryEntry[] FileSystemInfos;
public FileDesc(FileStream Stream)
{
this.Stream = Stream;
}
public FileDesc(DirectoryInfo DirInfo)
{
this.DirInfo = DirInfo;
}
public static void GetFileInfoFromFileSystemInfo(
FileSystemInfo Info,
out FileInfo FileInfo)
{
FileInfo.FileAttributes = (UInt32)Info.Attributes;
FileInfo.ReparseTag = 0;
FileInfo.FileSize = Info is System.IO.FileInfo ?
(UInt64)((System.IO.FileInfo)Info).Length : 0;
FileInfo.AllocationSize = (FileInfo.FileSize + ALLOCATION_UNIT - 1)
/ ALLOCATION_UNIT * ALLOCATION_UNIT;
FileInfo.CreationTime = (UInt64)Info.CreationTimeUtc.ToFileTimeUtc();
FileInfo.LastAccessTime = (UInt64)Info.LastAccessTimeUtc.ToFileTimeUtc();
FileInfo.LastWriteTime = (UInt64)Info.LastWriteTimeUtc.ToFileTimeUtc();
FileInfo.ChangeTime = FileInfo.LastWriteTime;
FileInfo.IndexNumber = 0;
FileInfo.HardLinks = 0;
}
public Int32 GetFileInfo(out FileInfo FileInfo)
{
if (null != Stream)
{
BY_HANDLE_FILE_INFORMATION Info;
if (!GetFileInformationByHandle(Stream.SafeFileHandle.DangerousGetHandle(),
out Info))
ThrowIoExceptionWithWin32(Marshal.GetLastWin32Error());
FileInfo.FileAttributes = Info.dwFileAttributes;
FileInfo.ReparseTag = 0;
FileInfo.FileSize = (UInt64)Stream.Length;
FileInfo.AllocationSize = (FileInfo.FileSize + ALLOCATION_UNIT - 1)
/ ALLOCATION_UNIT * ALLOCATION_UNIT;
FileInfo.CreationTime = Info.ftCreationTime;
FileInfo.LastAccessTime = Info.ftLastAccessTime;
FileInfo.LastWriteTime = Info.ftLastWriteTime;
FileInfo.ChangeTime = FileInfo.LastWriteTime;
FileInfo.IndexNumber = 0;
FileInfo.HardLinks = 0;
}
else
GetFileInfoFromFileSystemInfo(DirInfo, out FileInfo);
return STATUS_SUCCESS;
}
public void SetBasicInfo(
UInt32 FileAttributes,
UInt64 CreationTime,
UInt64 LastAccessTime,
UInt64 LastWriteTime)
{
if (0 == FileAttributes)
FileAttributes = (UInt32)System.IO.FileAttributes.Normal;
if (null != Stream)
{
FILE_BASIC_INFO Info = default(FILE_BASIC_INFO);
if (unchecked((UInt32)(-1)) != FileAttributes)
Info.FileAttributes = FileAttributes;
if (0 != CreationTime)
Info.CreationTime = CreationTime;
if (0 != LastAccessTime)
Info.LastAccessTime = LastAccessTime;
if (0 != LastWriteTime)
Info.LastWriteTime = LastWriteTime;
if (!SetFileInformationByHandle(Stream.SafeFileHandle.DangerousGetHandle(),
0/*FileBasicInfo*/, ref Info, (UInt32)Marshal.SizeOf(Info)))
ThrowIoExceptionWithWin32(Marshal.GetLastWin32Error());
}
else
{
if (unchecked((UInt32)(-1)) != FileAttributes)
DirInfo.Attributes = (System.IO.FileAttributes)FileAttributes;
if (0 != CreationTime)
DirInfo.CreationTimeUtc = DateTime.FromFileTimeUtc((Int64)CreationTime);
if (0 != LastAccessTime)
DirInfo.LastAccessTimeUtc = DateTime.FromFileTimeUtc((Int64)LastAccessTime);
if (0 != LastWriteTime)
DirInfo.LastWriteTimeUtc = DateTime.FromFileTimeUtc((Int64)LastWriteTime);
}
}
public UInt32 GetFileAttributes()
{
FileInfo FileInfo;
GetFileInfo(out FileInfo);
return FileInfo.FileAttributes;
}
public void SetFileAttributes(UInt32 FileAttributes)
{
SetBasicInfo(FileAttributes, 0, 0, 0);
}
public Byte[] GetSecurityDescriptor()
{
if (null != Stream)
return Stream.GetAccessControl().GetSecurityDescriptorBinaryForm();
else
return DirInfo.GetAccessControl().GetSecurityDescriptorBinaryForm();
}
public void SetSecurityDescriptor(AccessControlSections Sections, Byte[] SecurityDescriptor)
{
Int32 SecurityInformation = 0;
if (0 != (Sections & AccessControlSections.Owner))
SecurityInformation |= 1/*OWNER_SECURITY_INFORMATION*/;
if (0 != (Sections & AccessControlSections.Group))
SecurityInformation |= 2/*GROUP_SECURITY_INFORMATION*/;
if (0 != (Sections & AccessControlSections.Access))
SecurityInformation |= 4/*DACL_SECURITY_INFORMATION*/;
if (0 != (Sections & AccessControlSections.Audit))
SecurityInformation |= 8/*SACL_SECURITY_INFORMATION*/;
if (null != Stream)
{
if (!SetKernelObjectSecurity(Stream.SafeFileHandle.DangerousGetHandle(),
SecurityInformation, SecurityDescriptor))
ThrowIoExceptionWithWin32(Marshal.GetLastWin32Error());
}
else
{
if (!SetFileSecurityW(DirInfo.FullName,
SecurityInformation, SecurityDescriptor))
ThrowIoExceptionWithWin32(Marshal.GetLastWin32Error());
}
}
public void SetDisposition(Boolean Safe)
{
if (null != Stream)
{
FILE_DISPOSITION_INFO Info;
Info.DeleteFile = true;
if (!SetFileInformationByHandle(Stream.SafeFileHandle.DangerousGetHandle(),
4/*FileDispositionInfo*/, ref Info, (UInt32)Marshal.SizeOf(Info)))
if (!Safe)
ThrowIoExceptionWithWin32(Marshal.GetLastWin32Error());
}
else
try
{
DirInfo.Delete();
}
catch (Exception ex)
{
if (!Safe)
ThrowIoExceptionWithHResult(ex.HResult);
}
}
public static void Rename(String FileName, String NewFileName, Boolean ReplaceIfExists)
{
if (!MoveFileExW(FileName, NewFileName, ReplaceIfExists ? 1U/*MOVEFILE_REPLACE_EXISTING*/ : 0))
ThrowIoExceptionWithWin32(Marshal.GetLastWin32Error());
}
/* interop */
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct BY_HANDLE_FILE_INFORMATION
{
public UInt32 dwFileAttributes;
public UInt64 ftCreationTime;
public UInt64 ftLastAccessTime;
public UInt64 ftLastWriteTime;
public UInt32 dwVolumeSerialNumber;
public UInt32 nFileSizeHigh;
public UInt32 nFileSizeLow;
public UInt32 nNumberOfLinks;
public UInt32 nFileIndexHigh;
public UInt32 nFileIndexLow;
}
[StructLayout(LayoutKind.Sequential)]
private struct FILE_BASIC_INFO
{
public UInt64 CreationTime;
public UInt64 LastAccessTime;
public UInt64 LastWriteTime;
public UInt64 ChangeTime;
public UInt32 FileAttributes;
}
[StructLayout(LayoutKind.Sequential)]
private struct FILE_DISPOSITION_INFO
{
public Boolean DeleteFile;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern Boolean GetFileInformationByHandle(
IntPtr hFile,
out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern Boolean SetFileInformationByHandle(
IntPtr hFile,
Int32 FileInformationClass,
ref FILE_BASIC_INFO lpFileInformation,
UInt32 dwBufferSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern Boolean SetFileInformationByHandle(
IntPtr hFile,
Int32 FileInformationClass,
ref FILE_DISPOSITION_INFO lpFileInformation,
UInt32 dwBufferSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern Boolean MoveFileExW(
[MarshalAs(UnmanagedType.LPWStr)] String lpExistingFileName,
[MarshalAs(UnmanagedType.LPWStr)] String lpNewFileName,
UInt32 dwFlags);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern Boolean SetFileSecurityW(
[MarshalAs(UnmanagedType.LPWStr)] String FileName,
Int32 SecurityInformation,
Byte[] SecurityDescriptor);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern Boolean SetKernelObjectSecurity(
IntPtr Handle,
Int32 SecurityInformation,
Byte[] SecurityDescriptor);
}
private class DirectoryEntryComparer : IComparer
{
public int Compare(object x, object y)
{
return String.Compare(
(String)((DictionaryEntry)x).Key,
(String)((DictionaryEntry)y).Key);
}
}
private static DirectoryEntryComparer _DirectoryEntryComparer =
new DirectoryEntryComparer();
public Ptfs(String Path0)
{
_Path = Path.GetFullPath(Path0);
if (_Path.EndsWith("\\"))
_Path = _Path.Substring(0, _Path.Length - 1);
}
public String ConcatPath(String FileName)
{
return _Path + FileName;
}
public override Int32 ExceptionHandler(Exception ex)
{
Int32 HResult = ex.HResult; /* needs Framework 4.5 */
if (0x80070000 == (HResult & 0xFFFF0000))
return NtStatusFromWin32((UInt32)HResult & 0xFFFF);
return STATUS_UNEXPECTED_IO_ERROR;
}
public override Int32 Init(Object Host0)
{
FileSystemHost Host = (FileSystemHost)Host0;
Host.SectorSize = ALLOCATION_UNIT;
Host.SectorsPerAllocationUnit = 1;
Host.MaxComponentLength = 255;
Host.FileInfoTimeout = 1000;
Host.CaseSensitiveSearch = false;
Host.CasePreservedNames = true;
Host.UnicodeOnDisk = true;
Host.PersistentAcls = true;
Host.PostCleanupWhenModifiedOnly = true;
Host.PassQueryDirectoryPattern = true;
Host.FlushAndPurgeOnCleanup = true;
Host.VolumeCreationTime = (UInt64)File.GetCreationTimeUtc(_Path).ToFileTimeUtc();
Host.VolumeSerialNumber = 0;
return STATUS_SUCCESS;
}
public override Int32 GetVolumeInfo(
out VolumeInfo VolumeInfo)
{
VolumeInfo = default(VolumeInfo);
try
{
DriveInfo Info = new DriveInfo(_Path);
VolumeInfo.TotalSize = (UInt64)Info.TotalSize;
VolumeInfo.FreeSize = (UInt64)Info.TotalFreeSpace;
}
catch (ArgumentException)
{
/*
* DriveInfo only supports drives and does not support UNC paths.
* It would be better to use GetDiskFreeSpaceEx here.
*/
}
return STATUS_SUCCESS;
}
public override Int32 GetSecurityByName(
String FileName,
out UInt32 FileAttributes/* or ReparsePointIndex */,
ref Byte[] SecurityDescriptor)
{
FileName = ConcatPath(FileName);
System.IO.FileInfo Info = new System.IO.FileInfo(FileName);
FileAttributes = (UInt32)Info.Attributes;
if (null != SecurityDescriptor)
SecurityDescriptor = Info.GetAccessControl().GetSecurityDescriptorBinaryForm();
return STATUS_SUCCESS;
}
public override Int32 Create(
String FileName,
UInt32 CreateOptions,
UInt32 GrantedAccess,
UInt32 FileAttributes,
Byte[] SecurityDescriptor,
UInt64 AllocationSize,
out Object FileNode,
out Object FileDesc0,
out FileInfo FileInfo,
out String NormalizedName)
{
FileDesc FileDesc = null;
try
{
FileName = ConcatPath(FileName);
if (0 == (CreateOptions & FILE_DIRECTORY_FILE))
{
FileSecurity Security = null;
if (null != SecurityDescriptor)
{
Security = new FileSecurity();
Security.SetSecurityDescriptorBinaryForm(SecurityDescriptor);
}
FileDesc = new FileDesc(
new FileStream(
FileName,
FileMode.CreateNew,
(FileSystemRights)GrantedAccess | FileSystemRights.WriteAttributes,
FileShare.Read | FileShare.Write | FileShare.Delete,
4096,
0,
Security));
FileDesc.SetFileAttributes(FileAttributes | (UInt32)System.IO.FileAttributes.Archive);
}
else
{
if (Directory.Exists(FileName))
ThrowIoExceptionWithNtStatus(STATUS_OBJECT_NAME_COLLISION);
DirectorySecurity Security = null;
if (null != SecurityDescriptor)
{
Security = new DirectorySecurity();
Security.SetSecurityDescriptorBinaryForm(SecurityDescriptor);
}
FileDesc = new FileDesc(
Directory.CreateDirectory(FileName, Security));
FileDesc.SetFileAttributes(FileAttributes);
}
FileNode = default(Object);
FileDesc0 = FileDesc;
NormalizedName = default(String);
return FileDesc.GetFileInfo(out FileInfo);
}
catch
{
if (null != FileDesc && null != FileDesc.Stream)
FileDesc.Stream.Dispose();
throw;
}
}
public override Int32 Open(
String FileName,
UInt32 CreateOptions,
UInt32 GrantedAccess,
out Object FileNode,
out Object FileDesc0,
out FileInfo FileInfo,
out String NormalizedName)
{
FileDesc FileDesc = null;
try
{
FileName = ConcatPath(FileName);
if (!Directory.Exists(FileName))
{
FileDesc = new FileDesc(
new FileStream(
FileName,
FileMode.Open,
(FileSystemRights)GrantedAccess,
FileShare.Read | FileShare.Write | FileShare.Delete,
4096,
0));
}
else
{
FileDesc = new FileDesc(
new DirectoryInfo(FileName));
}
FileNode = default(Object);
FileDesc0 = FileDesc;
NormalizedName = default(String);
return FileDesc.GetFileInfo(out FileInfo);
}
catch
{
if (null != FileDesc && null != FileDesc.Stream)
FileDesc.Stream.Dispose();
throw;
}
}
public override Int32 Overwrite(
Object FileNode,
Object FileDesc0,
UInt32 FileAttributes,
Boolean ReplaceFileAttributes,
UInt64 AllocationSize,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (ReplaceFileAttributes)
FileDesc.SetFileAttributes(FileAttributes |
(UInt32)System.IO.FileAttributes.Archive);
else if (0 != FileAttributes)
FileDesc.SetFileAttributes(FileDesc.GetFileAttributes() | FileAttributes |
(UInt32)System.IO.FileAttributes.Archive);
FileDesc.Stream.SetLength(0);
return FileDesc.GetFileInfo(out FileInfo);
}
public override void Cleanup(
Object FileNode,
Object FileDesc0,
String FileName,
UInt32 Flags)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (0 != (Flags & CleanupDelete))
{
FileDesc.SetDisposition(true);
if (null != FileDesc.Stream)
FileDesc.Stream.Dispose();
}
}
public override void Close(
Object FileNode,
Object FileDesc0)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (null != FileDesc.Stream)
FileDesc.Stream.Dispose();
}
public override Int32 Read(
Object FileNode,
Object FileDesc0,
IntPtr Buffer,
UInt64 Offset,
UInt32 Length,
out UInt32 PBytesTransferred)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (Offset >= (UInt64)FileDesc.Stream.Length)
ThrowIoExceptionWithNtStatus(STATUS_END_OF_FILE);
Byte[] Bytes = new byte[Length];
FileDesc.Stream.Seek((Int64)Offset, SeekOrigin.Begin);
PBytesTransferred = (UInt32)FileDesc.Stream.Read(Bytes, 0, Bytes.Length);
Marshal.Copy(Bytes, 0, Buffer, Bytes.Length);
return STATUS_SUCCESS;
}
public override Int32 Write(
Object FileNode,
Object FileDesc0,
IntPtr Buffer,
UInt64 Offset,
UInt32 Length,
Boolean WriteToEndOfFile,
Boolean ConstrainedIo,
out UInt32 PBytesTransferred,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (ConstrainedIo)
{
if (Offset >= (UInt64)FileDesc.Stream.Length)
{
PBytesTransferred = default(UInt32);
FileInfo = default(FileInfo);
return STATUS_SUCCESS;
}
if (Offset + Length > (UInt64)FileDesc.Stream.Length)
Length = (UInt32)((UInt64)FileDesc.Stream.Length - Offset);
}
Byte[] Bytes = new byte[Length];
Marshal.Copy(Buffer, Bytes, 0, Bytes.Length);
if (!WriteToEndOfFile)
FileDesc.Stream.Seek((Int64)Offset, SeekOrigin.Begin);
FileDesc.Stream.Write(Bytes, 0, Bytes.Length);
PBytesTransferred = (UInt32)Bytes.Length;
return FileDesc.GetFileInfo(out FileInfo);
}
public override Int32 Flush(
Object FileNode,
Object FileDesc0,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (null == FileDesc)
{
/* we do not flush the whole volume, so just return SUCCESS */
FileInfo = default(FileInfo);
return STATUS_SUCCESS;
}
FileDesc.Stream.Flush(true);
return FileDesc.GetFileInfo(out FileInfo);
}
public override Int32 GetFileInfo(
Object FileNode,
Object FileDesc0,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
return FileDesc.GetFileInfo(out FileInfo);
}
public override Int32 SetBasicInfo(
Object FileNode,
Object FileDesc0,
UInt32 FileAttributes,
UInt64 CreationTime,
UInt64 LastAccessTime,
UInt64 LastWriteTime,
UInt64 ChangeTime,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
FileDesc.SetBasicInfo(FileAttributes, CreationTime, LastAccessTime, LastWriteTime);
return FileDesc.GetFileInfo(out FileInfo);
}
public override Int32 SetFileSize(
Object FileNode,
Object FileDesc0,
UInt64 NewSize,
Boolean SetAllocationSize,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (!SetAllocationSize || (UInt64)FileDesc.Stream.Length > NewSize)
{
/*
* "FileInfo.FileSize > NewSize" explanation:
* Ptfs does not support allocation size. However if the new AllocationSize
* is less than the current FileSize we must truncate the file.
*/
FileDesc.Stream.SetLength((Int64)NewSize);
}
return FileDesc.GetFileInfo(out FileInfo);
}
public override Int32 CanDelete(
Object FileNode,
Object FileDesc0,
String FileName)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
FileDesc.SetDisposition(false);
return STATUS_SUCCESS;
}
public override Int32 Rename(
Object FileNode,
Object FileDesc0,
String FileName,
String NewFileName,
Boolean ReplaceIfExists)
{
FileName = ConcatPath(FileName);
NewFileName = ConcatPath(NewFileName);
FileDesc.Rename(FileName, NewFileName, ReplaceIfExists);
return STATUS_SUCCESS;
}
public override Int32 GetSecurity(
Object FileNode,
Object FileDesc0,
ref Byte[] SecurityDescriptor)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
SecurityDescriptor = FileDesc.GetSecurityDescriptor();
return STATUS_SUCCESS;
}
public override Int32 SetSecurity(
Object FileNode,
Object FileDesc0,
AccessControlSections Sections,
Byte[] SecurityDescriptor)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
FileDesc.SetSecurityDescriptor(Sections, SecurityDescriptor);
return STATUS_SUCCESS;
}
public override Boolean ReadDirectoryEntry(
Object FileNode,
Object FileDesc0,
String Pattern,
String Marker,
ref Object Context,
out String FileName,
out FileInfo FileInfo)
{
FileDesc FileDesc = (FileDesc)FileDesc0;
if (null == FileDesc.FileSystemInfos)
{
if (null != Pattern)
Pattern = Pattern.Replace('<', '*').Replace('>', '?').Replace('"', '.');
else
Pattern = "*";
IEnumerable Enum = FileDesc.DirInfo.EnumerateFileSystemInfos(Pattern);
SortedList List = new SortedList();
if (null != FileDesc.DirInfo && null != FileDesc.DirInfo.Parent)
{
List.Add(".", FileDesc.DirInfo);
List.Add("..", FileDesc.DirInfo.Parent);
}
foreach (FileSystemInfo Info in Enum)
List.Add(Info.Name, Info);
FileDesc.FileSystemInfos = new DictionaryEntry[List.Count];
List.CopyTo(FileDesc.FileSystemInfos, 0);
}
int Index;
if (null == Context)
{
Index = 0;
if (null != Marker)
{
Index = Array.BinarySearch(FileDesc.FileSystemInfos,
new DictionaryEntry(Marker, null),
_DirectoryEntryComparer);
if (0 <= Index)
Index++;
else
Index = ~Index;
}
}
else
Index = (int)Context;
if (FileDesc.FileSystemInfos.Length > Index)
{
Context = Index + 1;
FileName = (String)FileDesc.FileSystemInfos[Index].Key;
FileDesc.GetFileInfoFromFileSystemInfo(
(FileSystemInfo)FileDesc.FileSystemInfos[Index].Value,
out FileInfo);
return true;
}
else
{
FileName = default(String);
FileInfo = default(FileInfo);
return false;
}
}
private String _Path;
}
class PtfsService : Service
{
private class CommandLineUsageException : Exception
{
public CommandLineUsageException(String Message = null) : base(Message)
{
HasMessage = null != Message;
}
public bool HasMessage;
}
private const String PROGNAME = "passthrough-dotnet";
public PtfsService() : base("PtfsService")
{
}
protected override void OnStart(String[] Args)
{
try
{
String DebugLogFile = null;
UInt32 DebugFlags = 0;
String VolumePrefix = null;
String PassThrough = null;
String MountPoint = null;
IntPtr DebugLogHandle = (IntPtr)(-1);
FileSystemHost Host = null;
Ptfs Ptfs = null;
int I;
for (I = 1; Args.Length > I; I++)
{
String Arg = Args[I];
if ('-' != Arg[0])
break;
switch (Arg[1])
{
case '?':
throw new CommandLineUsageException();
case 'd':
argtol(Args, ref I, ref DebugFlags);
break;
case 'D':
argtos(Args, ref I, ref DebugLogFile);
break;
case 'm':
argtos(Args, ref I, ref MountPoint);
break;
case 'p':
argtos(Args, ref I, ref PassThrough);
break;
case 'u':
argtos(Args, ref I, ref VolumePrefix);
break;
default:
throw new CommandLineUsageException();
}
}
if (Args.Length > I)
throw new CommandLineUsageException();
if (null == PassThrough && null != VolumePrefix)
{
I = VolumePrefix.IndexOf('\\');
if (-1 != I && VolumePrefix.Length > I && '\\' != VolumePrefix[I + 1])
{
I = VolumePrefix.IndexOf('\\', I + 1);
if (-1 != I &&
VolumePrefix.Length > I + 1 &&
(
('A' <= VolumePrefix[I + 1] && VolumePrefix[I + 1] <= 'Z') ||
('a' <= VolumePrefix[I + 1] && VolumePrefix[I + 1] <= 'z')
) &&
'$' == VolumePrefix[I + 2])
{
PassThrough = String.Format("{0}:{1}", VolumePrefix[I + 1], VolumePrefix.Substring(I + 3));
}
}
}
if (null == PassThrough || null == MountPoint)
throw new CommandLineUsageException();
if (null != DebugLogFile)
if (0 > FileSystemHost.SetDebugLogFile(DebugLogFile))
throw new CommandLineUsageException("cannot open debug log file");
Host = new FileSystemHost(Ptfs = new Ptfs(PassThrough));
Host.Prefix = VolumePrefix;
if (0 > Host.Mount(MountPoint, null, true, DebugFlags))
throw new IOException("cannot mount file system");
MountPoint = Host.MountPoint();
_Host = Host;
Log(EVENTLOG_INFORMATION_TYPE, String.Format("{0}{1}{2} -p {3} -m {4}",
PROGNAME,
null != VolumePrefix && 0 < VolumePrefix.Length ? " -u " : "",
null != VolumePrefix && 0 < VolumePrefix.Length ? VolumePrefix : "",
PassThrough,
MountPoint));
}
catch (CommandLineUsageException ex)
{
Log(EVENTLOG_ERROR_TYPE, String.Format(
"{0}" +
"usage: {1} OPTIONS\n" +
"\n" +
"options:\n" +
" -d DebugFlags [-1: enable all debug logs]\n" +
" -D DebugLogFile [file path; use - for stderr]\n" +
" -u \\Server\\Share [UNC prefix (single backslash)]\n" +
" -p Directory [directory to expose as pass through file system]\n" +
" -m MountPoint [X:|*|directory]\n",
ex.HasMessage ? ex.Message + "\n" : "",
PROGNAME));
throw;
}
catch (Exception ex)
{
Log(EVENTLOG_ERROR_TYPE, String.Format("{0}", ex.Message));
throw;
}
}
protected override void OnStop()
{
_Host.Unmount();
_Host = null;
}
private static void argtos(String[] Args, ref int I, ref String V)
{
if (Args.Length > ++I)
V = Args[I];
else
throw new CommandLineUsageException();
}
private static void argtol(String[] Args, ref int I, ref UInt32 V)
{
Int32 R;
if (Args.Length > ++I)
V = Int32.TryParse(Args[I], out R) ? (UInt32)R : V;
else
throw new CommandLineUsageException();
}
private FileSystemHost _Host;
}
class Program
{
static void Main(string[] args)
{
Environment.ExitCode = new PtfsService().Run();
}
}
}

View File

@ -0,0 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6EC13EBC-BD7E-4997-9B29-49D5F06103A6}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>passthrough</RootNamespace>
<AssemblyName>passthrough-dotnet</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath>
<BaseIntermediateOutputPath>$(SolutionDir)build\$(ProjectName).build\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>$(SolutionDir)build\$(Configuration)\</OutputPath>
<BaseIntermediateOutputPath>$(SolutionDir)build\$(ProjectName).build\</BaseIntermediateOutputPath>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)$(Configuration)\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="winfsp-msil, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b099876d8fa9b1f3, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>$(MSBuildProgramFiles32)\WinFsp\bin\winfsp-msil.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5.2 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "passthrough-dotnet", "passthrough-dotnet.csproj", "{6EC13EBC-BD7E-4997-9B29-49D5F06103A6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6EC13EBC-BD7E-4997-9B29-49D5F06103A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6EC13EBC-BD7E-4997-9B29-49D5F06103A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6EC13EBC-BD7E-4997-9B29-49D5F06103A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6EC13EBC-BD7E-4997-9B29-49D5F06103A6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,18 @@
usage:
@echo "make cygfuse|winfsp-fuse" 1>&2
@echo "" 1>&2
@echo " cygfuse Link with CYGFUSE" 1>&2
@echo " winfsp-fuse Link with WinFsp-FUSE" 1>&2
@exit 2
cygfuse: passthrough-cygfuse
winfsp-fuse: passthrough-winfsp-fuse
passthrough-cygfuse: passthrough-fuse.c
gcc $^ -o $@ -g -Wall `pkg-config fuse --cflags --libs`
passthrough-winfsp-fuse: export PKG_CONFIG_PATH=$(PWD)/winfsp.install/lib
passthrough-winfsp-fuse: passthrough-fuse.c
ln -nsf "`regtool --wow32 get '/HKLM/Software/WinFsp/InstallDir' | cygpath -au -f -`" winfsp.install
gcc $^ -o $@ -g -Wall `pkg-config fuse --cflags --libs`

View File

@ -0,0 +1,7 @@
`Passthrough-fuse` is a simple FUSE file system that passes all file system operations to an underlying file system.
It can be built with the following tools:
- Using Visual Studio (`winfsp.sln`).
- Using Cygwin GCC and linking directly with the WinFsp DLL (`make winfsp-fuse`).
- Using Cygwin GCC and linking to CYGFUSE (`make cygfuse`).

View File

@ -0,0 +1,417 @@
/**
* @file passthrough-fuse.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <fuse.h>
#if defined(_WIN64) || defined(_WIN32)
#include "winposix.h"
#else
#include <dirent.h>
#include <unistd.h>
#endif
#define PTFS_UTIMENS
#define FSNAME "passthrough"
#define PROGNAME "passthrough-fuse"
#define concat_path(ptfs, fn, fp) (sizeof fp > (unsigned)snprintf(fp, sizeof fp, "%s%s", ptfs->rootdir, fn))
#define fi_dirbit (0x8000000000000000ULL)
#define fi_fh(fi, MASK) ((fi)->fh & (MASK))
#define fi_setfh(fi, FH, MASK) ((fi)->fh = (intptr_t)(FH) | (MASK))
#define fi_fd(fi) (fi_fh(fi, fi_dirbit) ? \
dirfd((DIR *)(intptr_t)fi_fh(fi, ~fi_dirbit)) : (int)fi_fh(fi, ~fi_dirbit))
#define fi_dirp(fi) ((DIR *)(intptr_t)fi_fh(fi, ~fi_dirbit))
#define fi_setfd(fi, fd) (fi_setfh(fi, fd, 0))
#define fi_setdirp(fi, dirp) (fi_setfh(fi, dirp, fi_dirbit))
#define ptfs_impl_fullpath(n) \
char full ## n[PATH_MAX]; \
if (!concat_path(((PTFS *)fuse_get_context()->private_data), n, full ## n))\
return -ENAMETOOLONG; \
n = full ## n
typedef struct
{
const char *rootdir;
} PTFS;
static int ptfs_getattr(const char *path, struct fuse_stat *stbuf)
{
ptfs_impl_fullpath(path);
return -1 != lstat(path, stbuf) ? 0 : -errno;
}
static int ptfs_mkdir(const char *path, fuse_mode_t mode)
{
ptfs_impl_fullpath(path);
return -1 != mkdir(path, mode) ? 0 : -errno;
}
static int ptfs_unlink(const char *path)
{
ptfs_impl_fullpath(path);
return -1 != unlink(path) ? 0 : -errno;
}
static int ptfs_rmdir(const char *path)
{
ptfs_impl_fullpath(path);
return -1 != rmdir(path) ? 0 : -errno;
}
static int ptfs_rename(const char *oldpath, const char *newpath)
{
ptfs_impl_fullpath(newpath);
ptfs_impl_fullpath(oldpath);
return -1 != rename(oldpath, newpath) ? 0 : -errno;
}
static int ptfs_chmod(const char *path, fuse_mode_t mode)
{
ptfs_impl_fullpath(path);
return -1 != chmod(path, mode) ? 0 : -errno;
}
static int ptfs_chown(const char *path, fuse_uid_t uid, fuse_gid_t gid)
{
ptfs_impl_fullpath(path);
return -1 != lchown(path, uid, gid) ? 0 : -errno;
}
static int ptfs_truncate(const char *path, fuse_off_t size)
{
ptfs_impl_fullpath(path);
return -1 != truncate(path, size) ? 0 : -errno;
}
#if !defined(PTFS_UTIMENS)
static int ptfs_utime(const char *path, struct fuse_utimbuf *timbuf)
{
ptfs_impl_fullpath(path);
return -1 != utime(path, timbuf) ? 0 : -errno;
}
#endif
static int ptfs_open(const char *path, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
int fd;
return -1 != (fd = open(path, fi->flags)) ? (fi_setfd(fi, fd), 0) : -errno;
}
static int ptfs_read(const char *path, char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
int nb;
return -1 != (nb = pread(fd, buf, size, off)) ? nb : -errno;
}
static int ptfs_write(const char *path, const char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
int nb;
return -1 != (nb = pwrite(fd, buf, size, off)) ? nb : -errno;
}
static int ptfs_statfs(const char *path, struct fuse_statvfs *stbuf)
{
ptfs_impl_fullpath(path);
return -1 != statvfs(path, stbuf) ? 0 : -errno;
}
static int ptfs_release(const char *path, struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
close(fd);
return 0;
}
static int ptfs_fsync(const char *path, int datasync, struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
return -1 != fsync(fd) ? 0 : -errno;
}
static int ptfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags)
{
ptfs_impl_fullpath(path);
return -1 != lsetxattr(path, name, value, size, flags) ? 0 : -errno;
}
static int ptfs_getxattr(const char *path, const char *name, char *value, size_t size)
{
ptfs_impl_fullpath(path);
int nb;
return -1 != (nb = lgetxattr(path, name, value, size)) ? nb : -errno;
}
static int ptfs_listxattr(const char *path, char *namebuf, size_t size)
{
ptfs_impl_fullpath(path);
int nb;
return -1 != (nb = llistxattr(path, namebuf, size)) ? nb : -errno;
}
static int ptfs_removexattr(const char *path, const char *name)
{
ptfs_impl_fullpath(path);
return -1 != lremovexattr(path, name) ? 0 : -errno;
}
static int ptfs_opendir(const char *path, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
DIR *dirp;
return 0 != (dirp = opendir(path)) ? (fi_setdirp(fi, dirp), 0) : -errno;
}
static int ptfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, fuse_off_t off,
struct fuse_file_info *fi)
{
DIR *dirp = fi_dirp(fi);
struct dirent *de;
rewinddir(dirp);
for (;;)
{
errno = 0;
if (0 == (de = readdir(dirp)))
break;
#if defined(_WIN64) || defined(_WIN32)
if (0 != filler(buf, de->d_name, &de->d_stat, 0))
#else
if (0 != filler(buf, de->d_name, 0, 0))
#endif
return -ENOMEM;
}
return -errno;
}
static int ptfs_releasedir(const char *path, struct fuse_file_info *fi)
{
DIR *dirp = fi_dirp(fi);
return -1 != closedir(dirp) ? 0 : -errno;
}
static void *ptfs_init(struct fuse_conn_info *conn)
{
#if defined(_WIN64) || defined(_WIN32)
#if defined(FSP_FUSE_CAP_READDIR_PLUS)
conn->want |= (conn->capable & FSP_FUSE_CAP_READDIR_PLUS);
#endif
#if defined(FSP_FUSE_USE_STAT_EX) && defined(FSP_FUSE_CAP_STAT_EX)
conn->want |= (conn->capable & FSP_FUSE_CAP_STAT_EX);
#endif
#if defined(FSP_FUSE_CAP_CASE_INSENSITIVE)
conn->want |= (conn->capable & FSP_FUSE_CAP_CASE_INSENSITIVE);
#endif
#endif
return fuse_get_context()->private_data;
}
static int ptfs_create(const char *path, fuse_mode_t mode, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
int fd;
return -1 != (fd = open(path, fi->flags, mode)) ? (fi_setfd(fi, fd), 0) : -errno;
}
static int ptfs_ftruncate(const char *path, fuse_off_t off, struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
return -1 != ftruncate(fd, off) ? 0 : -errno;
}
static int ptfs_fgetattr(const char *path, struct fuse_stat *stbuf, struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
return -1 != fstat(fd, stbuf) ? 0 : -errno;
}
#if defined(PTFS_UTIMENS)
static int ptfs_utimens(const char *path, const struct fuse_timespec tv[2])
{
ptfs_impl_fullpath(path);
return -1 != utimensat(AT_FDCWD, path, tv, AT_SYMLINK_NOFOLLOW) ? 0 : -errno;
}
#endif
#if defined(_WIN64) || defined(_WIN32)
static int ptfs_setcrtime(const char *path, const struct fuse_timespec *tv)
{
ptfs_impl_fullpath(path);
return -1 != setcrtime(path, tv) ? 0 : -errno;
}
#endif
#if defined(FSP_FUSE_USE_STAT_EX)
static int ptfs_chflags(const char *path, uint32_t flags)
{
ptfs_impl_fullpath(path);
return -1 != lchflags(path, flags) ? 0 : -errno;
}
#endif
static struct fuse_operations ptfs_ops =
{
.getattr = ptfs_getattr,
.mkdir = ptfs_mkdir,
.unlink = ptfs_unlink,
.rmdir = ptfs_rmdir,
.rename = ptfs_rename,
.chmod = ptfs_chmod,
.chown = ptfs_chown,
.truncate = ptfs_truncate,
#if !defined(PTFS_UTIMENS)
.utime = ptfs_utime,
#endif
.open = ptfs_open,
.read = ptfs_read,
.write = ptfs_write,
.statfs = ptfs_statfs,
.release = ptfs_release,
.fsync = ptfs_fsync,
.setxattr = ptfs_setxattr,
.getxattr = ptfs_getxattr,
.listxattr = ptfs_listxattr,
.removexattr = ptfs_removexattr,
.opendir = ptfs_opendir,
.readdir = ptfs_readdir,
.releasedir = ptfs_releasedir,
.init = ptfs_init,
.create = ptfs_create,
.ftruncate = ptfs_ftruncate,
.fgetattr = ptfs_fgetattr,
#if defined(PTFS_UTIMENS)
.utimens = ptfs_utimens,
#endif
#if defined(_WIN64) || defined(_WIN32)
.setcrtime = ptfs_setcrtime,
#endif
#if defined(FSP_FUSE_USE_STAT_EX)
.chflags = ptfs_chflags,
#endif
};
static void usage(void)
{
fprintf(stderr, "usage: " PROGNAME " [FUSE options] rootdir mountpoint\n");
exit(2);
}
int main(int argc, char *argv[])
{
PTFS ptfs = { 0 };
if (3 <= argc && '-' != argv[argc - 2][0] && '-' != argv[argc - 1][0])
{
ptfs.rootdir = realpath(argv[argc - 2], 0); /* memory freed at process end */
argv[argc - 2] = argv[argc - 1];
argc--;
}
#if defined(_WIN64) || defined(_WIN32)
/*
* When building for Windows (rather than Cygwin or POSIX OS)
* allow the path to be specified using the --VolumePrefix
* switch using the syntax \\passthrough-fuse\C$\Path. This
* allows us to run the file system under the WinFsp.Launcher
* and start it using commands like:
*
* net use z: \\passthrough-fuse\C$\Path
*/
if (0 == ptfs.rootdir)
for (int argi = 1; argc > argi; argi++)
{
int strncmp(const char *a, const char *b, size_t length);
char *strchr(const char *s, int c);
char *p = 0;
if (0 == strncmp("--UNC=", argv[argi], sizeof "--UNC=" - 1))
p = argv[argi] + sizeof "--UNC=" - 1;
else if (0 == strncmp("--VolumePrefix=", argv[argi], sizeof "--VolumePrefix=" - 1))
p = argv[argi] + sizeof "--VolumePrefix=" - 1;
if (0 != p && '\\' != p[1])
{
p = strchr(p + 1, '\\');
if (0 != p &&
(
('A' <= p[1] && p[1] <= 'Z') ||
('a' <= p[1] && p[1] <= 'z')
) &&
'$' == p[2])
{
p[2] = ':';
ptfs.rootdir = realpath(p + 1, 0); /* memory freed at process end */
p[2] = '$';
break;
}
}
}
#endif
if (0 == ptfs.rootdir)
usage();
return fuse_main(argc, argv, &ptfs_ops, &ptfs);
}

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "passthrough-fuse", "passthrough-fuse.vcxproj", "{C753851C-142F-4AAD-B2F7-CBF905C2A600}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Debug|x64.ActiveCfg = Debug|x64
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Debug|x64.Build.0 = Debug|x64
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Debug|x86.ActiveCfg = Debug|Win32
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Debug|x86.Build.0 = Debug|Win32
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Release|x64.ActiveCfg = Release|x64
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Release|x64.Build.0 = Release|x64
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Release|x86.ActiveCfg = Release|Win32
{C753851C-142F-4AAD-B2F7-CBF905C2A600}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,190 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{C753851C-142F-4AAD-B2F7-CBF905C2A600}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>passthroughfuse</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>FSP_FUSE_USE_STAT_EX;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="passthrough-fuse.c" />
<ClCompile Include="winposix.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="winposix.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="passthrough-fuse.c">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="winposix.c">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="winposix.h">
<Filter>Source</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,892 @@
/**
* @file winposix.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
/*
* This is a very simple Windows POSIX layer. It handles all the POSIX
* file API's required to implement passthrough-fuse in POSIX, however
* the API handling is rather unsophisticated.
*
* Ways to improve it: use the FspPosix* API's to properly handle
* file names and security.
*/
#include <winfsp/winfsp.h>
#include <fcntl.h>
#include <fuse.h>
#include "winposix.h"
#pragma comment(lib, "ntdll.lib")
typedef struct _FILE_GET_EA_INFORMATION
{
ULONG NextEntryOffset;
UCHAR EaNameLength;
CHAR EaName[1];
} FILE_GET_EA_INFORMATION, *PFILE_GET_EA_INFORMATION;
NTSYSAPI NTSTATUS NTAPI NtQueryEaFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN BOOLEAN ReturnSingleEntry,
IN PVOID EaList OPTIONAL,
IN ULONG EaListLength,
IN PULONG EaIndex OPTIONAL,
IN BOOLEAN RestartScan);
NTSYSAPI NTSTATUS NTAPI NtSetEaFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID EaBuffer,
IN ULONG EaBufferSize);
#define NEXT_EA(Ea, EaEnd) \
(0 != (Ea)->NextEntryOffset ? (PVOID)((PUINT8)(Ea) + (Ea)->NextEntryOffset) : (EaEnd))
struct _DIR
{
HANDLE h, fh;
struct dirent de;
char path[];
};
#if defined(FSP_FUSE_USE_STAT_EX)
static inline uint32_t MapFileAttributesToFlags(UINT32 FileAttributes)
{
uint32_t flags = 0;
if (FileAttributes & FILE_ATTRIBUTE_READONLY)
flags |= FSP_FUSE_UF_READONLY;
if (FileAttributes & FILE_ATTRIBUTE_HIDDEN)
flags |= FSP_FUSE_UF_HIDDEN;
if (FileAttributes & FILE_ATTRIBUTE_SYSTEM)
flags |= FSP_FUSE_UF_SYSTEM;
if (FileAttributes & FILE_ATTRIBUTE_ARCHIVE)
flags |= FSP_FUSE_UF_ARCHIVE;
return flags;
}
static inline UINT32 MapFlagsToFileAttributes(uint32_t flags)
{
UINT32 FileAttributes = 0;
if (flags & FSP_FUSE_UF_READONLY)
FileAttributes |= FILE_ATTRIBUTE_READONLY;
if (flags & FSP_FUSE_UF_HIDDEN)
FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
if (flags & FSP_FUSE_UF_SYSTEM)
FileAttributes |= FILE_ATTRIBUTE_SYSTEM;
if (flags & FSP_FUSE_UF_ARCHIVE)
FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
return FileAttributes;
}
#endif
static int maperror(int winerrno);
static inline void *error0(void)
{
errno = maperror(GetLastError());
return 0;
}
static inline int error(void)
{
errno = maperror(GetLastError());
return -1;
}
char *realpath(const char *path, char *resolved)
{
char *result;
if (0 == resolved)
{
result = malloc(PATH_MAX); /* sets errno */
if (0 == result)
return 0;
}
else
result = resolved;
int err = 0;
DWORD len = GetFullPathNameA(path, PATH_MAX, result, 0);
if (0 == len)
err = GetLastError();
else if (PATH_MAX < len)
err = ERROR_INVALID_PARAMETER;
if (0 == err)
{
HANDLE h = CreateFileA(result,
FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE != h)
CloseHandle(h);
else
err = GetLastError();
}
if (0 != err)
{
if (result != resolved)
free(result);
errno = maperror(err);
result = 0;
}
return result;
}
int statvfs(const char *path, struct fuse_statvfs *stbuf)
{
char root[PATH_MAX];
DWORD
VolumeSerialNumber,
MaxComponentLength,
SectorsPerCluster,
BytesPerSector,
NumberOfFreeClusters,
TotalNumberOfClusters;
if (!GetVolumePathNameA(path, root, PATH_MAX) ||
!GetVolumeInformationA(root, 0, 0, &VolumeSerialNumber, &MaxComponentLength, 0, 0, 0) ||
!GetDiskFreeSpaceA(root, &SectorsPerCluster, &BytesPerSector,
&NumberOfFreeClusters, &TotalNumberOfClusters))
{
return error();
}
memset(stbuf, 0, sizeof *stbuf);
stbuf->f_bsize = SectorsPerCluster * BytesPerSector;
stbuf->f_frsize = SectorsPerCluster * BytesPerSector;
stbuf->f_blocks = TotalNumberOfClusters;
stbuf->f_bfree = NumberOfFreeClusters;
stbuf->f_bavail = TotalNumberOfClusters;
stbuf->f_fsid = VolumeSerialNumber;
stbuf->f_namemax = MaxComponentLength;
return 0;
}
int open(const char *path, int oflag, ...)
{
static DWORD da[] = { GENERIC_READ, GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE, 0 };
static DWORD cd[] = { OPEN_EXISTING, OPEN_ALWAYS, TRUNCATE_EXISTING, CREATE_ALWAYS };
DWORD DesiredAccess = 0 == (oflag & _O_APPEND) ?
da[oflag & (_O_RDONLY | _O_WRONLY | _O_RDWR)] :
(da[oflag & (_O_RDONLY | _O_WRONLY | _O_RDWR)] & ~FILE_WRITE_DATA) | FILE_APPEND_DATA;
DWORD CreationDisposition = (_O_CREAT | _O_EXCL) == (oflag & (_O_CREAT | _O_EXCL)) ?
CREATE_NEW :
cd[(oflag & (_O_CREAT | _O_TRUNC)) >> 8];
HANDLE h = CreateFileA(path,
DesiredAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0/* default security */,
CreationDisposition, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
return (int)(intptr_t)h;
}
int fstat(int fd, struct fuse_stat *stbuf)
{
HANDLE h = (HANDLE)(intptr_t)fd;
BY_HANDLE_FILE_INFORMATION FileInfo;
if (!GetFileInformationByHandle(h, &FileInfo))
return error();
memset(stbuf, 0, sizeof *stbuf);
stbuf->st_mode = 0777 |
((FileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0040000/* S_IFDIR */ : 0);
stbuf->st_nlink = 1;
stbuf->st_size = ((UINT64)FileInfo.nFileSizeHigh << 32) | ((UINT64)FileInfo.nFileSizeLow);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftCreationTime, (void *)&stbuf->st_birthtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftLastAccessTime, (void *)&stbuf->st_atim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftLastWriteTime, (void *)&stbuf->st_mtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftLastWriteTime, (void *)&stbuf->st_ctim);
#if defined(FSP_FUSE_USE_STAT_EX)
stbuf->st_flags = MapFileAttributesToFlags(FileInfo.dwFileAttributes);
#endif
return 0;
}
int ftruncate(int fd, fuse_off_t size)
{
HANDLE h = (HANDLE)(intptr_t)fd;
FILE_END_OF_FILE_INFO EndOfFileInfo;
EndOfFileInfo.EndOfFile.QuadPart = size;
if (!SetFileInformationByHandle(h, FileEndOfFileInfo, &EndOfFileInfo, sizeof EndOfFileInfo))
return error();
return 0;
}
int pread(int fd, void *buf, size_t nbyte, fuse_off_t offset)
{
HANDLE h = (HANDLE)(intptr_t)fd;
OVERLAPPED Overlapped = { 0 };
DWORD BytesTransferred;
Overlapped.Offset = (DWORD)offset;
Overlapped.OffsetHigh = (DWORD)(offset >> 32);
if (!ReadFile(h, buf, (DWORD)nbyte, &BytesTransferred, &Overlapped))
{
if (ERROR_HANDLE_EOF == GetLastError())
return 0;
return error();
}
return BytesTransferred;
}
int pwrite(int fd, const void *buf, size_t nbyte, fuse_off_t offset)
{
HANDLE h = (HANDLE)(intptr_t)fd;
OVERLAPPED Overlapped = { 0 };
DWORD BytesTransferred;
Overlapped.Offset = (DWORD)offset;
Overlapped.OffsetHigh = (DWORD)(offset >> 32);
if (!WriteFile(h, buf, (DWORD)nbyte, &BytesTransferred, &Overlapped))
return error();
return BytesTransferred;
}
int fsync(int fd)
{
HANDLE h = (HANDLE)(intptr_t)fd;
if (!FlushFileBuffers(h))
return error();
return 0;
}
int close(int fd)
{
HANDLE h = (HANDLE)(intptr_t)fd;
if (!CloseHandle(h))
return error();
return 0;
}
int lstat(const char *path, struct fuse_stat *stbuf)
{
HANDLE h = CreateFileA(path,
FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
int res = fstat((int)(intptr_t)h, stbuf);
CloseHandle(h);
return res;
}
int chmod(const char *path, fuse_mode_t mode)
{
/* we do not support file security */
return 0;
}
int lchown(const char *path, fuse_uid_t uid, fuse_gid_t gid)
{
/* we do not support file security */
return 0;
}
int lchflags(const char *path, uint32_t flags)
{
#if defined(FSP_FUSE_USE_STAT_EX)
UINT32 FileAttributes = MapFlagsToFileAttributes(flags);
if (0 == FileAttributes)
FileAttributes = FILE_ATTRIBUTE_NORMAL;
if (!SetFileAttributesA(path, FileAttributes))
return error();
#endif
return 0;
}
int truncate(const char *path, fuse_off_t size)
{
HANDLE h = CreateFileA(path,
FILE_WRITE_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
int res = ftruncate((int)(intptr_t)h, size);
CloseHandle(h);
return res;
}
int utime(const char *path, const struct fuse_utimbuf *timbuf)
{
if (0 == timbuf)
return utimensat(AT_FDCWD, path, 0, AT_SYMLINK_NOFOLLOW);
else
{
struct fuse_timespec times[2];
times[0].tv_sec = timbuf->actime;
times[0].tv_nsec = 0;
times[1].tv_sec = timbuf->modtime;
times[1].tv_nsec = 0;
return utimensat(AT_FDCWD, path, times, AT_SYMLINK_NOFOLLOW);
}
}
int utimensat(int dirfd, const char *path, const struct fuse_timespec times[2], int flag)
{
/* ignore dirfd and assume that it is always AT_FDCWD */
/* ignore flag and assume that it is always AT_SYMLINK_NOFOLLOW */
HANDLE h = CreateFileA(path,
FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
UINT64 LastAccessTime, LastWriteTime;
if (0 == times)
{
FILETIME FileTime;
GetSystemTimeAsFileTime(&FileTime);
LastAccessTime = LastWriteTime = *(PUINT64)&FileTime;
}
else
{
FspPosixUnixTimeToFileTime((void *)&times[0], &LastAccessTime);
FspPosixUnixTimeToFileTime((void *)&times[1], &LastWriteTime);
}
int res = SetFileTime(h,
0, (PFILETIME)&LastAccessTime, (PFILETIME)&LastWriteTime) ? 0 : error();
CloseHandle(h);
return res;
}
int setcrtime(const char *path, const struct fuse_timespec *tv)
{
HANDLE h = CreateFileA(path,
FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
UINT64 CreationTime;
FspPosixUnixTimeToFileTime((void *)tv, &CreationTime);
int res = SetFileTime(h,
(PFILETIME)&CreationTime, 0, 0) ? 0 : error();
CloseHandle(h);
return res;
}
int unlink(const char *path)
{
if (!DeleteFileA(path))
return error();
return 0;
}
int rename(const char *oldpath, const char *newpath)
{
if (!MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
return error();
return 0;
}
static int lsetea(const char *path, PFILE_FULL_EA_INFORMATION Ea, ULONG EaLength)
{
HANDLE h = CreateFileA(path,
FILE_WRITE_EA | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
IO_STATUS_BLOCK Iosb;
NTSTATUS Status = NtSetEaFile(h, &Iosb, Ea, EaLength);
CloseHandle(h);
if (!NT_SUCCESS(Status))
switch (Status)
{
case STATUS_INVALID_EA_NAME:
case STATUS_EA_LIST_INCONSISTENT:
case STATUS_EA_CORRUPT_ERROR:
case STATUS_NONEXISTENT_EA_ENTRY:
case STATUS_NO_MORE_EAS:
case STATUS_NO_EAS_ON_FILE:
errno = EINVAL;
return -1;
default:
SetLastError(RtlNtStatusToDosError(Status));
return error();
}
return 0;
}
static int lgetea(const char *path,
PFILE_GET_EA_INFORMATION GetEa, ULONG GetEaLength,
PFILE_FULL_EA_INFORMATION Ea, ULONG EaLength)
{
HANDLE h = CreateFileA(path,
FILE_READ_EA | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
IO_STATUS_BLOCK Iosb;
NTSTATUS Status = NtQueryEaFile(h, &Iosb, Ea, EaLength, FALSE, GetEa, GetEaLength, 0, TRUE);
CloseHandle(h);
if (!NT_SUCCESS(Status))
switch (Status)
{
case STATUS_INVALID_EA_NAME:
case STATUS_EA_LIST_INCONSISTENT:
case STATUS_EA_CORRUPT_ERROR:
case STATUS_NONEXISTENT_EA_ENTRY:
case STATUS_NO_MORE_EAS:
errno = EINVAL;
return -1;
case STATUS_NO_EAS_ON_FILE:
if (0 == GetEa)
return 0;
else
{
errno = ENODATA;
return -1;
}
default:
SetLastError(RtlNtStatusToDosError(Status));
return error();
}
else if (0 == GetEa &&
(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) > Iosb.Information || 0 == Ea->EaValueLength))
{
errno = ENODATA;
return -1;
}
return (ULONG)Iosb.Information;
}
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags)
{
union
{
FILE_FULL_EA_INFORMATION V;
UINT8 B[1024];
} EaBuf;
PFILE_FULL_EA_INFORMATION Ea = &EaBuf.V;
ULONG EaLength;
size_t namelen = strlen(name);
if (254 < namelen || 0xffff < size)
{
errno = EINVAL;
return -1;
}
EaLength = (ULONG)(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + namelen + 1 + size);
if (sizeof EaBuf < EaLength)
{
Ea = malloc(EaLength); /* sets errno */
if (0 == Ea)
return -1;
}
memset(Ea, 0, sizeof(FILE_FULL_EA_INFORMATION));
Ea->EaNameLength = (UCHAR)namelen;
Ea->EaValueLength = (USHORT)size;
memcpy(Ea->EaName, name, namelen + 1);
memcpy(Ea->EaName + namelen + 1, value, size);
int res = lsetea(path, Ea, EaLength); /* sets errno */
if (&EaBuf.V != Ea)
free(Ea);
return res;
}
int lgetxattr(const char *path, const char *name, void *value, size_t size0)
{
size_t size = 0 == size0 || 0xffff < size0 ? 0xffff : size0;
union
{
FILE_GET_EA_INFORMATION V;
UINT8 B[FIELD_OFFSET(FILE_GET_EA_INFORMATION, EaName) + 255];
} GetEaBuf;
PFILE_GET_EA_INFORMATION GetEa = &GetEaBuf.V;
union
{
FILE_FULL_EA_INFORMATION V;
UINT8 B[1024];
} EaBuf;
PFILE_FULL_EA_INFORMATION Ea = &EaBuf.V;
ULONG GetEaLength, EaLength;
size_t namelen = strlen(name);
if (254 < namelen)
{
errno = EINVAL;
return -1;
}
EaLength = (ULONG)(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + namelen + 1 + size);
if (sizeof EaBuf < EaLength)
{
Ea = malloc(EaLength); /* sets errno */
if (0 == Ea)
return -1;
}
GetEaLength = (ULONG)(FIELD_OFFSET(FILE_GET_EA_INFORMATION, EaName) + namelen + 1);
memset(GetEa, 0, sizeof(FILE_GET_EA_INFORMATION));
GetEa->EaNameLength = (UCHAR)namelen;
memcpy(GetEa->EaName, name, namelen + 1);
int res = lgetea(path, GetEa, GetEaLength, Ea, EaLength);
if (0 < res)
{
res = Ea->EaValueLength;
if (0 == size0)
;
else if (res <= size0)
memcpy(value, Ea->EaName + Ea->EaNameLength + 1, res);
else
{
errno = ERANGE;
res = -1;
}
}
else if (0 == res) /* should not happen! */
{
}
if (&EaBuf.V != Ea)
free(Ea);
return res;
}
int llistxattr(const char *path, char *namebuf, size_t size)
{
PFILE_FULL_EA_INFORMATION Ea = 0;
ULONG EaLength;
EaLength = (ULONG)(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + 254 + 1 + 0xffff);
Ea = malloc(EaLength); /* sets errno */
if (0 == Ea)
return -1;
int res = lgetea(path, 0, 0, Ea, EaLength);
if (0 < res)
{
PFILE_FULL_EA_INFORMATION EaEnd = (PVOID)((PUINT8)Ea + res);
res = 0;
for (PFILE_FULL_EA_INFORMATION EaPtr = Ea; EaEnd > EaPtr; EaPtr = NEXT_EA(EaPtr, EaEnd))
res += EaPtr->EaNameLength + 1;
if (0 == size)
;
else if (res <= size)
{
char *p = namebuf;
for (PFILE_FULL_EA_INFORMATION EaPtr = Ea; EaEnd > EaPtr; EaPtr = NEXT_EA(EaPtr, EaEnd))
{
memcpy(p, EaPtr->EaName, EaPtr->EaNameLength + 1);
p += EaPtr->EaNameLength + 1;
}
}
else
{
errno = ERANGE;
res = -1;
}
}
free(Ea);
return res;
}
int lremovexattr(const char *path, const char *name)
{
return lsetxattr(path, name, 0, 0, 0);
}
int mkdir(const char *path, fuse_mode_t mode)
{
if (!CreateDirectoryA(path, 0/* default security */))
return error();
return 0;
}
int rmdir(const char *path)
{
if (!RemoveDirectoryA(path))
return error();
return 0;
}
DIR *opendir(const char *path)
{
HANDLE h = CreateFileA(path,
FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error0();
size_t pathlen = strlen(path);
if (0 < pathlen && '/' == path[pathlen - 1])
pathlen--;
DIR *dirp = malloc(sizeof *dirp + pathlen + 3); /* sets errno */
if (0 == dirp)
{
CloseHandle(h);
return 0;
}
memset(dirp, 0, sizeof *dirp);
dirp->h = h;
dirp->fh = INVALID_HANDLE_VALUE;
memcpy(dirp->path, path, pathlen);
dirp->path[pathlen + 0] = '/';
dirp->path[pathlen + 1] = '*';
dirp->path[pathlen + 2] = '\0';
return dirp;
}
int dirfd(DIR *dirp)
{
return (int)(intptr_t)dirp->h;
}
void rewinddir(DIR *dirp)
{
if (INVALID_HANDLE_VALUE != dirp->fh)
{
FindClose(dirp->fh);
dirp->fh = INVALID_HANDLE_VALUE;
}
}
struct dirent *readdir(DIR *dirp)
{
WIN32_FIND_DATAA FindData;
struct fuse_stat *stbuf = &dirp->de.d_stat;
if (INVALID_HANDLE_VALUE == dirp->fh)
{
dirp->fh = FindFirstFileA(dirp->path, &FindData);
if (INVALID_HANDLE_VALUE == dirp->fh)
return error0();
}
else
{
if (!FindNextFileA(dirp->fh, &FindData))
{
if (ERROR_NO_MORE_FILES == GetLastError())
return 0;
return error0();
}
}
memset(stbuf, 0, sizeof *stbuf);
stbuf->st_mode = 0777 |
((FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0040000/* S_IFDIR */ : 0);
stbuf->st_nlink = 1;
stbuf->st_size = ((UINT64)FindData.nFileSizeHigh << 32) | ((UINT64)FindData.nFileSizeLow);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftCreationTime, (void *)&stbuf->st_birthtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftLastAccessTime, (void *)&stbuf->st_atim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftLastWriteTime, (void *)&stbuf->st_mtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftLastWriteTime, (void *)&stbuf->st_ctim);
#if defined(FSP_FUSE_USE_STAT_EX)
stbuf->st_flags = MapFileAttributesToFlags(FindData.dwFileAttributes);
#endif
strcpy(dirp->de.d_name, FindData.cFileName);
return &dirp->de;
}
int closedir(DIR *dirp)
{
if (INVALID_HANDLE_VALUE != dirp->fh)
FindClose(dirp->fh);
CloseHandle(dirp->h);
free(dirp);
return 0;
}
static int maperror(int winerrno)
{
switch (winerrno)
{
case ERROR_INVALID_FUNCTION:
return EINVAL;
case ERROR_FILE_NOT_FOUND:
return ENOENT;
case ERROR_PATH_NOT_FOUND:
return ENOENT;
case ERROR_TOO_MANY_OPEN_FILES:
return EMFILE;
case ERROR_ACCESS_DENIED:
return EACCES;
case ERROR_INVALID_HANDLE:
return EBADF;
case ERROR_ARENA_TRASHED:
return ENOMEM;
case ERROR_NOT_ENOUGH_MEMORY:
return ENOMEM;
case ERROR_INVALID_BLOCK:
return ENOMEM;
case ERROR_BAD_ENVIRONMENT:
return E2BIG;
case ERROR_BAD_FORMAT:
return ENOEXEC;
case ERROR_INVALID_ACCESS:
return EINVAL;
case ERROR_INVALID_DATA:
return EINVAL;
case ERROR_INVALID_DRIVE:
return ENOENT;
case ERROR_CURRENT_DIRECTORY:
return EACCES;
case ERROR_NOT_SAME_DEVICE:
return EXDEV;
case ERROR_NO_MORE_FILES:
return ENOENT;
case ERROR_LOCK_VIOLATION:
return EACCES;
case ERROR_BAD_NETPATH:
return ENOENT;
case ERROR_NETWORK_ACCESS_DENIED:
return EACCES;
case ERROR_BAD_NET_NAME:
return ENOENT;
case ERROR_FILE_EXISTS:
return EEXIST;
case ERROR_CANNOT_MAKE:
return EACCES;
case ERROR_FAIL_I24:
return EACCES;
case ERROR_INVALID_PARAMETER:
return EINVAL;
case ERROR_NO_PROC_SLOTS:
return EAGAIN;
case ERROR_DRIVE_LOCKED:
return EACCES;
case ERROR_BROKEN_PIPE:
return EPIPE;
case ERROR_DISK_FULL:
return ENOSPC;
case ERROR_INVALID_TARGET_HANDLE:
return EBADF;
case ERROR_WAIT_NO_CHILDREN:
return ECHILD;
case ERROR_CHILD_NOT_COMPLETE:
return ECHILD;
case ERROR_DIRECT_ACCESS_HANDLE:
return EBADF;
case ERROR_NEGATIVE_SEEK:
return EINVAL;
case ERROR_SEEK_ON_DEVICE:
return EACCES;
case ERROR_DIR_NOT_EMPTY:
return ENOTEMPTY;
case ERROR_NOT_LOCKED:
return EACCES;
case ERROR_BAD_PATHNAME:
return ENOENT;
case ERROR_MAX_THRDS_REACHED:
return EAGAIN;
case ERROR_LOCK_FAILED:
return EACCES;
case ERROR_ALREADY_EXISTS:
return EEXIST;
case ERROR_FILENAME_EXCED_RANGE:
return ENOENT;
case ERROR_NESTING_NOT_ALLOWED:
return EAGAIN;
case ERROR_NOT_ENOUGH_QUOTA:
return ENOMEM;
default:
if (ERROR_WRITE_PROTECT <= winerrno && winerrno <= ERROR_SHARING_BUFFER_EXCEEDED)
return EACCES;
else if (ERROR_INVALID_STARTING_CODESEG <= winerrno && winerrno <= ERROR_INFLOOP_IN_RELOC_CHAIN)
return ENOEXEC;
else
return EINVAL;
}
}
long WinFspLoad(void)
{
return FspLoad(0);
}

View File

@ -0,0 +1,86 @@
/**
* @file winposix.h
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#ifndef WINPOSIX_H_INCLUDED
#define WINPOSIX_H_INCLUDED
#define O_RDONLY _O_RDONLY
#define O_WRONLY _O_WRONLY
#define O_RDWR _O_RDWR
#define O_APPEND _O_APPEND
#define O_CREAT _O_CREAT
#define O_EXCL _O_EXCL
#define O_TRUNC _O_TRUNC
#define PATH_MAX 1024
#define AT_FDCWD -2
#define AT_SYMLINK_NOFOLLOW 2
typedef struct _DIR DIR;
struct dirent
{
struct fuse_stat d_stat;
char d_name[255];
};
char *realpath(const char *path, char *resolved);
int statvfs(const char *path, struct fuse_statvfs *stbuf);
int open(const char *path, int oflag, ...);
int fstat(int fd, struct fuse_stat *stbuf);
int ftruncate(int fd, fuse_off_t size);
int pread(int fd, void *buf, size_t nbyte, fuse_off_t offset);
int pwrite(int fd, const void *buf, size_t nbyte, fuse_off_t offset);
int fsync(int fd);
int close(int fd);
int lstat(const char *path, struct fuse_stat *stbuf);
int chmod(const char *path, fuse_mode_t mode);
int lchown(const char *path, fuse_uid_t uid, fuse_gid_t gid);
int lchflags(const char *path, uint32_t flags);
int truncate(const char *path, fuse_off_t size);
int utime(const char *path, const struct fuse_utimbuf *timbuf);
int utimensat(int dirfd, const char *path, const struct fuse_timespec times[2], int flag);
int setcrtime(const char *path, const struct fuse_timespec *tv);
int unlink(const char *path);
int rename(const char *oldpath, const char *newpath);
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags);
int lgetxattr(const char *path, const char *name, void *value, size_t size);
int llistxattr(const char *path, char *namebuf, size_t size);
int lremovexattr(const char *path, const char *name);
int mkdir(const char *path, fuse_mode_t mode);
int rmdir(const char *path);
DIR *opendir(const char *path);
int dirfd(DIR *dirp);
void rewinddir(DIR *dirp);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
long WinFspLoad(void);
#undef fuse_main
#define fuse_main(argc, argv, ops, data)\
(WinFspLoad(), fuse_main_real(argc, argv, ops, sizeof *(ops), data))
#endif

View File

@ -0,0 +1,18 @@
usage:
@echo "make cygfuse3|winfsp-fuse3" 1>&2
@echo "" 1>&2
@echo " cygfuse3 Link with CYGFUSE3" 1>&2
@echo " winfsp-fuse3 Link with WinFsp-FUSE3" 1>&2
@exit 2
cygfuse3: passthrough-cygfuse3
winfsp-fuse3: passthrough-winfsp-fuse3
passthrough-cygfuse3: passthrough-fuse3.c
gcc $^ -o $@ -g -Wall `pkg-config fuse3 --cflags --libs`
passthrough-winfsp-fuse3: export PKG_CONFIG_PATH=$(PWD)/winfsp.install/lib
passthrough-winfsp-fuse3: passthrough-fuse3.c
ln -nsf "`regtool --wow32 get '/HKLM/Software/WinFsp/InstallDir' | cygpath -au -f -`" winfsp.install
gcc $^ -o $@ -g -Wall `pkg-config fuse3 --cflags --libs`

View File

@ -0,0 +1,7 @@
`Passthrough-fuse3` is a simple FUSE3 file system that passes all file system operations to an underlying file system.
It can be built with the following tools:
- Using Visual Studio (`winfsp.sln`).
- Using Cygwin GCC and linking directly with the WinFsp DLL (`make winfsp-fuse3`).
- Using Cygwin GCC and linking to CYGFUSE3 (`make cygfuse3`).

View File

@ -0,0 +1,369 @@
/**
* @file passthrough-fuse.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <fuse.h>
#if defined(_WIN64) || defined(_WIN32)
#include "winposix.h"
#else
#include <dirent.h>
#include <unistd.h>
#endif
#define FSNAME "passthrough"
#define PROGNAME "passthrough-fuse"
#define concat_path(ptfs, fn, fp) (sizeof fp > (unsigned)snprintf(fp, sizeof fp, "%s%s", ptfs->rootdir, fn))
#define fi_dirbit (0x8000000000000000ULL)
#define fi_fh(fi, MASK) ((fi)->fh & (MASK))
#define fi_setfh(fi, FH, MASK) ((fi)->fh = (intptr_t)(FH) | (MASK))
#define fi_fd(fi) (fi_fh(fi, fi_dirbit) ? \
dirfd((DIR *)(intptr_t)fi_fh(fi, ~fi_dirbit)) : (int)fi_fh(fi, ~fi_dirbit))
#define fi_dirp(fi) ((DIR *)(intptr_t)fi_fh(fi, ~fi_dirbit))
#define fi_setfd(fi, fd) (fi_setfh(fi, fd, 0))
#define fi_setdirp(fi, dirp) (fi_setfh(fi, dirp, fi_dirbit))
#define ptfs_impl_fullpath(n) \
char full ## n[PATH_MAX]; \
if (!concat_path(((PTFS *)fuse_get_context()->private_data), n, full ## n))\
return -ENAMETOOLONG; \
n = full ## n
typedef struct
{
const char *rootdir;
} PTFS;
static int ptfs_getattr(const char *path, struct fuse_stat *stbuf, struct fuse_file_info *fi)
{
if (0 == fi)
{
ptfs_impl_fullpath(path);
return -1 != lstat(path, stbuf) ? 0 : -errno;
}
else
{
int fd = fi_fd(fi);
return -1 != fstat(fd, stbuf) ? 0 : -errno;
}
}
static int ptfs_mkdir(const char *path, fuse_mode_t mode)
{
ptfs_impl_fullpath(path);
return -1 != mkdir(path, mode) ? 0 : -errno;
}
static int ptfs_unlink(const char *path)
{
ptfs_impl_fullpath(path);
return -1 != unlink(path) ? 0 : -errno;
}
static int ptfs_rmdir(const char *path)
{
ptfs_impl_fullpath(path);
return -1 != rmdir(path) ? 0 : -errno;
}
static int ptfs_rename(const char *oldpath, const char *newpath, unsigned int flags)
{
ptfs_impl_fullpath(newpath);
ptfs_impl_fullpath(oldpath);
return -1 != rename(oldpath, newpath) ? 0 : -errno;
}
static int ptfs_chmod(const char *path, fuse_mode_t mode, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
return -1 != chmod(path, mode) ? 0 : -errno;
}
static int ptfs_chown(const char *path, fuse_uid_t uid, fuse_gid_t gid, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
return -1 != lchown(path, uid, gid) ? 0 : -errno;
}
static int ptfs_truncate(const char *path, fuse_off_t size, struct fuse_file_info *fi)
{
if (0 == fi)
{
ptfs_impl_fullpath(path);
return -1 != truncate(path, size) ? 0 : -errno;
}
else
{
int fd = fi_fd(fi);
return -1 != ftruncate(fd, size) ? 0 : -errno;
}
}
static int ptfs_open(const char *path, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
int fd;
return -1 != (fd = open(path, fi->flags)) ? (fi_setfd(fi, fd), 0) : -errno;
}
static int ptfs_read(const char *path, char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
int nb;
return -1 != (nb = pread(fd, buf, size, off)) ? nb : -errno;
}
static int ptfs_write(const char *path, const char *buf, size_t size, fuse_off_t off,
struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
int nb;
return -1 != (nb = pwrite(fd, buf, size, off)) ? nb : -errno;
}
static int ptfs_statfs(const char *path, struct fuse_statvfs *stbuf)
{
ptfs_impl_fullpath(path);
return -1 != statvfs(path, stbuf) ? 0 : -errno;
}
static int ptfs_release(const char *path, struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
close(fd);
return 0;
}
static int ptfs_fsync(const char *path, int datasync, struct fuse_file_info *fi)
{
int fd = fi_fd(fi);
return -1 != fsync(fd) ? 0 : -errno;
}
static int ptfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags)
{
ptfs_impl_fullpath(path);
return -1 != lsetxattr(path, name, value, size, flags) ? 0 : -errno;
}
static int ptfs_getxattr(const char *path, const char *name, char *value, size_t size)
{
ptfs_impl_fullpath(path);
int nb;
return -1 != (nb = lgetxattr(path, name, value, size)) ? nb : -errno;
}
static int ptfs_listxattr(const char *path, char *namebuf, size_t size)
{
ptfs_impl_fullpath(path);
int nb;
return -1 != (nb = llistxattr(path, namebuf, size)) ? nb : -errno;
}
static int ptfs_removexattr(const char *path, const char *name)
{
ptfs_impl_fullpath(path);
return -1 != lremovexattr(path, name) ? 0 : -errno;
}
static int ptfs_opendir(const char *path, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
DIR *dirp;
return 0 != (dirp = opendir(path)) ? (fi_setdirp(fi, dirp), 0) : -errno;
}
static int ptfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, fuse_off_t off,
struct fuse_file_info *fi, enum fuse_readdir_flags flags)
{
DIR *dirp = fi_dirp(fi);
struct dirent *de;
rewinddir(dirp);
for (;;)
{
errno = 0;
if (0 == (de = readdir(dirp)))
break;
#if defined(_WIN64) || defined(_WIN32)
if (0 != filler(buf, de->d_name, &de->d_stat, 0, FUSE_FILL_DIR_PLUS))
#else
if (0 != filler(buf, de->d_name, 0, 0, 0))
#endif
return -ENOMEM;
}
return -errno;
}
static int ptfs_releasedir(const char *path, struct fuse_file_info *fi)
{
DIR *dirp = fi_dirp(fi);
return -1 != closedir(dirp) ? 0 : -errno;
}
static void *ptfs_init(struct fuse_conn_info *conn, struct fuse_config *conf)
{
conn->want |= (conn->capable & FUSE_CAP_READDIRPLUS);
#if defined(FSP_FUSE_CAP_CASE_INSENSITIVE)
conn->want |= (conn->capable & FSP_FUSE_CAP_CASE_INSENSITIVE);
#endif
return fuse_get_context()->private_data;
}
static int ptfs_create(const char *path, fuse_mode_t mode, struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
int fd;
return -1 != (fd = open(path, fi->flags, mode)) ? (fi_setfd(fi, fd), 0) : -errno;
}
static int ptfs_utimens(const char *path, const struct fuse_timespec tv[2], struct fuse_file_info *fi)
{
ptfs_impl_fullpath(path);
return -1 != utimensat(AT_FDCWD, path, tv, AT_SYMLINK_NOFOLLOW) ? 0 : -errno;
}
static struct fuse_operations ptfs_ops =
{
.getattr = ptfs_getattr,
.mkdir = ptfs_mkdir,
.unlink = ptfs_unlink,
.rmdir = ptfs_rmdir,
.rename = ptfs_rename,
.chmod = ptfs_chmod,
.chown = ptfs_chown,
.truncate = ptfs_truncate,
.open = ptfs_open,
.read = ptfs_read,
.write = ptfs_write,
.statfs = ptfs_statfs,
.release = ptfs_release,
.fsync = ptfs_fsync,
.setxattr = ptfs_setxattr,
.getxattr = ptfs_getxattr,
.listxattr = ptfs_listxattr,
.removexattr = ptfs_removexattr,
.opendir = ptfs_opendir,
.readdir = ptfs_readdir,
.releasedir = ptfs_releasedir,
.init = ptfs_init,
.create = ptfs_create,
.utimens = ptfs_utimens,
};
static void usage(void)
{
fprintf(stderr, "usage: " PROGNAME " [FUSE options] rootdir mountpoint\n");
exit(2);
}
int main(int argc, char *argv[])
{
PTFS ptfs = { 0 };
if (3 <= argc && '-' != argv[argc - 2][0] && '-' != argv[argc - 1][0])
{
ptfs.rootdir = realpath(argv[argc - 2], 0); /* memory freed at process end */
argv[argc - 2] = argv[argc - 1];
argc--;
}
#if defined(_WIN64) || defined(_WIN32)
/*
* When building for Windows (rather than Cygwin or POSIX OS)
* allow the path to be specified using the --VolumePrefix
* switch using the syntax \\passthrough-fuse\C$\Path. This
* allows us to run the file system under the WinFsp.Launcher
* and start it using commands like:
*
* net use z: \\passthrough-fuse\C$\Path
*/
if (0 == ptfs.rootdir)
for (int argi = 1; argc > argi; argi++)
{
int strncmp(const char *a, const char *b, size_t length);
char *strchr(const char *s, int c);
char *p = 0;
if (0 == strncmp("--UNC=", argv[argi], sizeof "--UNC=" - 1))
p = argv[argi] + sizeof "--UNC=" - 1;
else if (0 == strncmp("--VolumePrefix=", argv[argi], sizeof "--VolumePrefix=" - 1))
p = argv[argi] + sizeof "--VolumePrefix=" - 1;
if (0 != p && '\\' != p[1])
{
p = strchr(p + 1, '\\');
if (0 != p &&
(
('A' <= p[1] && p[1] <= 'Z') ||
('a' <= p[1] && p[1] <= 'z')
) &&
'$' == p[2])
{
p[2] = ':';
ptfs.rootdir = realpath(p + 1, 0); /* memory freed at process end */
p[2] = '$';
break;
}
}
}
#endif
if (0 == ptfs.rootdir)
usage();
return fuse_main(argc, argv, &ptfs_ops, &ptfs);
}

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "passthrough-fuse3", "passthrough-fuse3.vcxproj", "{5E99498C-D30C-48EF-A04A-7977C0305FAC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Debug|x64.ActiveCfg = Debug|x64
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Debug|x64.Build.0 = Debug|x64
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Debug|x86.ActiveCfg = Debug|Win32
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Debug|x86.Build.0 = Debug|Win32
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Release|x64.ActiveCfg = Release|x64
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Release|x64.Build.0 = Release|x64
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Release|x86.ActiveCfg = Release|Win32
{5E99498C-D30C-48EF-A04A-7977C0305FAC}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,190 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{5E99498C-D30C-48EF-A04A-7977C0305FAC}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>passthroughfuse3</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc\fuse3;$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<DisableSpecificWarnings>4996</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="passthrough-fuse3.c" />
<ClCompile Include="winposix.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="winposix.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{bfbcc136-ea14-4445-8f9b-1fa7f8aedc71}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="passthrough-fuse3.c">
<Filter>Source</Filter>
</ClCompile>
<ClCompile Include="winposix.c">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="winposix.h">
<Filter>Source</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,892 @@
/**
* @file winposix.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
/*
* This is a very simple Windows POSIX layer. It handles all the POSIX
* file API's required to implement passthrough-fuse in POSIX, however
* the API handling is rather unsophisticated.
*
* Ways to improve it: use the FspPosix* API's to properly handle
* file names and security.
*/
#include <winfsp/winfsp.h>
#include <fcntl.h>
#include <fuse.h>
#include "winposix.h"
#pragma comment(lib, "ntdll.lib")
typedef struct _FILE_GET_EA_INFORMATION
{
ULONG NextEntryOffset;
UCHAR EaNameLength;
CHAR EaName[1];
} FILE_GET_EA_INFORMATION, *PFILE_GET_EA_INFORMATION;
NTSYSAPI NTSTATUS NTAPI NtQueryEaFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID Buffer,
IN ULONG Length,
IN BOOLEAN ReturnSingleEntry,
IN PVOID EaList OPTIONAL,
IN ULONG EaListLength,
IN PULONG EaIndex OPTIONAL,
IN BOOLEAN RestartScan);
NTSYSAPI NTSTATUS NTAPI NtSetEaFile(
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID EaBuffer,
IN ULONG EaBufferSize);
#define NEXT_EA(Ea, EaEnd) \
(0 != (Ea)->NextEntryOffset ? (PVOID)((PUINT8)(Ea) + (Ea)->NextEntryOffset) : (EaEnd))
struct _DIR
{
HANDLE h, fh;
struct dirent de;
char path[];
};
#if defined(FSP_FUSE_USE_STAT_EX)
static inline uint32_t MapFileAttributesToFlags(UINT32 FileAttributes)
{
uint32_t flags = 0;
if (FileAttributes & FILE_ATTRIBUTE_READONLY)
flags |= FSP_FUSE_UF_READONLY;
if (FileAttributes & FILE_ATTRIBUTE_HIDDEN)
flags |= FSP_FUSE_UF_HIDDEN;
if (FileAttributes & FILE_ATTRIBUTE_SYSTEM)
flags |= FSP_FUSE_UF_SYSTEM;
if (FileAttributes & FILE_ATTRIBUTE_ARCHIVE)
flags |= FSP_FUSE_UF_ARCHIVE;
return flags;
}
static inline UINT32 MapFlagsToFileAttributes(uint32_t flags)
{
UINT32 FileAttributes = 0;
if (flags & FSP_FUSE_UF_READONLY)
FileAttributes |= FILE_ATTRIBUTE_READONLY;
if (flags & FSP_FUSE_UF_HIDDEN)
FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
if (flags & FSP_FUSE_UF_SYSTEM)
FileAttributes |= FILE_ATTRIBUTE_SYSTEM;
if (flags & FSP_FUSE_UF_ARCHIVE)
FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
return FileAttributes;
}
#endif
static int maperror(int winerrno);
static inline void *error0(void)
{
errno = maperror(GetLastError());
return 0;
}
static inline int error(void)
{
errno = maperror(GetLastError());
return -1;
}
char *realpath(const char *path, char *resolved)
{
char *result;
if (0 == resolved)
{
result = malloc(PATH_MAX); /* sets errno */
if (0 == result)
return 0;
}
else
result = resolved;
int err = 0;
DWORD len = GetFullPathNameA(path, PATH_MAX, result, 0);
if (0 == len)
err = GetLastError();
else if (PATH_MAX < len)
err = ERROR_INVALID_PARAMETER;
if (0 == err)
{
HANDLE h = CreateFileA(result,
FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE != h)
CloseHandle(h);
else
err = GetLastError();
}
if (0 != err)
{
if (result != resolved)
free(result);
errno = maperror(err);
result = 0;
}
return result;
}
int statvfs(const char *path, struct fuse_statvfs *stbuf)
{
char root[PATH_MAX];
DWORD
VolumeSerialNumber,
MaxComponentLength,
SectorsPerCluster,
BytesPerSector,
NumberOfFreeClusters,
TotalNumberOfClusters;
if (!GetVolumePathNameA(path, root, PATH_MAX) ||
!GetVolumeInformationA(root, 0, 0, &VolumeSerialNumber, &MaxComponentLength, 0, 0, 0) ||
!GetDiskFreeSpaceA(root, &SectorsPerCluster, &BytesPerSector,
&NumberOfFreeClusters, &TotalNumberOfClusters))
{
return error();
}
memset(stbuf, 0, sizeof *stbuf);
stbuf->f_bsize = SectorsPerCluster * BytesPerSector;
stbuf->f_frsize = SectorsPerCluster * BytesPerSector;
stbuf->f_blocks = TotalNumberOfClusters;
stbuf->f_bfree = NumberOfFreeClusters;
stbuf->f_bavail = TotalNumberOfClusters;
stbuf->f_fsid = VolumeSerialNumber;
stbuf->f_namemax = MaxComponentLength;
return 0;
}
int open(const char *path, int oflag, ...)
{
static DWORD da[] = { GENERIC_READ, GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE, 0 };
static DWORD cd[] = { OPEN_EXISTING, OPEN_ALWAYS, TRUNCATE_EXISTING, CREATE_ALWAYS };
DWORD DesiredAccess = 0 == (oflag & _O_APPEND) ?
da[oflag & (_O_RDONLY | _O_WRONLY | _O_RDWR)] :
(da[oflag & (_O_RDONLY | _O_WRONLY | _O_RDWR)] & ~FILE_WRITE_DATA) | FILE_APPEND_DATA;
DWORD CreationDisposition = (_O_CREAT | _O_EXCL) == (oflag & (_O_CREAT | _O_EXCL)) ?
CREATE_NEW :
cd[(oflag & (_O_CREAT | _O_TRUNC)) >> 8];
HANDLE h = CreateFileA(path,
DesiredAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0/* default security */,
CreationDisposition, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
return (int)(intptr_t)h;
}
int fstat(int fd, struct fuse_stat *stbuf)
{
HANDLE h = (HANDLE)(intptr_t)fd;
BY_HANDLE_FILE_INFORMATION FileInfo;
if (!GetFileInformationByHandle(h, &FileInfo))
return error();
memset(stbuf, 0, sizeof *stbuf);
stbuf->st_mode = 0777 |
((FileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0040000/* S_IFDIR */ : 0);
stbuf->st_nlink = 1;
stbuf->st_size = ((UINT64)FileInfo.nFileSizeHigh << 32) | ((UINT64)FileInfo.nFileSizeLow);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftCreationTime, (void *)&stbuf->st_birthtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftLastAccessTime, (void *)&stbuf->st_atim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftLastWriteTime, (void *)&stbuf->st_mtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FileInfo.ftLastWriteTime, (void *)&stbuf->st_ctim);
#if defined(FSP_FUSE_USE_STAT_EX)
stbuf->st_flags = MapFileAttributesToFlags(FileInfo.dwFileAttributes);
#endif
return 0;
}
int ftruncate(int fd, fuse_off_t size)
{
HANDLE h = (HANDLE)(intptr_t)fd;
FILE_END_OF_FILE_INFO EndOfFileInfo;
EndOfFileInfo.EndOfFile.QuadPart = size;
if (!SetFileInformationByHandle(h, FileEndOfFileInfo, &EndOfFileInfo, sizeof EndOfFileInfo))
return error();
return 0;
}
int pread(int fd, void *buf, size_t nbyte, fuse_off_t offset)
{
HANDLE h = (HANDLE)(intptr_t)fd;
OVERLAPPED Overlapped = { 0 };
DWORD BytesTransferred;
Overlapped.Offset = (DWORD)offset;
Overlapped.OffsetHigh = (DWORD)(offset >> 32);
if (!ReadFile(h, buf, (DWORD)nbyte, &BytesTransferred, &Overlapped))
{
if (ERROR_HANDLE_EOF == GetLastError())
return 0;
return error();
}
return BytesTransferred;
}
int pwrite(int fd, const void *buf, size_t nbyte, fuse_off_t offset)
{
HANDLE h = (HANDLE)(intptr_t)fd;
OVERLAPPED Overlapped = { 0 };
DWORD BytesTransferred;
Overlapped.Offset = (DWORD)offset;
Overlapped.OffsetHigh = (DWORD)(offset >> 32);
if (!WriteFile(h, buf, (DWORD)nbyte, &BytesTransferred, &Overlapped))
return error();
return BytesTransferred;
}
int fsync(int fd)
{
HANDLE h = (HANDLE)(intptr_t)fd;
if (!FlushFileBuffers(h))
return error();
return 0;
}
int close(int fd)
{
HANDLE h = (HANDLE)(intptr_t)fd;
if (!CloseHandle(h))
return error();
return 0;
}
int lstat(const char *path, struct fuse_stat *stbuf)
{
HANDLE h = CreateFileA(path,
FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
int res = fstat((int)(intptr_t)h, stbuf);
CloseHandle(h);
return res;
}
int chmod(const char *path, fuse_mode_t mode)
{
/* we do not support file security */
return 0;
}
int lchown(const char *path, fuse_uid_t uid, fuse_gid_t gid)
{
/* we do not support file security */
return 0;
}
int lchflags(const char *path, uint32_t flags)
{
#if defined(FSP_FUSE_USE_STAT_EX)
UINT32 FileAttributes = MapFlagsToFileAttributes(flags);
if (0 == FileAttributes)
FileAttributes = FILE_ATTRIBUTE_NORMAL;
if (!SetFileAttributesA(path, FileAttributes))
return error();
#endif
return 0;
}
int truncate(const char *path, fuse_off_t size)
{
HANDLE h = CreateFileA(path,
FILE_WRITE_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
int res = ftruncate((int)(intptr_t)h, size);
CloseHandle(h);
return res;
}
int utime(const char *path, const struct fuse_utimbuf *timbuf)
{
if (0 == timbuf)
return utimensat(AT_FDCWD, path, 0, AT_SYMLINK_NOFOLLOW);
else
{
struct fuse_timespec times[2];
times[0].tv_sec = timbuf->actime;
times[0].tv_nsec = 0;
times[1].tv_sec = timbuf->modtime;
times[1].tv_nsec = 0;
return utimensat(AT_FDCWD, path, times, AT_SYMLINK_NOFOLLOW);
}
}
int utimensat(int dirfd, const char *path, const struct fuse_timespec times[2], int flag)
{
/* ignore dirfd and assume that it is always AT_FDCWD */
/* ignore flag and assume that it is always AT_SYMLINK_NOFOLLOW */
HANDLE h = CreateFileA(path,
FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
UINT64 LastAccessTime, LastWriteTime;
if (0 == times)
{
FILETIME FileTime;
GetSystemTimeAsFileTime(&FileTime);
LastAccessTime = LastWriteTime = *(PUINT64)&FileTime;
}
else
{
FspPosixUnixTimeToFileTime((void *)&times[0], &LastAccessTime);
FspPosixUnixTimeToFileTime((void *)&times[1], &LastWriteTime);
}
int res = SetFileTime(h,
0, (PFILETIME)&LastAccessTime, (PFILETIME)&LastWriteTime) ? 0 : error();
CloseHandle(h);
return res;
}
int setcrtime(const char *path, const struct fuse_timespec *tv)
{
HANDLE h = CreateFileA(path,
FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
UINT64 CreationTime;
FspPosixUnixTimeToFileTime((void *)tv, &CreationTime);
int res = SetFileTime(h,
(PFILETIME)&CreationTime, 0, 0) ? 0 : error();
CloseHandle(h);
return res;
}
int unlink(const char *path)
{
if (!DeleteFileA(path))
return error();
return 0;
}
int rename(const char *oldpath, const char *newpath)
{
if (!MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
return error();
return 0;
}
static int lsetea(const char *path, PFILE_FULL_EA_INFORMATION Ea, ULONG EaLength)
{
HANDLE h = CreateFileA(path,
FILE_WRITE_EA | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
IO_STATUS_BLOCK Iosb;
NTSTATUS Status = NtSetEaFile(h, &Iosb, Ea, EaLength);
CloseHandle(h);
if (!NT_SUCCESS(Status))
switch (Status)
{
case STATUS_INVALID_EA_NAME:
case STATUS_EA_LIST_INCONSISTENT:
case STATUS_EA_CORRUPT_ERROR:
case STATUS_NONEXISTENT_EA_ENTRY:
case STATUS_NO_MORE_EAS:
case STATUS_NO_EAS_ON_FILE:
errno = EINVAL;
return -1;
default:
SetLastError(RtlNtStatusToDosError(Status));
return error();
}
return 0;
}
static int lgetea(const char *path,
PFILE_GET_EA_INFORMATION GetEa, ULONG GetEaLength,
PFILE_FULL_EA_INFORMATION Ea, ULONG EaLength)
{
HANDLE h = CreateFileA(path,
FILE_READ_EA | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error();
IO_STATUS_BLOCK Iosb;
NTSTATUS Status = NtQueryEaFile(h, &Iosb, Ea, EaLength, FALSE, GetEa, GetEaLength, 0, TRUE);
CloseHandle(h);
if (!NT_SUCCESS(Status))
switch (Status)
{
case STATUS_INVALID_EA_NAME:
case STATUS_EA_LIST_INCONSISTENT:
case STATUS_EA_CORRUPT_ERROR:
case STATUS_NONEXISTENT_EA_ENTRY:
case STATUS_NO_MORE_EAS:
errno = EINVAL;
return -1;
case STATUS_NO_EAS_ON_FILE:
if (0 == GetEa)
return 0;
else
{
errno = ENODATA;
return -1;
}
default:
SetLastError(RtlNtStatusToDosError(Status));
return error();
}
else if (0 == GetEa &&
(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) > Iosb.Information || 0 == Ea->EaValueLength))
{
errno = ENODATA;
return -1;
}
return (ULONG)Iosb.Information;
}
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags)
{
union
{
FILE_FULL_EA_INFORMATION V;
UINT8 B[1024];
} EaBuf;
PFILE_FULL_EA_INFORMATION Ea = &EaBuf.V;
ULONG EaLength;
size_t namelen = strlen(name);
if (254 < namelen || 0xffff < size)
{
errno = EINVAL;
return -1;
}
EaLength = (ULONG)(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + namelen + 1 + size);
if (sizeof EaBuf < EaLength)
{
Ea = malloc(EaLength); /* sets errno */
if (0 == Ea)
return -1;
}
memset(Ea, 0, sizeof(FILE_FULL_EA_INFORMATION));
Ea->EaNameLength = (UCHAR)namelen;
Ea->EaValueLength = (USHORT)size;
memcpy(Ea->EaName, name, namelen + 1);
memcpy(Ea->EaName + namelen + 1, value, size);
int res = lsetea(path, Ea, EaLength); /* sets errno */
if (&EaBuf.V != Ea)
free(Ea);
return res;
}
int lgetxattr(const char *path, const char *name, void *value, size_t size0)
{
size_t size = 0 == size0 || 0xffff < size0 ? 0xffff : size0;
union
{
FILE_GET_EA_INFORMATION V;
UINT8 B[FIELD_OFFSET(FILE_GET_EA_INFORMATION, EaName) + 255];
} GetEaBuf;
PFILE_GET_EA_INFORMATION GetEa = &GetEaBuf.V;
union
{
FILE_FULL_EA_INFORMATION V;
UINT8 B[1024];
} EaBuf;
PFILE_FULL_EA_INFORMATION Ea = &EaBuf.V;
ULONG GetEaLength, EaLength;
size_t namelen = strlen(name);
if (254 < namelen)
{
errno = EINVAL;
return -1;
}
EaLength = (ULONG)(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + namelen + 1 + size);
if (sizeof EaBuf < EaLength)
{
Ea = malloc(EaLength); /* sets errno */
if (0 == Ea)
return -1;
}
GetEaLength = (ULONG)(FIELD_OFFSET(FILE_GET_EA_INFORMATION, EaName) + namelen + 1);
memset(GetEa, 0, sizeof(FILE_GET_EA_INFORMATION));
GetEa->EaNameLength = (UCHAR)namelen;
memcpy(GetEa->EaName, name, namelen + 1);
int res = lgetea(path, GetEa, GetEaLength, Ea, EaLength);
if (0 < res)
{
res = Ea->EaValueLength;
if (0 == size0)
;
else if (res <= size0)
memcpy(value, Ea->EaName + Ea->EaNameLength + 1, res);
else
{
errno = ERANGE;
res = -1;
}
}
else if (0 == res) /* should not happen! */
{
}
if (&EaBuf.V != Ea)
free(Ea);
return res;
}
int llistxattr(const char *path, char *namebuf, size_t size)
{
PFILE_FULL_EA_INFORMATION Ea = 0;
ULONG EaLength;
EaLength = (ULONG)(FIELD_OFFSET(FILE_FULL_EA_INFORMATION, EaName) + 254 + 1 + 0xffff);
Ea = malloc(EaLength); /* sets errno */
if (0 == Ea)
return -1;
int res = lgetea(path, 0, 0, Ea, EaLength);
if (0 < res)
{
PFILE_FULL_EA_INFORMATION EaEnd = (PVOID)((PUINT8)Ea + res);
res = 0;
for (PFILE_FULL_EA_INFORMATION EaPtr = Ea; EaEnd > EaPtr; EaPtr = NEXT_EA(EaPtr, EaEnd))
res += EaPtr->EaNameLength + 1;
if (0 == size)
;
else if (res <= size)
{
char *p = namebuf;
for (PFILE_FULL_EA_INFORMATION EaPtr = Ea; EaEnd > EaPtr; EaPtr = NEXT_EA(EaPtr, EaEnd))
{
memcpy(p, EaPtr->EaName, EaPtr->EaNameLength + 1);
p += EaPtr->EaNameLength + 1;
}
}
else
{
errno = ERANGE;
res = -1;
}
}
free(Ea);
return res;
}
int lremovexattr(const char *path, const char *name)
{
return lsetxattr(path, name, 0, 0, 0);
}
int mkdir(const char *path, fuse_mode_t mode)
{
if (!CreateDirectoryA(path, 0/* default security */))
return error();
return 0;
}
int rmdir(const char *path)
{
if (!RemoveDirectoryA(path))
return error();
return 0;
}
DIR *opendir(const char *path)
{
HANDLE h = CreateFileA(path,
FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == h)
return error0();
size_t pathlen = strlen(path);
if (0 < pathlen && '/' == path[pathlen - 1])
pathlen--;
DIR *dirp = malloc(sizeof *dirp + pathlen + 3); /* sets errno */
if (0 == dirp)
{
CloseHandle(h);
return 0;
}
memset(dirp, 0, sizeof *dirp);
dirp->h = h;
dirp->fh = INVALID_HANDLE_VALUE;
memcpy(dirp->path, path, pathlen);
dirp->path[pathlen + 0] = '/';
dirp->path[pathlen + 1] = '*';
dirp->path[pathlen + 2] = '\0';
return dirp;
}
int dirfd(DIR *dirp)
{
return (int)(intptr_t)dirp->h;
}
void rewinddir(DIR *dirp)
{
if (INVALID_HANDLE_VALUE != dirp->fh)
{
FindClose(dirp->fh);
dirp->fh = INVALID_HANDLE_VALUE;
}
}
struct dirent *readdir(DIR *dirp)
{
WIN32_FIND_DATAA FindData;
struct fuse_stat *stbuf = &dirp->de.d_stat;
if (INVALID_HANDLE_VALUE == dirp->fh)
{
dirp->fh = FindFirstFileA(dirp->path, &FindData);
if (INVALID_HANDLE_VALUE == dirp->fh)
return error0();
}
else
{
if (!FindNextFileA(dirp->fh, &FindData))
{
if (ERROR_NO_MORE_FILES == GetLastError())
return 0;
return error0();
}
}
memset(stbuf, 0, sizeof *stbuf);
stbuf->st_mode = 0777 |
((FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? 0040000/* S_IFDIR */ : 0);
stbuf->st_nlink = 1;
stbuf->st_size = ((UINT64)FindData.nFileSizeHigh << 32) | ((UINT64)FindData.nFileSizeLow);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftCreationTime, (void *)&stbuf->st_birthtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftLastAccessTime, (void *)&stbuf->st_atim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftLastWriteTime, (void *)&stbuf->st_mtim);
FspPosixFileTimeToUnixTime(*(PUINT64)&FindData.ftLastWriteTime, (void *)&stbuf->st_ctim);
#if defined(FSP_FUSE_USE_STAT_EX)
stbuf->st_flags = MapFileAttributesToFlags(FindData.dwFileAttributes);
#endif
strcpy(dirp->de.d_name, FindData.cFileName);
return &dirp->de;
}
int closedir(DIR *dirp)
{
if (INVALID_HANDLE_VALUE != dirp->fh)
FindClose(dirp->fh);
CloseHandle(dirp->h);
free(dirp);
return 0;
}
static int maperror(int winerrno)
{
switch (winerrno)
{
case ERROR_INVALID_FUNCTION:
return EINVAL;
case ERROR_FILE_NOT_FOUND:
return ENOENT;
case ERROR_PATH_NOT_FOUND:
return ENOENT;
case ERROR_TOO_MANY_OPEN_FILES:
return EMFILE;
case ERROR_ACCESS_DENIED:
return EACCES;
case ERROR_INVALID_HANDLE:
return EBADF;
case ERROR_ARENA_TRASHED:
return ENOMEM;
case ERROR_NOT_ENOUGH_MEMORY:
return ENOMEM;
case ERROR_INVALID_BLOCK:
return ENOMEM;
case ERROR_BAD_ENVIRONMENT:
return E2BIG;
case ERROR_BAD_FORMAT:
return ENOEXEC;
case ERROR_INVALID_ACCESS:
return EINVAL;
case ERROR_INVALID_DATA:
return EINVAL;
case ERROR_INVALID_DRIVE:
return ENOENT;
case ERROR_CURRENT_DIRECTORY:
return EACCES;
case ERROR_NOT_SAME_DEVICE:
return EXDEV;
case ERROR_NO_MORE_FILES:
return ENOENT;
case ERROR_LOCK_VIOLATION:
return EACCES;
case ERROR_BAD_NETPATH:
return ENOENT;
case ERROR_NETWORK_ACCESS_DENIED:
return EACCES;
case ERROR_BAD_NET_NAME:
return ENOENT;
case ERROR_FILE_EXISTS:
return EEXIST;
case ERROR_CANNOT_MAKE:
return EACCES;
case ERROR_FAIL_I24:
return EACCES;
case ERROR_INVALID_PARAMETER:
return EINVAL;
case ERROR_NO_PROC_SLOTS:
return EAGAIN;
case ERROR_DRIVE_LOCKED:
return EACCES;
case ERROR_BROKEN_PIPE:
return EPIPE;
case ERROR_DISK_FULL:
return ENOSPC;
case ERROR_INVALID_TARGET_HANDLE:
return EBADF;
case ERROR_WAIT_NO_CHILDREN:
return ECHILD;
case ERROR_CHILD_NOT_COMPLETE:
return ECHILD;
case ERROR_DIRECT_ACCESS_HANDLE:
return EBADF;
case ERROR_NEGATIVE_SEEK:
return EINVAL;
case ERROR_SEEK_ON_DEVICE:
return EACCES;
case ERROR_DIR_NOT_EMPTY:
return ENOTEMPTY;
case ERROR_NOT_LOCKED:
return EACCES;
case ERROR_BAD_PATHNAME:
return ENOENT;
case ERROR_MAX_THRDS_REACHED:
return EAGAIN;
case ERROR_LOCK_FAILED:
return EACCES;
case ERROR_ALREADY_EXISTS:
return EEXIST;
case ERROR_FILENAME_EXCED_RANGE:
return ENOENT;
case ERROR_NESTING_NOT_ALLOWED:
return EAGAIN;
case ERROR_NOT_ENOUGH_QUOTA:
return ENOMEM;
default:
if (ERROR_WRITE_PROTECT <= winerrno && winerrno <= ERROR_SHARING_BUFFER_EXCEEDED)
return EACCES;
else if (ERROR_INVALID_STARTING_CODESEG <= winerrno && winerrno <= ERROR_INFLOOP_IN_RELOC_CHAIN)
return ENOEXEC;
else
return EINVAL;
}
}
long WinFspLoad(void)
{
return FspLoad(0);
}

View File

@ -0,0 +1,86 @@
/**
* @file winposix.h
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#ifndef WINPOSIX_H_INCLUDED
#define WINPOSIX_H_INCLUDED
#define O_RDONLY _O_RDONLY
#define O_WRONLY _O_WRONLY
#define O_RDWR _O_RDWR
#define O_APPEND _O_APPEND
#define O_CREAT _O_CREAT
#define O_EXCL _O_EXCL
#define O_TRUNC _O_TRUNC
#define PATH_MAX 1024
#define AT_FDCWD -2
#define AT_SYMLINK_NOFOLLOW 2
typedef struct _DIR DIR;
struct dirent
{
struct fuse_stat d_stat;
char d_name[255];
};
char *realpath(const char *path, char *resolved);
int statvfs(const char *path, struct fuse_statvfs *stbuf);
int open(const char *path, int oflag, ...);
int fstat(int fd, struct fuse_stat *stbuf);
int ftruncate(int fd, fuse_off_t size);
int pread(int fd, void *buf, size_t nbyte, fuse_off_t offset);
int pwrite(int fd, const void *buf, size_t nbyte, fuse_off_t offset);
int fsync(int fd);
int close(int fd);
int lstat(const char *path, struct fuse_stat *stbuf);
int chmod(const char *path, fuse_mode_t mode);
int lchown(const char *path, fuse_uid_t uid, fuse_gid_t gid);
int lchflags(const char *path, uint32_t flags);
int truncate(const char *path, fuse_off_t size);
int utime(const char *path, const struct fuse_utimbuf *timbuf);
int utimensat(int dirfd, const char *path, const struct fuse_timespec times[2], int flag);
int setcrtime(const char *path, const struct fuse_timespec *tv);
int unlink(const char *path);
int rename(const char *oldpath, const char *newpath);
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags);
int lgetxattr(const char *path, const char *name, void *value, size_t size);
int llistxattr(const char *path, char *namebuf, size_t size);
int lremovexattr(const char *path, const char *name);
int mkdir(const char *path, fuse_mode_t mode);
int rmdir(const char *path);
DIR *opendir(const char *path);
int dirfd(DIR *dirp);
void rewinddir(DIR *dirp);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);
long WinFspLoad(void);
#undef fuse_main
#define fuse_main(argc, argv, ops, data)\
(WinFspLoad(), fuse_main_real(argc, argv, ops, sizeof *(ops), data))
#endif

View File

@ -0,0 +1,940 @@
/**
* @file passthrough.c
*
* @copyright 2015-2021 Bill Zissimopoulos
*/
/*
* This file is part of WinFsp.
*
* You can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3 as published by the Free Software
* Foundation.
*
* Licensees holding a valid commercial license may use this software
* in accordance with the commercial license agreement provided in
* conjunction with the software. The terms and conditions of any such
* commercial license agreement shall govern, supersede, and render
* ineffective any application of the GPLv3 license to this software,
* notwithstanding of any reference thereto in the software or
* associated repository.
*/
#include <winfsp/winfsp.h>
#include <strsafe.h>
#define PROGNAME "passthrough"
#define ALLOCATION_UNIT 4096
#define FULLPATH_SIZE (MAX_PATH + FSP_FSCTL_TRANSACT_PATH_SIZEMAX / sizeof(WCHAR))
#define info(format, ...) FspServiceLog(EVENTLOG_INFORMATION_TYPE, format, __VA_ARGS__)
#define warn(format, ...) FspServiceLog(EVENTLOG_WARNING_TYPE, format, __VA_ARGS__)
#define fail(format, ...) FspServiceLog(EVENTLOG_ERROR_TYPE, format, __VA_ARGS__)
#define ConcatPath(Ptfs, FN, FP) (0 == StringCbPrintfW(FP, sizeof FP, L"%s%s", Ptfs->Path, FN))
#define HandleFromContext(FC) (((PTFS_FILE_CONTEXT *)(FC))->Handle)
typedef struct
{
FSP_FILE_SYSTEM *FileSystem;
PWSTR Path;
} PTFS;
typedef struct
{
HANDLE Handle;
PVOID DirBuffer;
} PTFS_FILE_CONTEXT;
static NTSTATUS GetFileInfoInternal(HANDLE Handle, FSP_FSCTL_FILE_INFO *FileInfo)
{
BY_HANDLE_FILE_INFORMATION ByHandleFileInfo;
if (!GetFileInformationByHandle(Handle, &ByHandleFileInfo))
return FspNtStatusFromWin32(GetLastError());
FileInfo->FileAttributes = ByHandleFileInfo.dwFileAttributes;
FileInfo->ReparseTag = 0;
FileInfo->FileSize =
((UINT64)ByHandleFileInfo.nFileSizeHigh << 32) | (UINT64)ByHandleFileInfo.nFileSizeLow;
FileInfo->AllocationSize = (FileInfo->FileSize + ALLOCATION_UNIT - 1)
/ ALLOCATION_UNIT * ALLOCATION_UNIT;
FileInfo->CreationTime = ((PLARGE_INTEGER)&ByHandleFileInfo.ftCreationTime)->QuadPart;
FileInfo->LastAccessTime = ((PLARGE_INTEGER)&ByHandleFileInfo.ftLastAccessTime)->QuadPart;
FileInfo->LastWriteTime = ((PLARGE_INTEGER)&ByHandleFileInfo.ftLastWriteTime)->QuadPart;
FileInfo->ChangeTime = FileInfo->LastWriteTime;
FileInfo->IndexNumber = 0;
FileInfo->HardLinks = 0;
return STATUS_SUCCESS;
}
static NTSTATUS GetVolumeInfo(FSP_FILE_SYSTEM *FileSystem,
FSP_FSCTL_VOLUME_INFO *VolumeInfo)
{
PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
WCHAR Root[MAX_PATH];
ULARGE_INTEGER TotalSize, FreeSize;
if (!GetVolumePathName(Ptfs->Path, Root, MAX_PATH))
return FspNtStatusFromWin32(GetLastError());
if (!GetDiskFreeSpaceEx(Root, 0, &TotalSize, &FreeSize))
return FspNtStatusFromWin32(GetLastError());
VolumeInfo->TotalSize = TotalSize.QuadPart;
VolumeInfo->FreeSize = FreeSize.QuadPart;
return STATUS_SUCCESS;
}
static NTSTATUS SetVolumeLabel_(FSP_FILE_SYSTEM *FileSystem,
PWSTR VolumeLabel,
FSP_FSCTL_VOLUME_INFO *VolumeInfo)
{
/* we do not support changing the volume label */
return STATUS_INVALID_DEVICE_REQUEST;
}
static NTSTATUS GetSecurityByName(FSP_FILE_SYSTEM *FileSystem,
PWSTR FileName, PUINT32 PFileAttributes,
PSECURITY_DESCRIPTOR SecurityDescriptor, SIZE_T *PSecurityDescriptorSize)
{
PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
WCHAR FullPath[FULLPATH_SIZE];
HANDLE Handle;
FILE_ATTRIBUTE_TAG_INFO AttributeTagInfo;
DWORD SecurityDescriptorSizeNeeded;
NTSTATUS Result;
if (!ConcatPath(Ptfs, FileName, FullPath))
return STATUS_OBJECT_NAME_INVALID;
Handle = CreateFileW(FullPath,
FILE_READ_ATTRIBUTES | READ_CONTROL, 0, 0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == Handle)
{
Result = FspNtStatusFromWin32(GetLastError());
goto exit;
}
if (0 != PFileAttributes)
{
if (!GetFileInformationByHandleEx(Handle,
FileAttributeTagInfo, &AttributeTagInfo, sizeof AttributeTagInfo))
{
Result = FspNtStatusFromWin32(GetLastError());
goto exit;
}
*PFileAttributes = AttributeTagInfo.FileAttributes;
}
if (0 != PSecurityDescriptorSize)
{
if (!GetKernelObjectSecurity(Handle,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
SecurityDescriptor, (DWORD)*PSecurityDescriptorSize, &SecurityDescriptorSizeNeeded))
{
*PSecurityDescriptorSize = SecurityDescriptorSizeNeeded;
Result = FspNtStatusFromWin32(GetLastError());
goto exit;
}
*PSecurityDescriptorSize = SecurityDescriptorSizeNeeded;
}
Result = STATUS_SUCCESS;
exit:
if (INVALID_HANDLE_VALUE != Handle)
CloseHandle(Handle);
return Result;
}
static NTSTATUS Create(FSP_FILE_SYSTEM *FileSystem,
PWSTR FileName, UINT32 CreateOptions, UINT32 GrantedAccess,
UINT32 FileAttributes, PSECURITY_DESCRIPTOR SecurityDescriptor, UINT64 AllocationSize,
PVOID *PFileContext, FSP_FSCTL_FILE_INFO *FileInfo)
{
PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
WCHAR FullPath[FULLPATH_SIZE];
SECURITY_ATTRIBUTES SecurityAttributes;
ULONG CreateFlags;
PTFS_FILE_CONTEXT *FileContext;
if (!ConcatPath(Ptfs, FileName, FullPath))
return STATUS_OBJECT_NAME_INVALID;
FileContext = malloc(sizeof *FileContext);
if (0 == FileContext)
return STATUS_INSUFFICIENT_RESOURCES;
memset(FileContext, 0, sizeof *FileContext);
SecurityAttributes.nLength = sizeof SecurityAttributes;
SecurityAttributes.lpSecurityDescriptor = SecurityDescriptor;
SecurityAttributes.bInheritHandle = FALSE;
CreateFlags = FILE_FLAG_BACKUP_SEMANTICS;
if (CreateOptions & FILE_DELETE_ON_CLOSE)
CreateFlags |= FILE_FLAG_DELETE_ON_CLOSE;
if (CreateOptions & FILE_DIRECTORY_FILE)
{
/*
* It is not widely known but CreateFileW can be used to create directories!
* It requires the specification of both FILE_FLAG_BACKUP_SEMANTICS and
* FILE_FLAG_POSIX_SEMANTICS. It also requires that FileAttributes has
* FILE_ATTRIBUTE_DIRECTORY set.
*/
CreateFlags |= FILE_FLAG_POSIX_SEMANTICS;
FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
}
else
FileAttributes &= ~FILE_ATTRIBUTE_DIRECTORY;
if (0 == FileAttributes)
FileAttributes = FILE_ATTRIBUTE_NORMAL;
FileContext->Handle = CreateFileW(FullPath,
GrantedAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, &SecurityAttributes,
CREATE_NEW, CreateFlags | FileAttributes, 0);
if (INVALID_HANDLE_VALUE == FileContext->Handle)
{
free(FileContext);
return FspNtStatusFromWin32(GetLastError());
}
*PFileContext = FileContext;
return GetFileInfoInternal(FileContext->Handle, FileInfo);
}
static NTSTATUS Open(FSP_FILE_SYSTEM *FileSystem,
PWSTR FileName, UINT32 CreateOptions, UINT32 GrantedAccess,
PVOID *PFileContext, FSP_FSCTL_FILE_INFO *FileInfo)
{
PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
WCHAR FullPath[FULLPATH_SIZE];
ULONG CreateFlags;
PTFS_FILE_CONTEXT *FileContext;
if (!ConcatPath(Ptfs, FileName, FullPath))
return STATUS_OBJECT_NAME_INVALID;
FileContext = malloc(sizeof *FileContext);
if (0 == FileContext)
return STATUS_INSUFFICIENT_RESOURCES;
memset(FileContext, 0, sizeof *FileContext);
CreateFlags = FILE_FLAG_BACKUP_SEMANTICS;
if (CreateOptions & FILE_DELETE_ON_CLOSE)
CreateFlags |= FILE_FLAG_DELETE_ON_CLOSE;
FileContext->Handle = CreateFileW(FullPath,
GrantedAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0,
OPEN_EXISTING, CreateFlags, 0);
if (INVALID_HANDLE_VALUE == FileContext->Handle)
{
free(FileContext);
return FspNtStatusFromWin32(GetLastError());
}
*PFileContext = FileContext;
return GetFileInfoInternal(FileContext->Handle, FileInfo);
}
static NTSTATUS Overwrite(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, UINT32 FileAttributes, BOOLEAN ReplaceFileAttributes, UINT64 AllocationSize,
FSP_FSCTL_FILE_INFO *FileInfo)
{
HANDLE Handle = HandleFromContext(FileContext);
FILE_BASIC_INFO BasicInfo = { 0 };
FILE_ALLOCATION_INFO AllocationInfo = { 0 };
FILE_ATTRIBUTE_TAG_INFO AttributeTagInfo;
if (ReplaceFileAttributes)
{
if (0 == FileAttributes)
FileAttributes = FILE_ATTRIBUTE_NORMAL;
BasicInfo.FileAttributes = FileAttributes;
if (!SetFileInformationByHandle(Handle,
FileBasicInfo, &BasicInfo, sizeof BasicInfo))
return FspNtStatusFromWin32(GetLastError());
}
else if (0 != FileAttributes)
{
if (!GetFileInformationByHandleEx(Handle,
FileAttributeTagInfo, &AttributeTagInfo, sizeof AttributeTagInfo))
return FspNtStatusFromWin32(GetLastError());
BasicInfo.FileAttributes = FileAttributes | AttributeTagInfo.FileAttributes;
if (BasicInfo.FileAttributes ^ FileAttributes)
{
if (!SetFileInformationByHandle(Handle,
FileBasicInfo, &BasicInfo, sizeof BasicInfo))
return FspNtStatusFromWin32(GetLastError());
}
}
if (!SetFileInformationByHandle(Handle,
FileAllocationInfo, &AllocationInfo, sizeof AllocationInfo))
return FspNtStatusFromWin32(GetLastError());
return GetFileInfoInternal(Handle, FileInfo);
}
static VOID Cleanup(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, PWSTR FileName, ULONG Flags)
{
HANDLE Handle = HandleFromContext(FileContext);
if (Flags & FspCleanupDelete)
{
CloseHandle(Handle);
/* this will make all future uses of Handle to fail with STATUS_INVALID_HANDLE */
HandleFromContext(FileContext) = INVALID_HANDLE_VALUE;
}
}
static VOID Close(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext0)
{
PTFS_FILE_CONTEXT *FileContext = FileContext0;
HANDLE Handle = HandleFromContext(FileContext);
CloseHandle(Handle);
FspFileSystemDeleteDirectoryBuffer(&FileContext->DirBuffer);
free(FileContext);
}
static NTSTATUS Read(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, PVOID Buffer, UINT64 Offset, ULONG Length,
PULONG PBytesTransferred)
{
HANDLE Handle = HandleFromContext(FileContext);
OVERLAPPED Overlapped = { 0 };
Overlapped.Offset = (DWORD)Offset;
Overlapped.OffsetHigh = (DWORD)(Offset >> 32);
if (!ReadFile(Handle, Buffer, Length, PBytesTransferred, &Overlapped))
return FspNtStatusFromWin32(GetLastError());
return STATUS_SUCCESS;
}
static NTSTATUS Write(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, PVOID Buffer, UINT64 Offset, ULONG Length,
BOOLEAN WriteToEndOfFile, BOOLEAN ConstrainedIo,
PULONG PBytesTransferred, FSP_FSCTL_FILE_INFO *FileInfo)
{
HANDLE Handle = HandleFromContext(FileContext);
LARGE_INTEGER FileSize;
OVERLAPPED Overlapped = { 0 };
if (ConstrainedIo)
{
if (!GetFileSizeEx(Handle, &FileSize))
return FspNtStatusFromWin32(GetLastError());
if (Offset >= (UINT64)FileSize.QuadPart)
return STATUS_SUCCESS;
if (Offset + Length > (UINT64)FileSize.QuadPart)
Length = (ULONG)((UINT64)FileSize.QuadPart - Offset);
}
Overlapped.Offset = (DWORD)Offset;
Overlapped.OffsetHigh = (DWORD)(Offset >> 32);
if (!WriteFile(Handle, Buffer, Length, PBytesTransferred, &Overlapped))
return FspNtStatusFromWin32(GetLastError());
return GetFileInfoInternal(Handle, FileInfo);
}
NTSTATUS Flush(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext,
FSP_FSCTL_FILE_INFO *FileInfo)
{
HANDLE Handle = HandleFromContext(FileContext);
/* we do not flush the whole volume, so just return SUCCESS */
if (0 == Handle)
return STATUS_SUCCESS;
if (!FlushFileBuffers(Handle))
return FspNtStatusFromWin32(GetLastError());
return GetFileInfoInternal(Handle, FileInfo);
}
static NTSTATUS GetFileInfo(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext,
FSP_FSCTL_FILE_INFO *FileInfo)
{
HANDLE Handle = HandleFromContext(FileContext);
return GetFileInfoInternal(Handle, FileInfo);
}
static NTSTATUS SetBasicInfo(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, UINT32 FileAttributes,
UINT64 CreationTime, UINT64 LastAccessTime, UINT64 LastWriteTime, UINT64 ChangeTime,
FSP_FSCTL_FILE_INFO *FileInfo)
{
HANDLE Handle = HandleFromContext(FileContext);
FILE_BASIC_INFO BasicInfo = { 0 };
if (INVALID_FILE_ATTRIBUTES == FileAttributes)
FileAttributes = 0;
else if (0 == FileAttributes)
FileAttributes = FILE_ATTRIBUTE_NORMAL;
BasicInfo.FileAttributes = FileAttributes;
BasicInfo.CreationTime.QuadPart = CreationTime;
BasicInfo.LastAccessTime.QuadPart = LastAccessTime;
BasicInfo.LastWriteTime.QuadPart = LastWriteTime;
//BasicInfo.ChangeTime = ChangeTime;
if (!SetFileInformationByHandle(Handle,
FileBasicInfo, &BasicInfo, sizeof BasicInfo))
return FspNtStatusFromWin32(GetLastError());
return GetFileInfoInternal(Handle, FileInfo);
}
static NTSTATUS SetFileSize(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, UINT64 NewSize, BOOLEAN SetAllocationSize,
FSP_FSCTL_FILE_INFO *FileInfo)
{
HANDLE Handle = HandleFromContext(FileContext);
FILE_ALLOCATION_INFO AllocationInfo;
FILE_END_OF_FILE_INFO EndOfFileInfo;
if (SetAllocationSize)
{
/*
* This file system does not maintain AllocationSize, although NTFS clearly can.
* However it must always be FileSize <= AllocationSize and NTFS will make sure
* to truncate the FileSize if it sees an AllocationSize < FileSize.
*
* If OTOH a very large AllocationSize is passed, the call below will increase
* the AllocationSize of the underlying file, although our file system does not
* expose this fact. This AllocationSize is only temporary as NTFS will reset
* the AllocationSize of the underlying file when it is closed.
*/
AllocationInfo.AllocationSize.QuadPart = NewSize;
if (!SetFileInformationByHandle(Handle,
FileAllocationInfo, &AllocationInfo, sizeof AllocationInfo))
return FspNtStatusFromWin32(GetLastError());
}
else
{
EndOfFileInfo.EndOfFile.QuadPart = NewSize;
if (!SetFileInformationByHandle(Handle,
FileEndOfFileInfo, &EndOfFileInfo, sizeof EndOfFileInfo))
return FspNtStatusFromWin32(GetLastError());
}
return GetFileInfoInternal(Handle, FileInfo);
}
static NTSTATUS Rename(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext,
PWSTR FileName, PWSTR NewFileName, BOOLEAN ReplaceIfExists)
{
PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
WCHAR FullPath[FULLPATH_SIZE], NewFullPath[FULLPATH_SIZE];
if (!ConcatPath(Ptfs, FileName, FullPath))
return STATUS_OBJECT_NAME_INVALID;
if (!ConcatPath(Ptfs, NewFileName, NewFullPath))
return STATUS_OBJECT_NAME_INVALID;
if (!MoveFileExW(FullPath, NewFullPath, ReplaceIfExists ? MOVEFILE_REPLACE_EXISTING : 0))
return FspNtStatusFromWin32(GetLastError());
return STATUS_SUCCESS;
}
static NTSTATUS GetSecurity(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext,
PSECURITY_DESCRIPTOR SecurityDescriptor, SIZE_T *PSecurityDescriptorSize)
{
HANDLE Handle = HandleFromContext(FileContext);
DWORD SecurityDescriptorSizeNeeded;
if (!GetKernelObjectSecurity(Handle,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
SecurityDescriptor, (DWORD)*PSecurityDescriptorSize, &SecurityDescriptorSizeNeeded))
{
*PSecurityDescriptorSize = SecurityDescriptorSizeNeeded;
return FspNtStatusFromWin32(GetLastError());
}
*PSecurityDescriptorSize = SecurityDescriptorSizeNeeded;
return STATUS_SUCCESS;
}
static NTSTATUS SetSecurity(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext,
SECURITY_INFORMATION SecurityInformation, PSECURITY_DESCRIPTOR ModificationDescriptor)
{
HANDLE Handle = HandleFromContext(FileContext);
if (!SetKernelObjectSecurity(Handle, SecurityInformation, ModificationDescriptor))
return FspNtStatusFromWin32(GetLastError());
return STATUS_SUCCESS;
}
static NTSTATUS ReadDirectory(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext0, PWSTR Pattern, PWSTR Marker,
PVOID Buffer, ULONG BufferLength, PULONG PBytesTransferred)
{
PTFS *Ptfs = (PTFS *)FileSystem->UserContext;
PTFS_FILE_CONTEXT *FileContext = FileContext0;
HANDLE Handle = HandleFromContext(FileContext);
WCHAR FullPath[FULLPATH_SIZE];
ULONG Length, PatternLength;
HANDLE FindHandle;
WIN32_FIND_DATAW FindData;
union
{
UINT8 B[FIELD_OFFSET(FSP_FSCTL_DIR_INFO, FileNameBuf) + MAX_PATH * sizeof(WCHAR)];
FSP_FSCTL_DIR_INFO D;
} DirInfoBuf;
FSP_FSCTL_DIR_INFO *DirInfo = &DirInfoBuf.D;
NTSTATUS DirBufferResult;
DirBufferResult = STATUS_SUCCESS;
if (FspFileSystemAcquireDirectoryBuffer(&FileContext->DirBuffer, 0 == Marker, &DirBufferResult))
{
if (0 == Pattern)
Pattern = L"*";
PatternLength = (ULONG)wcslen(Pattern);
Length = GetFinalPathNameByHandleW(Handle, FullPath, FULLPATH_SIZE - 1, 0);
if (0 == Length)
DirBufferResult = FspNtStatusFromWin32(GetLastError());
else if (Length + 1 + PatternLength >= FULLPATH_SIZE)
DirBufferResult = STATUS_OBJECT_NAME_INVALID;
if (!NT_SUCCESS(DirBufferResult))
{
FspFileSystemReleaseDirectoryBuffer(&FileContext->DirBuffer);
return DirBufferResult;
}
if (L'\\' != FullPath[Length - 1])
FullPath[Length++] = L'\\';
memcpy(FullPath + Length, Pattern, PatternLength * sizeof(WCHAR));
FullPath[Length + PatternLength] = L'\0';
FindHandle = FindFirstFileW(FullPath, &FindData);
if (INVALID_HANDLE_VALUE != FindHandle)
{
do
{
memset(DirInfo, 0, sizeof *DirInfo);
Length = (ULONG)wcslen(FindData.cFileName);
DirInfo->Size = (UINT16)(FIELD_OFFSET(FSP_FSCTL_DIR_INFO, FileNameBuf) + Length * sizeof(WCHAR));
DirInfo->FileInfo.FileAttributes = FindData.dwFileAttributes;
DirInfo->FileInfo.ReparseTag = 0;
DirInfo->FileInfo.FileSize =
((UINT64)FindData.nFileSizeHigh << 32) | (UINT64)FindData.nFileSizeLow;
DirInfo->FileInfo.AllocationSize = (DirInfo->FileInfo.FileSize + ALLOCATION_UNIT - 1)
/ ALLOCATION_UNIT * ALLOCATION_UNIT;
DirInfo->FileInfo.CreationTime = ((PLARGE_INTEGER)&FindData.ftCreationTime)->QuadPart;
DirInfo->FileInfo.LastAccessTime = ((PLARGE_INTEGER)&FindData.ftLastAccessTime)->QuadPart;
DirInfo->FileInfo.LastWriteTime = ((PLARGE_INTEGER)&FindData.ftLastWriteTime)->QuadPart;
DirInfo->FileInfo.ChangeTime = DirInfo->FileInfo.LastWriteTime;
DirInfo->FileInfo.IndexNumber = 0;
DirInfo->FileInfo.HardLinks = 0;
memcpy(DirInfo->FileNameBuf, FindData.cFileName, Length * sizeof(WCHAR));
if (!FspFileSystemFillDirectoryBuffer(&FileContext->DirBuffer, DirInfo, &DirBufferResult))
break;
} while (FindNextFileW(FindHandle, &FindData));
FindClose(FindHandle);
}
FspFileSystemReleaseDirectoryBuffer(&FileContext->DirBuffer);
}
if (!NT_SUCCESS(DirBufferResult))
return DirBufferResult;
FspFileSystemReadDirectoryBuffer(&FileContext->DirBuffer,
Marker, Buffer, BufferLength, PBytesTransferred);
return STATUS_SUCCESS;
}
static NTSTATUS SetDelete(FSP_FILE_SYSTEM *FileSystem,
PVOID FileContext, PWSTR FileName, BOOLEAN DeleteFile)
{
HANDLE Handle = HandleFromContext(FileContext);
FILE_DISPOSITION_INFO DispositionInfo;
DispositionInfo.DeleteFile = DeleteFile;
if (!SetFileInformationByHandle(Handle,
FileDispositionInfo, &DispositionInfo, sizeof DispositionInfo))
return FspNtStatusFromWin32(GetLastError());
return STATUS_SUCCESS;
}
static FSP_FILE_SYSTEM_INTERFACE PtfsInterface =
{
.GetVolumeInfo = GetVolumeInfo,
.SetVolumeLabel = SetVolumeLabel_,
.GetSecurityByName = GetSecurityByName,
.Create = Create,
.Open = Open,
.Overwrite = Overwrite,
.Cleanup = Cleanup,
.Close = Close,
.Read = Read,
.Write = Write,
.Flush = Flush,
.GetFileInfo = GetFileInfo,
.SetBasicInfo = SetBasicInfo,
.SetFileSize = SetFileSize,
.Rename = Rename,
.GetSecurity = GetSecurity,
.SetSecurity = SetSecurity,
.ReadDirectory = ReadDirectory,
.SetDelete = SetDelete,
};
static VOID PtfsDelete(PTFS *Ptfs);
static NTSTATUS PtfsCreate(PWSTR Path, PWSTR VolumePrefix, PWSTR MountPoint, UINT32 DebugFlags,
PTFS **PPtfs)
{
WCHAR FullPath[MAX_PATH];
ULONG Length;
HANDLE Handle;
FILETIME CreationTime;
DWORD LastError;
FSP_FSCTL_VOLUME_PARAMS VolumeParams;
PTFS *Ptfs = 0;
NTSTATUS Result;
*PPtfs = 0;
Handle = CreateFileW(
Path, FILE_READ_ATTRIBUTES, 0, 0,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (INVALID_HANDLE_VALUE == Handle)
return FspNtStatusFromWin32(GetLastError());
Length = GetFinalPathNameByHandleW(Handle, FullPath, FULLPATH_SIZE - 1, 0);
if (0 == Length)
{
LastError = GetLastError();
CloseHandle(Handle);
return FspNtStatusFromWin32(LastError);
}
if (L'\\' == FullPath[Length - 1])
FullPath[--Length] = L'\0';
if (!GetFileTime(Handle, &CreationTime, 0, 0))
{
LastError = GetLastError();
CloseHandle(Handle);
return FspNtStatusFromWin32(LastError);
}
CloseHandle(Handle);
/* from now on we must goto exit on failure */
Ptfs = malloc(sizeof *Ptfs);
if (0 == Ptfs)
{
Result = STATUS_INSUFFICIENT_RESOURCES;
goto exit;
}
memset(Ptfs, 0, sizeof *Ptfs);
Length = (Length + 1) * sizeof(WCHAR);
Ptfs->Path = malloc(Length);
if (0 == Ptfs->Path)
{
Result = STATUS_INSUFFICIENT_RESOURCES;
goto exit;
}
memcpy(Ptfs->Path, FullPath, Length);
memset(&VolumeParams, 0, sizeof VolumeParams);
VolumeParams.SectorSize = ALLOCATION_UNIT;
VolumeParams.SectorsPerAllocationUnit = 1;
VolumeParams.VolumeCreationTime = ((PLARGE_INTEGER)&CreationTime)->QuadPart;
VolumeParams.VolumeSerialNumber = 0;
VolumeParams.FileInfoTimeout = 1000;
VolumeParams.CaseSensitiveSearch = 0;
VolumeParams.CasePreservedNames = 1;
VolumeParams.UnicodeOnDisk = 1;
VolumeParams.PersistentAcls = 1;
VolumeParams.PostCleanupWhenModifiedOnly = 1;
VolumeParams.PassQueryDirectoryPattern = 1;
VolumeParams.FlushAndPurgeOnCleanup = 1;
VolumeParams.UmFileContextIsUserContext2 = 1;
if (0 != VolumePrefix)
wcscpy_s(VolumeParams.Prefix, sizeof VolumeParams.Prefix / sizeof(WCHAR), VolumePrefix);
wcscpy_s(VolumeParams.FileSystemName, sizeof VolumeParams.FileSystemName / sizeof(WCHAR),
L"" PROGNAME);
Result = FspFileSystemCreate(
VolumeParams.Prefix[0] ? L"" FSP_FSCTL_NET_DEVICE_NAME : L"" FSP_FSCTL_DISK_DEVICE_NAME,
&VolumeParams,
&PtfsInterface,
&Ptfs->FileSystem);
if (!NT_SUCCESS(Result))
goto exit;
Ptfs->FileSystem->UserContext = Ptfs;
Result = FspFileSystemSetMountPoint(Ptfs->FileSystem, MountPoint);
if (!NT_SUCCESS(Result))
goto exit;
FspFileSystemSetDebugLog(Ptfs->FileSystem, DebugFlags);
Result = STATUS_SUCCESS;
exit:
if (NT_SUCCESS(Result))
*PPtfs = Ptfs;
else if (0 != Ptfs)
PtfsDelete(Ptfs);
return Result;
}
static VOID PtfsDelete(PTFS *Ptfs)
{
if (0 != Ptfs->FileSystem)
FspFileSystemDelete(Ptfs->FileSystem);
if (0 != Ptfs->Path)
free(Ptfs->Path);
free(Ptfs);
}
static NTSTATUS EnableBackupRestorePrivileges(VOID)
{
union
{
TOKEN_PRIVILEGES P;
UINT8 B[sizeof(TOKEN_PRIVILEGES) + sizeof(LUID_AND_ATTRIBUTES)];
} Privileges;
HANDLE Token;
Privileges.P.PrivilegeCount = 2;
Privileges.P.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
Privileges.P.Privileges[1].Attributes = SE_PRIVILEGE_ENABLED;
if (!LookupPrivilegeValueW(0, SE_BACKUP_NAME, &Privileges.P.Privileges[0].Luid) ||
!LookupPrivilegeValueW(0, SE_RESTORE_NAME, &Privileges.P.Privileges[1].Luid))
return FspNtStatusFromWin32(GetLastError());
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &Token))
return FspNtStatusFromWin32(GetLastError());
if (!AdjustTokenPrivileges(Token, FALSE, &Privileges.P, 0, 0, 0))
{
CloseHandle(Token);
return FspNtStatusFromWin32(GetLastError());
}
CloseHandle(Token);
return STATUS_SUCCESS;
}
static ULONG wcstol_deflt(wchar_t *w, ULONG deflt)
{
wchar_t *endp;
ULONG ul = wcstol(w, &endp, 0);
return L'\0' != w[0] && L'\0' == *endp ? ul : deflt;
}
static NTSTATUS SvcStart(FSP_SERVICE *Service, ULONG argc, PWSTR *argv)
{
#define argtos(v) if (arge > ++argp) v = *argp; else goto usage
#define argtol(v) if (arge > ++argp) v = wcstol_deflt(*argp, v); else goto usage
wchar_t **argp, **arge;
PWSTR DebugLogFile = 0;
ULONG DebugFlags = 0;
PWSTR VolumePrefix = 0;
PWSTR PassThrough = 0;
PWSTR MountPoint = 0;
HANDLE DebugLogHandle = INVALID_HANDLE_VALUE;
WCHAR PassThroughBuf[MAX_PATH];
PTFS *Ptfs = 0;
NTSTATUS Result;
for (argp = argv + 1, arge = argv + argc; arge > argp; argp++)
{
if (L'-' != argp[0][0])
break;
switch (argp[0][1])
{
case L'?':
goto usage;
case L'd':
argtol(DebugFlags);
break;
case L'D':
argtos(DebugLogFile);
break;
case L'm':
argtos(MountPoint);
break;
case L'p':
argtos(PassThrough);
break;
case L'u':
argtos(VolumePrefix);
break;
default:
goto usage;
}
}
if (arge > argp)
goto usage;
if (0 == PassThrough && 0 != VolumePrefix)
{
PWSTR P;
P = wcschr(VolumePrefix, L'\\');
if (0 != P && L'\\' != P[1])
{
P = wcschr(P + 1, L'\\');
if (0 != P &&
(
(L'A' <= P[1] && P[1] <= L'Z') ||
(L'a' <= P[1] && P[1] <= L'z')
) &&
L'$' == P[2])
{
StringCbPrintf(PassThroughBuf, sizeof PassThroughBuf, L"%c:%s", P[1], P + 3);
PassThrough = PassThroughBuf;
}
}
}
if (0 == PassThrough || 0 == MountPoint)
goto usage;
EnableBackupRestorePrivileges();
if (0 != DebugLogFile)
{
if (0 == wcscmp(L"-", DebugLogFile))
DebugLogHandle = GetStdHandle(STD_ERROR_HANDLE);
else
DebugLogHandle = CreateFileW(
DebugLogFile,
FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
0);
if (INVALID_HANDLE_VALUE == DebugLogHandle)
{
fail(L"cannot open debug log file");
goto usage;
}
FspDebugLogSetHandle(DebugLogHandle);
}
Result = PtfsCreate(PassThrough, VolumePrefix, MountPoint, DebugFlags, &Ptfs);
if (!NT_SUCCESS(Result))
{
fail(L"cannot create file system");
goto exit;
}
Result = FspFileSystemStartDispatcher(Ptfs->FileSystem, 0);
if (!NT_SUCCESS(Result))
{
fail(L"cannot start file system");
goto exit;
}
MountPoint = FspFileSystemMountPoint(Ptfs->FileSystem);
info(L"%s%s%s -p %s -m %s",
L"" PROGNAME,
0 != VolumePrefix && L'\0' != VolumePrefix[0] ? L" -u " : L"",
0 != VolumePrefix && L'\0' != VolumePrefix[0] ? VolumePrefix : L"",
PassThrough,
MountPoint);
Service->UserContext = Ptfs;
Result = STATUS_SUCCESS;
exit:
if (!NT_SUCCESS(Result) && 0 != Ptfs)
PtfsDelete(Ptfs);
return Result;
usage:
static wchar_t usage[] = L""
"usage: %s OPTIONS\n"
"\n"
"options:\n"
" -d DebugFlags [-1: enable all debug logs]\n"
" -D DebugLogFile [file path; use - for stderr]\n"
" -u \\Server\\Share [UNC prefix (single backslash)]\n"
" -p Directory [directory to expose as pass through file system]\n"
" -m MountPoint [X:|*|directory]\n";
fail(usage, L"" PROGNAME);
return STATUS_UNSUCCESSFUL;
#undef argtos
#undef argtol
}
static NTSTATUS SvcStop(FSP_SERVICE *Service)
{
PTFS *Ptfs = Service->UserContext;
FspFileSystemStopDispatcher(Ptfs->FileSystem);
PtfsDelete(Ptfs);
return STATUS_SUCCESS;
}
int wmain(int argc, wchar_t **argv)
{
if (!NT_SUCCESS(FspLoad(0)))
return ERROR_DELAY_LOAD_FAILED;
return FspServiceRun(L"" PROGNAME, SvcStart, SvcStop, 0);
}

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "passthrough", "passthrough.vcxproj", "{9E0E5997-7316-4818-A130-00B3AF1AD354}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Debug|x64.ActiveCfg = Debug|x64
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Debug|x64.Build.0 = Debug|x64
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Debug|x86.ActiveCfg = Debug|Win32
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Debug|x86.Build.0 = Debug|Win32
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Release|x64.ActiveCfg = Release|x64
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Release|x64.Build.0 = Release|x64
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Release|x86.ActiveCfg = Release|Win32
{9E0E5997-7316-4818-A130-00B3AF1AD354}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,182 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="passthrough.c" />
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{9E0E5997-7316-4818-A130-00B3AF1AD354}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>passthrough</RootNamespace>
<WindowsTargetPlatformVersion>$(LatestTargetPlatformVersion)</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>$(DefaultPlatformToolset)</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
<IntDir>$(SolutionDir)build\$(ProjectName).build\$(Configuration)\$(PlatformTarget)\</IntDir>
<TargetName>$(ProjectName)-$(PlatformTarget)</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\WinFsp\inc</AdditionalIncludeDirectories>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(MSBuildProgramFiles32)\WinFsp\lib\winfsp-$(PlatformTarget).lib;%(AdditionalDependencies)</AdditionalDependencies>
<DelayLoadDLLs>winfsp-$(PlatformTarget).dll</DelayLoadDLLs>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="passthrough.c">
<Filter>Source</Filter>
</ClCompile>
</ItemGroup>
</Project>