-
-
Notifications
You must be signed in to change notification settings - Fork 386
Feature: Whitelist overhaul #3107
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SakuraIsayeki
wants to merge
18
commits into
Pryaxis:general-devel
Choose a base branch
from
SakuraIsayeki:feature/whitelist
base: general-devel
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
d50ec7a
feat: implement IP whitelist management service
SakuraIsayeki d2f9ecc
style: update IP comments for private ranges
SakuraIsayeki 699e5d7
feat: Use new whitelist system
SakuraIsayeki e8a3ebf
refactor: Improve default whitelist file creation
SakuraIsayeki a9fe6c6
refactor: move whitelist management to static property
SakuraIsayeki 933d640
feat: use new whitelist service for add command
SakuraIsayeki ae82a7e
fix: ensure newlines before appending to file
SakuraIsayeki 9e1991c
chore: Remove old whitelist check code
SakuraIsayeki 00dbbc0
style: Fix indentations and newlines
SakuraIsayeki cc0fd66
refactor: Improve whitelist command validation and feedback
SakuraIsayeki e8ac543
fix: Remove IPv6 whitelist support
SakuraIsayeki bd2497f
feat: Add whitelist reload functionality
SakuraIsayeki 9a01d9f
Merge remote-tracking branch 'upstream/general-devel' into feature/wh…
SakuraIsayeki 3a18dab
fix: Fix unwanted changes
SakuraIsayeki c97f960
fix: use bitwise AND instead of logical AND for whitelist updates
SakuraIsayeki d18b7c1
fix: Correct fs handling in addline
SakuraIsayeki eb52d11
refactor: improve whitelist command handling
SakuraIsayeki b7d8208
fix: localize logging messages for IPv6 support and invalid entries
SakuraIsayeki File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,270 @@ | ||
| /* | ||
| TShock, a server mod for Terraria | ||
| Copyright (C) 2011-2025 Pryaxis & TShock Contributors | ||
| This program is free software: you can redistribute it and/or modify | ||
| it under the terms of the GNU General Public License as published by | ||
| the Free Software Foundation, either version 3 of the License, or | ||
| (at your option) any later version. | ||
| This program is distributed in the hope that it will be useful, | ||
| but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| GNU General Public License for more details. | ||
| You should have received a copy of the GNU General Public License | ||
| along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
| #nullable enable | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Net; | ||
| using System.Threading; | ||
| using TShockAPI.Configuration; | ||
|
|
||
| namespace TShockAPI; | ||
|
|
||
| /// <summary> | ||
| /// Provides the storage for a whitelist. | ||
| /// </summary> | ||
| public sealed class Whitelist | ||
| { | ||
| private readonly FileInfo _file; | ||
| private readonly Lock _fileLock = new(); | ||
|
|
||
| private readonly HashSet<IPAddress> _whitelistAddresses = []; | ||
| private readonly HashSet<IPNetwork> _whitelistNetworks = []; | ||
|
|
||
| /// <summary> | ||
| /// Defines if the whitelist is enabled or not. | ||
| /// </summary> | ||
| /// <remarks>Shorthand to the current <see cref="TShockSettings.EnableWhitelist" /> setting.</remarks> | ||
| private bool Enabled => TShock.Config.Settings.EnableWhitelist; | ||
|
|
||
| internal const string DefaultWhitelistContent = /*lang=conf*/ | ||
| """ | ||
| # Localhost | ||
| 127.0.0.1 | ||
| ::1 | ||
| # Uncomment to allow IPs within private ranges | ||
| # 10.0.0.0/8 | ||
| # 172.16.0.0/12 | ||
| # 192.168.0.0/16 | ||
| # fe80::/10 | ||
| # fd00::/8 | ||
| """; | ||
|
|
||
| internal const char CommentPrefix = '#'; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="Whitelist"/> class. | ||
| /// Creates the whitelist file if it does not exist on disk. | ||
| /// </summary> | ||
| public Whitelist(string path) | ||
| { | ||
| _file = new(path); | ||
|
|
||
| if (!_file.Exists) | ||
| { | ||
| throw new FileNotFoundException("The whitelist file does not exist", _file.FullName); | ||
| } | ||
|
|
||
| ReadWhitelistFromFile(); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Tells if a user is on the whitelist | ||
| /// </summary> | ||
| /// <param name="host">string ip of the user</param> | ||
| /// <returns>true/false</returns> | ||
| public bool IsWhitelisted(string host) | ||
| { | ||
| if (!Enabled) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| if (!IPAddress.TryParse(TShock.Utils.GetRealIP(host), out IPAddress? ip)) | ||
SakuraIsayeki marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| throw new ArgumentException($"The provided host '{host}' is not a valid IP address.", nameof(host)); | ||
| } | ||
|
|
||
| // First check if the IP address is directly whitelisted | ||
| return _whitelistAddresses.Contains(ip) | ||
| // Otherwise is it contained within a whitelisted network? | ||
| || _whitelistNetworks.Any(n => n.Contains(ip)); | ||
| } | ||
|
|
||
| private void ReadWhitelistFromFile() | ||
| { | ||
| using StreamReader sr = _file.OpenText(); | ||
|
|
||
| int i = 0; | ||
| while (!sr.EndOfStream) | ||
| { | ||
| ReadWhitelistLine(sr.ReadLine(), i); | ||
| i++; | ||
| } | ||
| } | ||
|
|
||
| private void ReadWhitelistLine(scoped ReadOnlySpan<char> content, int line) | ||
| { | ||
| // Ignore blank line or comment | ||
| if (content is [] or [CommentPrefix, ..]) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| // Try parse first IP range, which uses CIDR sep as discriminator. | ||
| if (IPNetwork.TryParse(content, out IPNetwork range)) | ||
| { | ||
| _whitelistNetworks.Add(range); | ||
| } | ||
| else if (IPAddress.TryParse(content, out IPAddress? ip)) | ||
| { | ||
| _whitelistAddresses.Add(ip); | ||
| } | ||
| else | ||
| { | ||
| // If we reach here, the line is not a valid IP address or network. | ||
| // We could throw this, but for now we just log and ignore it. | ||
| TShock.Log.Warn($"Invalid whitelist entry at line {line}: \"{content.ToString()}\", skipped"); | ||
SakuraIsayeki marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
SakuraIsayeki marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Adds an IP address or network to the whitelist. | ||
| /// </summary> | ||
| /// <param name="ip">The IP address or network to add.</param> | ||
| /// <returns>true if the address or network was added successfully; otherwise, false.</returns> | ||
| public bool AddToWhitelist(scoped ReadOnlySpan<char> ip) | ||
| { | ||
| if (IPNetwork.TryParse(ip, out IPNetwork range)) | ||
| { | ||
| return AddToWhitelist(range); | ||
| } | ||
|
|
||
| if (IPAddress.TryParse(ip, out IPAddress? address)) | ||
| { | ||
| return AddToWhitelist(address); | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Removes an IP address or network from the whitelist. | ||
| /// </summary> | ||
| /// <param name="ip">The IP address or network to remove.</param> | ||
| /// <returns>>true if the address or network was removed successfully; otherwise, false.</returns> | ||
| public bool RemoveFromWhitelist(scoped ReadOnlySpan<char> ip) | ||
| { | ||
| if (IPNetwork.TryParse(ip, out IPNetwork range)) | ||
| { | ||
| return RemoveFromWhitelist(range); | ||
| } | ||
|
|
||
| if (IPAddress.TryParse(ip, out IPAddress? address)) | ||
| { | ||
| return RemoveFromWhitelist(address); | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
|
|
||
| private bool AddToWhitelist(IPAddress ip) | ||
| => _whitelistAddresses.Add(ip) | ||
| && AddLine(ip.ToString()); | ||
|
|
||
| private bool AddToWhitelist(IPNetwork network) | ||
| => _whitelistNetworks.Add(network) | ||
| && AddLine(network.ToString()); | ||
|
|
||
| private bool RemoveFromWhitelist(IPAddress ip) | ||
| => _whitelistAddresses.Remove(ip) | ||
| && RemoveLine(ip.ToString()); | ||
|
|
||
| private bool RemoveFromWhitelist(IPNetwork network) | ||
| => _whitelistNetworks.Remove(network) | ||
| && RemoveLine(network.ToString()); | ||
|
|
||
| private bool AddLine(scoped ReadOnlySpan<char> content) | ||
SakuraIsayeki marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| lock (_fileLock) | ||
| { | ||
|
|
||
| using StreamWriter sw = _file.AppendText(); | ||
|
|
||
| // Case: File does not end with a newline, add one | ||
| bool needsNewLine; | ||
|
|
||
| using (FileStream fs = _file.OpenRead()) | ||
| { | ||
| fs.Seek(-1, SeekOrigin.End); | ||
| needsNewLine = fs.Length > 0 && fs.ReadByte() != '\n'; | ||
| } | ||
|
|
||
| if (needsNewLine) | ||
| { | ||
| sw.WriteLine(); | ||
| } | ||
|
|
||
| sw.WriteLine(content); | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
|
|
||
| private bool RemoveLine(scoped ReadOnlySpan<char> content) | ||
| { | ||
| if (content is []) | ||
| { | ||
| throw new ArgumentException("Content cannot be empty.", nameof(content)); | ||
| } | ||
|
|
||
| lock (_fileLock) | ||
| { | ||
| string tempFile = Path.GetTempFileName(); | ||
|
|
||
| using StreamReader sr = _file.OpenText(); | ||
| using StreamWriter sw = new(tempFile); | ||
|
|
||
| bool removed = false; | ||
|
|
||
| while (!sr.EndOfStream) | ||
| { | ||
| scoped ReadOnlySpan<char> line = sr.ReadLine(); | ||
|
|
||
| // If the line does not match the content, write it to the temp file | ||
| if (line != content) | ||
| { | ||
| sw.WriteLine(line); | ||
| } | ||
| else | ||
| { | ||
| removed = true; | ||
| } | ||
| } | ||
|
|
||
| // If we removed a line, we need to overwrite the original file | ||
| if (removed) | ||
| { | ||
| sw.Flush(); | ||
|
|
||
| _file.Delete(); | ||
| File.Move(tempFile, _file.FullName); | ||
| } | ||
| else | ||
| { | ||
| File.Delete(tempFile); | ||
| } | ||
|
|
||
| return removed; | ||
SakuraIsayeki marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.