Skip to content

Commit

Permalink
Add ServerListTools and UseNat
Browse files Browse the repository at this point in the history
  • Loading branch information
Corecii committed Feb 20, 2020
1 parent 8cf108d commit 689bee1
Show file tree
Hide file tree
Showing 42 changed files with 329 additions and 20 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ Distance.dll
x64/
x86/
[Bb]uild/
BuildLinux/
BuildWindows/
bld/
[Bb]in/
[Oo]bj/
Expand Down
16 changes: 16 additions & 0 deletions ServerBase/DistanceServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ public int MaxPlayers
Network.maxConnections = maxPlayers;
}
}

public bool UseNat = false;

public int Port = 45671;

bool reportToMasterServer = false;
Expand Down Expand Up @@ -261,6 +264,9 @@ public DistancePlayer GetDistancePlayer(int clientId)
public LocalEvent<DistancePlayer> OnPlayerValidatedEvent = new LocalEvent<DistancePlayer>();
public LocalEvent<DistancePlayer> OnPlayerValidatedPreReplicationEvent = new LocalEvent<DistancePlayer>();

public LocalEvent<NetworkConnectionError> OnFailedToConnectToMasterServerEvent = new LocalEvent<NetworkConnectionError>();
public LocalEvent<MasterServerEvent> OnMasterServerEvent = new LocalEvent<MasterServerEvent>();

///

public void Init()
Expand Down Expand Up @@ -448,6 +454,16 @@ public void OnServerInitialized()
OnServerInitializedEvent.Fire();
}

public void OnFailedToConnectToMasterServer(NetworkConnectionError error)
{
OnFailedToConnectToMasterServerEvent.Fire(error);
}

public void OnMasterServer(MasterServerEvent evt)
{
OnMasterServerEvent.Fire(evt);
}

public void RequestSubmitLobbyInfo(NetworkPlayer player)
{
DistanceServerMain.GetEvent<Events.ServerToClient.Request>().Fire(
Expand Down
15 changes: 13 additions & 2 deletions ServerBase/DistanceServerMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -342,9 +342,10 @@ public override void Awake()
Server.Init();

LoadPlugins();

Log.WriteLine($"Starting server version {Server.DistanceVersion} on port {Server.Port} (UseNat: {Server.UseNat})");

Log.WriteLine($"Starting server version {Server.DistanceVersion} on port {Server.Port}");
Network.InitializeServer(Server.MaxPlayers, Server.Port, false);
Network.InitializeServer(Server.MaxPlayers, Server.Port, Server.UseNat);
}

public List<DistanceServerPlugin> Plugins = new List<DistanceServerPlugin>();
Expand Down Expand Up @@ -673,4 +674,14 @@ public override void SubmitServerNetworkTimeSync(NetworkMessageInfo info)
num2
});
}

public override void OnFailedToConnectToMasterServer(NetworkConnectionError error)
{
Server.OnFailedToConnectToMasterServer(error);
}

public override void OnMasterServerEvent(MasterServerEvent evt)
{
Server.OnMasterServer(evt);
}
}
3 changes: 3 additions & 0 deletions ServerPlugins/BasicAutoServer/BasicAutoServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ public bool FilterWorkshopLevels(List<DistanceSearchResultItem> results)
string PrivateServerPassword = null;
int MaxPlayers = 24;
int Port = 45671;
bool UseNat = false;
bool ReportToMasterServer = true;
public double ReportToMasterServerInitialDelay = 0;
double MasterServerReRegisterFrequency = 5 * 60.0;
Expand Down Expand Up @@ -113,6 +114,7 @@ public void ReadSettings()
TryGetValue(dictionary, "ServerName", ref ServerName);
TryGetValue(dictionary, "MaxPlayers", ref MaxPlayers);
TryGetValue(dictionary, "Port", ref Port);
TryGetValue(dictionary, "UseNat", ref UseNat);
TryGetValue(dictionary, "PrivateServerPassword", ref PrivateServerPassword);
TryGetValue(dictionary, "ReportToMasterServer", ref ReportToMasterServer);
TryGetValue(dictionary, "ReportToMasterServerInitialDelay", ref ReportToMasterServerInitialDelay);
Expand Down Expand Up @@ -212,6 +214,7 @@ public override void Start()
Server.ServerName = ServerName;
Server.MaxPlayers = MaxPlayers;
Server.Port = Port;
Server.UseNat = UseNat;
if (ReportToMasterServerInitialDelay > 0)
{
Server.ReportToMasterServer = false;
Expand Down
169 changes: 169 additions & 0 deletions ServerPlugins/ServerListTools/Entry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace ServerListTools
{
public class Entry : DistanceServerPlugin
{
public override string Author { get; } = "Corecii; Discord: Corecii#3019";
public override string DisplayName { get; } = "Server List Tools";
public override int Priority { get; } = 100;
public override SemanticVersion ServerVersion => new SemanticVersion("0.1.3");

public double LogServersFrequency = -1.0;
public double HealthCheckFrequency = -1.0;
public double HealthCheckDelay = 60.0;
public double HealthCheckTimeout = 120.0;

public double LastSuccessfulHealthCheckTime = -1.0;

public void ReadSettings()
{
var filePath = new System.IO.FileInfo(Manager.ServerDirectory.FullName + "/ServerListTools.json");
if (!filePath.Exists)
{
Log.Info("No ServerListTools.json, using default settings");
return;
}
try
{
var txt = System.IO.File.ReadAllText(filePath.FullName);
var reader = new JsonFx.Json.JsonReader();
var dictionary = (Dictionary<string, object>)reader.Read(txt);
TryGetValue(dictionary, "LogServersFrequency", ref LogServersFrequency);
TryGetValue(dictionary, "HealthCheckFrequency", ref HealthCheckFrequency);
TryGetValue(dictionary, "HealthCheckDelay", ref HealthCheckDelay);
TryGetValue(dictionary, "HealthCheckTimeout", ref HealthCheckTimeout);
Log.Info("Loaded settings from ServerListTools.json");
}
catch (Exception e)
{
Log.Error($"Couldn't read ServerListTools.json. Is your json malformed?\n{e}");

}
}

bool TryGetValue<T>(Dictionary<string, object> dict, string name, ref T value)
{
try
{
value = (T)dict[name];
return true;
}
catch (Exception e)
{
return false;
}
}

public override void Start()
{
Log.Info("Server List Tools Plugin started!");
Log.Info($"My guid: {DistanceServerMain.View.owner.guid}");

ReadSettings();

if (LogServersFrequency > 0 || HealthCheckFrequency > 0)
{
Server.OnUpdateEvent.Connect(() =>
{
MasterServer.PollHostList();
});
}

if (LogServersFrequency > 0)
{
Log.Info("Will be logging servers...");
DistanceServerMainStarter.Instance.StartCoroutine(LogServers());
}
if (HealthCheckFrequency > 0)
{
Log.Info("Will be running health checks...");
DistanceServerMainStarter.Instance.StartCoroutine(HealthCheck());
}
}

public System.Collections.IEnumerator HealthCheck()
{
yield return new WaitForSeconds((float)HealthCheckDelay);
LastSuccessfulHealthCheckTime = DistanceServerMain.UnixTime;
while (true)
{
if (DistanceServerMain.UnixTime - LastSuccessfulHealthCheckTime > HealthCheckTimeout)
{
Log.Error($"Quitting because health check failed: server is not on the master server list");
Application.Quit();
}
DistanceServerMainStarter.Instance.StartCoroutine(ExitIfNotOnServerList());
yield return new WaitForSeconds((float)HealthCheckFrequency);
}
}

public System.Collections.IEnumerator LogServers()
{
while (true)
{
DistanceServerMainStarter.Instance.StartCoroutine(LogServerList());
yield return new WaitForSeconds((float)LogServersFrequency);
}
}

public System.Collections.IEnumerator ExitIfNotOnServerList()
{
MasterServer.ClearHostList();
MasterServer.RequestHostList("Distance");
yield return new WaitForServerList();
var servers = MasterServer.PollHostList();
var hasMe = servers.Any((server) =>
{
return server.guid == DistanceServerMain.View.owner.guid;
});
if (hasMe)
{
LastSuccessfulHealthCheckTime = DistanceServerMain.UnixTime;
}
yield break;
}

public System.Collections.IEnumerator LogServerList()
{
MasterServer.ClearHostList();
MasterServer.RequestHostList("Distance");
yield return new WaitForServerList();
var servers = MasterServer.PollHostList();
var i = 0;
Log.Debug("Server list:");
foreach (var server in servers)
{
i++;
Log.Debug($"{i}: {String.Join(",", server.ip)}:{server.port} {server.gameName} {server.gameType} {server.connectedPlayers}/{server.playerLimit} {server.useNat} {(server.passwordProtected ? "private" : "public")} {server.comment} {server.guid}");
}
yield break;
}
}

public class WaitForServerList : UnityEngine.CustomYieldInstruction
{
public override bool keepWaiting => !done;

bool done = false;
LocalEvent<MasterServerEvent>.EventConnection conn;

public WaitForServerList()
{
conn = DistanceServerMain.Instance.Server.OnMasterServerEvent.Connect(evt =>
{
if (evt == MasterServerEvent.HostListReceived)
{
conn.Disconnect();
conn = null;
done = true;
}
});
}
}
}
36 changes: 36 additions & 0 deletions ServerPlugins/ServerListTools/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ServerListTools")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServerListTools")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("77836de9-5b0f-44bb-a70c-c9187a5b7a28")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
5 changes: 5 additions & 0 deletions ServerPlugins/WorkshopSearch/DistanceSearchRetriever.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ public System.Collections.IEnumerator Retrieve()
}
Log.DebugLine("Retrieve");
var levelIds = new List<string>();

if (searchResult.Result == null)
{
Log.Warn("HtmlAgilityPack might not be loaded");
}
foreach (var item in searchResult.Result.Items)
{
levelIds.Add(item.PublishedFileId);
Expand Down
8 changes: 8 additions & 0 deletions ServerPlugins/WorkshopSearch/WorkshopSearchRetriever.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,10 @@ public System.Collections.IEnumerator RetrieveFiles()
{
Finished = true;
Error = request.error;
if (Error == null)
{
Error = "Unkown error";
}
yield break;
}

Expand Down Expand Up @@ -462,6 +466,10 @@ public System.Collections.IEnumerator RetrieveFiles()
catch (Exception e)
{
Error = e.ToString();
if (Error == null)
{
Error = "Unkown error";
}
}

Finished = true;
Expand Down
2 changes: 2 additions & 0 deletions ServerUnity/Assets/DistanceServerMainBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ public GameObject gameObject
public abstract void OnServerInitialized();
public abstract void OnPlayerConnected(NetworkPlayer player);
public abstract void OnPlayerDisconnected(NetworkPlayer player);
public abstract void OnFailedToConnectToMasterServer(NetworkConnectionError error);
public abstract void OnMasterServerEvent(MasterServerEvent evt);
public abstract void OnDestroy();
public abstract void ReceiveBroadcastAllEvent(byte[] bytes, NetworkMessageInfo info);
public abstract void ReceiveClientToServerEvent(byte[] bytes, NetworkMessageInfo info);
Expand Down
Loading

0 comments on commit 689bee1

Please sign in to comment.