Reduce output verbosity, default session cache

- Memory session cache will be used by default
 - Verbose messages are now hidden by default
 - Improve ping procedure's Forge handling
 - Fix 1.8.9 and 1.9.0 in mcversion setting
 - SessionCache.cs: fix LF into CRLF
 - Use 1.9 translations instead of 1.8
This commit is contained in:
ORelio 2016-03-10 13:29:05 +01:00
parent d44a76e82c
commit d45f75f9f4
11 changed files with 119 additions and 105 deletions

View file

@ -123,7 +123,8 @@ namespace MinecraftClient.Protocol.Handlers
}
}
ConsoleIO.WriteLineFormatted("§8Translations file loaded.");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Translations file loaded.");
}
else //No external dictionnary found.
{

View file

@ -449,7 +449,7 @@ namespace MinecraftClient.Protocol.Handlers
if (serverID == "-")
ConsoleIO.WriteLineFormatted("§8Server is in offline mode.");
else
else if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Handshake successful. (Server ID: " + serverID + ')');
return StartEncryption(uuid, username, sessionID, token, serverID, PublicServerkey);
@ -462,7 +462,8 @@ namespace MinecraftClient.Protocol.Handlers
System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();
ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
if (serverIDhash != "-")
{

View file

@ -451,13 +451,15 @@ namespace MinecraftClient.Protocol.Handlers
byte fmlProtocolVersion = readNextByte(packetData);
// There's another value afterwards for the dimension, but we don't need it.
ConsoleIO.WriteLineFormatted("§8Forge protocol version : " + fmlProtocolVersion);
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Forge protocol version : " + fmlProtocolVersion);
// Tell the server we're running the same version.
SendForgeHandshakePacket(FMLHandshakeDiscriminator.ClientHello, new byte[] { fmlProtocolVersion });
// Then tell the server that we're running the same mods.
ConsoleIO.WriteLineFormatted("§8Sending falsified mod list to server...");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Sending falsified mod list to server...");
byte[][] mods = new byte[forgeInfo.Mods.Count][];
for (int i = 0; i < forgeInfo.Mods.Count; i++)
{
@ -476,7 +478,8 @@ namespace MinecraftClient.Protocol.Handlers
Thread.Sleep(2000);
ConsoleIO.WriteLineFormatted("§8Accepting server mod list...");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Accepting server mod list...");
// Tell the server that yes, we are OK with the mods it has
// even though we don't actually care what mods it has.
@ -497,8 +500,8 @@ namespace MinecraftClient.Protocol.Handlers
// with blocks and items.
int registrySize = readNextVarInt(packetData);
ConsoleIO.WriteLineFormatted("§8Received registry " +
"with " + registrySize + " entries");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Received registry with " + registrySize + " entries");
fmlHandshakeState = FMLHandshakeClientState.PENDINGCOMPLETE;
}
@ -509,14 +512,10 @@ namespace MinecraftClient.Protocol.Handlers
bool hasNextRegistry = readNextBool(packetData);
string registryName = readNextString(packetData);
int registrySize = readNextVarInt(packetData);
ConsoleIO.WriteLineFormatted("§8Received registry " + registryName +
" with " + registrySize + " entries");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Received registry " + registryName + " with " + registrySize + " entries");
if (!hasNextRegistry)
{
fmlHandshakeState = FMLHandshakeClientState.PENDINGCOMPLETE;
}
}
return false;
@ -525,9 +524,8 @@ namespace MinecraftClient.Protocol.Handlers
// Just say yes.
if (discriminator != FMLHandshakeDiscriminator.HandshakeAck)
return false;
ConsoleIO.WriteLineFormatted("§8Accepting server registries...");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Accepting server registries...");
SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
new byte[] { (byte)FMLHandshakeClientState.PENDINGCOMPLETE });
fmlHandshakeState = FMLHandshakeClientState.COMPLETE;
@ -540,8 +538,8 @@ namespace MinecraftClient.Protocol.Handlers
SendForgeHandshakePacket(FMLHandshakeDiscriminator.HandshakeAck,
new byte[] { (byte)FMLHandshakeClientState.COMPLETE });
ConsoleIO.WriteLine("Forge server connection complete!");
if (Settings.DebugMessages)
ConsoleIO.WriteLine("Forge server connection complete!");
fmlHandshakeState = FMLHandshakeClientState.DONE;
return true;
}
@ -582,7 +580,7 @@ namespace MinecraftClient.Protocol.Handlers
private void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, bool hasSkyLight, bool chunksContinuous, List<byte> cache)
{
if (protocolversion >= MC19Version && chunksContinuous && chunkMask == 0)
if (protocolversion < MC19Version && chunksContinuous && chunkMask == 0)
{
//Unload the entire chunk column
handler.GetWorld()[chunkX, chunkZ] = null;
@ -1124,7 +1122,7 @@ namespace MinecraftClient.Protocol.Handlers
{
readNextPacket(ref packetID, packetData);
if (packetID == 0x40) // Disconect
if (packetID == 0x40) // Disconnect
{
handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, ChatParser.ParseText(readNextString(packetData)));
return false;
@ -1148,7 +1146,8 @@ namespace MinecraftClient.Protocol.Handlers
System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();
ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
if (Settings.DebugMessages)
ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
if (serverIDhash != "-")
{
@ -1408,8 +1407,6 @@ namespace MinecraftClient.Protocol.Handlers
if (protocolversion < 47 && version.Split(' ', '/').Contains("1.8"))
protocolversion = ProtocolHandler.MCVer2ProtocolVersion("1.8.0");
ConsoleIO.WriteLineFormatted("§8Server version : " + version + " (protocol v" + protocolversion + ").");
// Check for forge on the server.
if (jsonData.Properties.ContainsKey("modinfo") && jsonData.Properties["modinfo"].Type == Json.JSONData.DataType.Object)
{
@ -1418,13 +1415,24 @@ namespace MinecraftClient.Protocol.Handlers
{
forgeInfo = new ForgeInfo(modData);
ConsoleIO.WriteLineFormatted("§8Server is running forge. Mod list:");
foreach (ForgeInfo.ForgeMod mod in forgeInfo.Mods)
if (forgeInfo.Mods.Any())
{
ConsoleIO.WriteLineFormatted("§8 " + mod.ToString());
if (Settings.DebugMessages)
{
ConsoleIO.WriteLineFormatted("§8Server is running Forge. Mod list:");
foreach (ForgeInfo.ForgeMod mod in forgeInfo.Mods)
{
ConsoleIO.WriteLineFormatted("§8 " + mod.ToString());
}
}
else ConsoleIO.WriteLineFormatted("§8Server is running Forge.");
}
else forgeInfo = null;
}
}
ConsoleIO.WriteLineFormatted("§8Server version : " + version + " (protocol v" + protocolversion + (forgeInfo != null ? ", with Forge)." : ")."));
return true;
}
}

View file

@ -90,8 +90,8 @@ namespace MinecraftClient.Protocol
void UnregisterPluginChannel(string channel, ChatBot bot);
/// <summary>
/// Sends a plugin channel packet to the server. See http://wiki.vg/Plugin_channel for more information
/// about plugin channels.
/// Sends a plugin channel packet to the server.
/// See http://wiki.vg/Plugin_channel for more information about plugin channels.
/// </summary>
/// <param name="channel">The channel to send the packet on.</param>
/// <param name="data">The payload for the packet.</param>

View file

@ -123,8 +123,9 @@ namespace MinecraftClient.Protocol
case "1.8.6":
case "1.8.7":
case "1.8.8":
return 47;
case "1.8.9":
return 47;
case "1.9.0":
return 107;
default:
return 0;

View file

@ -0,0 +1,4 @@
namespace MinecraftClient.Protocol.SessionCache
{
public enum CacheType { None, Memory, Disk };
}

View file

@ -0,0 +1,177 @@
using MinecraftClient.Protocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Timers;
namespace MinecraftClient.Protocol.SessionCache
{
/// <summary>
/// Handle sessions caching and storage.
/// </summary>
public static class SessionCache
{
private const string SessionCacheFile = "SessionCache.db";
private static Dictionary<string, SessionToken> sessions = new Dictionary<string, SessionToken>();
private static FileSystemWatcher cachemonitor = new FileSystemWatcher();
private static Timer updatetimer = new Timer(100);
private static List<KeyValuePair<string, SessionToken>> pendingadds = new List<KeyValuePair<string, SessionToken>>();
private static BinaryFormatter formatter = new BinaryFormatter();
/// <summary>
/// Retrieve whether SessionCache contains a session for the given login.
/// </summary>
/// <param name="login">User login used with Minecraft.net</param>
/// <returns>TRUE if session is available</returns>
public static bool Contains(string login)
{
return sessions.ContainsKey(login);
}
/// <summary>
/// Store a session and save it to disk if required.
/// </summary>
/// <param name="login">User login used with Minecraft.net</param>
/// <param name="session">User session token used with Minecraft.net</param>
public static void Store(string login, SessionToken session)
{
if (Contains(login))
{
sessions[login] = session;
}
else
{
sessions.Add(login, session);
}
if (Settings.SessionCaching == CacheType.Disk && updatetimer.Enabled == true)
{
pendingadds.Add(new KeyValuePair<string, SessionToken>(login, session));
}
else if (Settings.SessionCaching == CacheType.Disk)
{
SaveToDisk();
}
}
/// <summary>
/// Retrieve a session token for the given login.
/// </summary>
/// <param name="login">User login used with Minecraft.net</param>
/// <returns>SessionToken for given login</returns>
public static SessionToken Get(string login)
{
return sessions[login];
}
/// <summary>
/// Initialize cache monitoring to keep cache updated with external changes.
/// </summary>
/// <returns>TRUE if session tokens are seeded from file</returns>
public static bool InitializeDiskCache()
{
cachemonitor.Path = AppDomain.CurrentDomain.BaseDirectory;
cachemonitor.IncludeSubdirectories = false;
cachemonitor.Filter = SessionCacheFile;
cachemonitor.NotifyFilter = NotifyFilters.LastWrite;
cachemonitor.Changed += new FileSystemEventHandler(OnChanged);
cachemonitor.EnableRaisingEvents = true;
updatetimer.Elapsed += HandlePending;
return LoadFromDisk();
}
/// <summary>
/// Reloads cache on external cache file change.
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Event data</param>
private static void OnChanged(object sender, FileSystemEventArgs e)
{
updatetimer.Stop();
updatetimer.Start();
}
/// <summary>
/// Called after timer elapsed. Reads disk cache and adds new/modified sessions back.
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Event data</param>
private static void HandlePending(object sender, ElapsedEventArgs e)
{
LoadFromDisk();
foreach(KeyValuePair<string, SessionToken> pending in pendingadds.ToArray())
{
Store(pending.Key, pending.Value);
pendingadds.Remove(pending);
}
}
/// <summary>
/// Reads cache file and loads SessionTokens into SessionCache.
/// </summary>
/// <returns>True if data is successfully loaded</returns>
private static bool LoadFromDisk()
{
if (File.Exists(SessionCacheFile))
{
try
{
using (FileStream fs = new FileStream(SessionCacheFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
sessions = (Dictionary<string, SessionToken>)formatter.Deserialize(fs);
return true;
}
}
catch (IOException ex)
{
Console.WriteLine("Error reading cached sessions from disk: " + ex.Message);
}
catch (SerializationException)
{
Console.WriteLine("Malformed sessions from cache file ");
}
}
return false;
}
/// <summary>
/// Saves SessionToken's from SessionCache into cache file.
/// </summary>
private static void SaveToDisk()
{
bool fileexists = File.Exists(SessionCacheFile);
using (FileStream fs = new FileStream(SessionCacheFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
cachemonitor.EnableRaisingEvents = false;
// delete existing file contents
if (fileexists)
{
fs.SetLength(0);
fs.Flush();
}
formatter.Serialize(fs, sessions);
cachemonitor.EnableRaisingEvents = true;
}
}
}
}