Lua `file` library implementation for a GMod-style roleplay framework. Maps file.Read/Write/Append/Delete/CreateDir/IsDir/Size/Exists/Find onto FileSystem.Data under a per-realm root, with path validation, extension restrictions and folder quotas.
using System;
using System.Linq;
using System.Text.RegularExpressions;
using RoleplayFramework.Lua;
namespace RoleplayFramework.Scripting;
/// <summary>
/// GMod's file functions for the <c>"DATA"</c> path: a private folder per realm where Lua may read and write text.
///
/// file.Read(path, "DATA") file.Write(path, text) file.Append(path, text) file.Delete(path)
/// file.CreateDir(dir) file.IsDir(dir, "DATA") file.Size(path, "DATA") file.Exists(path, "DATA")
/// file.Find(pattern, "DATA") → files, folders
/// Without "DATA" (or with "LUA"), file.Find/Exists keep looking at the gamemode's own scripts.
///
/// Folders: the server realm uses data/roleplay/data/<gamemode>/; the client realm a folder per server
/// (data/roleplay/clientdata/<server>/), so one server can't read or fill another's files.
/// Rules: relative paths of a-z, 0-9, _ - . and /, no "..", writes only to .txt .json .dat .csv files (like GMod).
/// Limits: 4 MB per file; per folder 100 MB / 2,000 files on the server, 20 MB / 500 files on a client.
/// </summary>
public static class LuaDataFiles
{
static readonly Regex PathPattern = new( @"^[a-z0-9_\-.]+(/[a-z0-9_\-.]+)*$" );
static readonly string[] WritableExtensions = { ".txt", ".json", ".dat", ".csv" };
const long MaxFileBytes = 4L * 1024 * 1024;
static BaseFileSystem Fs => FileSystem.Data;
static string Root( LuaRealm realm )
{
if ( realm.Kind == LuaRealmKind.Server ) return $"roleplay/data/{realm.Gamemode?.Id ?? "none"}";
var server = Networking.IsActive && !Networking.IsHost ? LuaContent.ServerKey() : "local";
return $"roleplay/clientdata/{server}";
}
static (long Bytes, int Files) Quota( LuaRealm realm ) => realm.Kind == LuaRealmKind.Server
? (100L * 1024 * 1024, 2000) : (20L * 1024 * 1024, 500);
static string Resolve( LuaRealm realm, string path, string fname, bool allowEmpty = false )
{
path = (path ?? "").Replace( '\\', '/' ).Trim( '/' ).ToLowerInvariant();
if ( path.Length == 0 && allowEmpty ) return Root( realm );
if ( path.Length > 200 || path.Contains( ".." ) || !PathPattern.IsMatch( path ) )
throw LuaState.ArgError( 0, fname, $"'{path}' is not a valid data path (a-z, 0-9, _ - . and /, no '..')" );
return $"{Root( realm )}/{path}";
}
static bool IsData( LuaValue[] a, int i ) => LuaState.Arg( a, i ).IsString && LuaState.Arg( a, i ).AsString.Equals( "DATA", StringComparison.OrdinalIgnoreCase );
static void CheckWrite( LuaRealm realm, string full, string fname, long addBytes )
{
if ( !WritableExtensions.Any( e => full.EndsWith( e ) ) )
throw LuaState.ArgError( 0, fname, "only .txt, .json, .dat and .csv files can be written" );
var (maxBytes, maxFiles) = Quota( realm );
var root = Root( realm );
long used = 0;
int files = 0;
if ( Fs.DirectoryExists( root ) )
{
foreach ( var f in Fs.FindFile( root, "*", true ) )
{
files++;
used += Fs.FileSize( $"{root}/{f}" );
}
}
var existing = Fs.FileExists( full ) ? Fs.FileSize( full ) : 0;
if ( existing == 0 && files >= maxFiles ) throw new LuaRuntimeException( $"{fname}: too many data files (limit {maxFiles})" );
if ( used + addBytes > maxBytes ) throw new LuaRuntimeException( $"{fname}: data folder full (limit {maxBytes / 1024 / 1024} MB)" );
}
static void EnsureDir( string full )
{
var dir = full.Substring( 0, full.LastIndexOf( '/' ) );
if ( !Fs.DirectoryExists( dir ) ) Fs.CreateDirectory( dir );
}
public static void Register( LuaRealm realm )
{
var t = realm.State.GetOrCreateLibrary( "file" );
var luaFind = t.Get( "Find" );
var luaExists = t.Get( "Exists" );
LuaState.Register( t, "Read", ( s, a ) =>
{
var path = LuaState.CheckString( a, 0, "file.Read" );
if ( !IsData( a, 1 ) && !LuaState.Arg( a, 1 ).IsNil ) return new[] { LuaValue.Nil }; // GMod: other paths not readable here
var full = Resolve( realm, path, "file.Read" );
if ( !Fs.FileExists( full ) ) return new[] { LuaValue.Nil };
if ( Fs.FileSize( full ) > MaxFileBytes ) throw new LuaRuntimeException( "file.Read: file larger than 4 MB" );
return new LuaValue[] { Fs.ReadAllText( full ) };
} );
LuaState.Register( t, "Write", ( s, a ) =>
{
var full = Resolve( realm, LuaState.CheckString( a, 0, "file.Write" ), "file.Write" );
var text = s.ToStringMeta( LuaState.Arg( a, 1 ) );
if ( text.Length > MaxFileBytes ) throw new LuaRuntimeException( "file.Write: more than 4 MB" );
var existing = Fs.FileExists( full ) ? Fs.FileSize( full ) : 0;
CheckWrite( realm, full, "file.Write", text.Length - existing );
EnsureDir( full );
Fs.WriteAllText( full, text );
return null;
} );
LuaState.Register( t, "Append", ( s, a ) =>
{
var full = Resolve( realm, LuaState.CheckString( a, 0, "file.Append" ), "file.Append" );
var text = s.ToStringMeta( LuaState.Arg( a, 1 ) );
var old = Fs.FileExists( full ) ? Fs.ReadAllText( full ) : "";
if ( old.Length + text.Length > MaxFileBytes ) throw new LuaRuntimeException( "file.Append: file would be larger than 4 MB" );
CheckWrite( realm, full, "file.Append", text.Length );
EnsureDir( full );
Fs.WriteAllText( full, old + text );
return null;
} );
LuaState.Register( t, "Delete", ( s, a ) =>
{
var full = Resolve( realm, LuaState.CheckString( a, 0, "file.Delete" ), "file.Delete" );
if ( Fs.FileExists( full ) ) Fs.DeleteFile( full );
else if ( Fs.DirectoryExists( full ) && !Fs.FindFile( full, "*", true ).Any() ) Fs.DeleteDirectory( full, false ); // only empty folders
return null;
} );
LuaState.Register( t, "CreateDir", ( s, a ) =>
{
var full = Resolve( realm, LuaState.CheckString( a, 0, "file.CreateDir" ), "file.CreateDir" );
if ( !Fs.DirectoryExists( full ) ) Fs.CreateDirectory( full );
return null;
} );
LuaState.Register( t, "IsDir", ( s, a ) =>
{
if ( !IsData( a, 1 ) ) return new LuaValue[] { false };
return new LuaValue[] { Fs.DirectoryExists( Resolve( realm, LuaState.CheckString( a, 0, "file.IsDir" ), "file.IsDir" ) ) };
} );
LuaState.Register( t, "Size", ( s, a ) =>
{
if ( !IsData( a, 1 ) ) return new LuaValue[] { -1 };
var full = Resolve( realm, LuaState.CheckString( a, 0, "file.Size" ), "file.Size" );
return new LuaValue[] { Fs.FileExists( full ) ? Fs.FileSize( full ) : -1 };
} );
// Find/Exists: "DATA" looks in the data folder, anything else in the gamemode's scripts (as before).
LuaState.Register( t, "Exists", ( s, a ) =>
{
if ( !IsData( a, 1 ) ) return s.Call( luaExists, LuaState.Arg( a, 0 ) );
var full = Resolve( realm, LuaState.CheckString( a, 0, "file.Exists" ), "file.Exists" );
return new LuaValue[] { Fs.FileExists( full ) || Fs.DirectoryExists( full ) };
} );
LuaState.Register( t, "Find", ( s, a ) =>
{
if ( !IsData( a, 1 ) ) return s.Call( luaFind, LuaState.Arg( a, 0 ) );
var pattern = LuaState.CheckString( a, 0, "file.Find" ).Replace( '\\', '/' ).ToLowerInvariant();
int slash = pattern.LastIndexOf( '/' );
var dir = slash > 0 ? Resolve( realm, pattern.Substring( 0, slash ), "file.Find" ) : Root( realm );
var mask = slash >= 0 ? pattern.Substring( slash + 1 ) : pattern;
if ( !Regex.IsMatch( mask, @"^[a-z0-9_\-.*]{1,64}$" ) ) throw LuaState.ArgError( 0, "file.Find", "invalid file mask" );
var files = new LuaTable();
var dirs = new LuaTable();
if ( Fs.DirectoryExists( dir ) )
{
foreach ( var f in Fs.FindFile( dir, mask, false ).OrderBy( x => x, StringComparer.Ordinal ) ) files.Append( f );
foreach ( var d in Fs.FindDirectory( dir, mask, false ).OrderBy( x => x, StringComparer.Ordinal ) ) dirs.Append( d );
}
return new LuaValue[] { files, dirs };
} );
}
}