Fixed SCA warnings

This commit is contained in:
high 2011-08-06 16:49:40 -04:00
parent 72d49d421c
commit 56eca71853
13 changed files with 299 additions and 236 deletions

View file

@ -797,9 +797,10 @@ namespace TShockAPI
{
if (args.Parameters.Count == 1)
{
TextWriter tw = new StreamWriter(FileTools.WhitelistPath, true);
using (var tw = new StreamWriter(FileTools.WhitelistPath, true))
{
tw.WriteLine(args.Parameters[0]);
tw.Close();
}
args.Player.SendMessage("Added " + args.Parameters[0] + " to the whitelist.");
}
}
@ -862,31 +863,38 @@ namespace TShockAPI
ThreadPool.QueueUserWorkItem(UpdateManager.CheckUpdate);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static void UpdateNow(CommandArgs args)
{
Process TServer = Process.GetCurrentProcess();
StreamWriter sw = new StreamWriter("pid");
using (var sw = new StreamWriter("pid"))
{
sw.Write(TServer.Id);
sw.Close();
}
sw = new StreamWriter("pn");
using (var sw = new StreamWriter("pn"))
{
sw.Write(TServer.ProcessName + " " + Environment.CommandLine);
sw.Close();
}
WebClient client = new WebClient();
using (var client = new WebClient())
{
client.Headers.Add("user-agent", "TShock");
byte[] updatefile = client.DownloadData("http://tsupdate.shankshock.com/UpdateTShock.exe");
BinaryWriter bw = new BinaryWriter(new FileStream("UpdateTShock.exe", FileMode.Create));
using (var bw = new BinaryWriter(new FileStream("UpdateTShock.exe", FileMode.Create)))
{
bw.Write(updatefile);
bw.Close();
}
}
Process.Start(new ProcessStartInfo("UpdateTShock.exe"));
Tools.ForceKickAll("Server shutting down for update!");
WorldGen.saveWorld();
Netplay.disconnect = true;
}
#endregion Server Maintenence Commands

View file

@ -54,6 +54,7 @@ namespace TShockAPI.DB
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public void ImportOld()
{
String file = Path.Combine(TShock.SavePath, "regions.xml");
@ -62,9 +63,8 @@ namespace TShockAPI.DB
Region region;
Rectangle rect;
using (var sr = new StreamReader(file))
{
using (var reader = XmlReader.Create(sr))
using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings { CloseInput = true }))
{
// Parse the file and display each of the nodes.
while (reader.Read())
@ -120,8 +120,6 @@ namespace TShockAPI.DB
}
region.Area = rect;
using (var com = database.CreateCommand())
{
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO Regions VALUES (@0, @1, @2, @3, @4, @5, @6, @7);" :
"INSERT IGNORE INTO Regions SET X1=@0, Y1=@1, height=@2, width=@3, RegionName=@4, WorldID=@5, UserIds=@6, Protected=@7;";
@ -129,10 +127,10 @@ namespace TShockAPI.DB
//Todo: What should this be? We don't really have a way to go from ips to userids
/*string.Join(",", region.AllowedIDs)*/
}
}
}
}
String path = Path.Combine(TShock.SavePath, "old_configs");
String file2 = Path.Combine(path, "regions.xml");
if (!Directory.Exists(path))

View file

@ -350,6 +350,7 @@ namespace TShockAPI.DB
}
}
[Serializable]
public class UserManagerException : Exception
{
public UserManagerException(string message)
@ -363,6 +364,7 @@ namespace TShockAPI.DB
}
}
[Serializable]
public class UserExistsException : UserManagerException
{
public UserExistsException(string name)
@ -370,6 +372,7 @@ namespace TShockAPI.DB
{
}
}
[Serializable]
public class UserNotExistException : UserManagerException
{
public UserNotExistException(string name)
@ -377,7 +380,7 @@ namespace TShockAPI.DB
{
}
}
[Serializable]
public class GroupNotExistsException : UserManagerException
{
public GroupNotExistsException(string group)

View file

@ -31,6 +31,7 @@ namespace TShockAPI.DB
{
private IDbConnection database;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public WarpManager(IDbConnection db)
{
database = db;
@ -50,10 +51,10 @@ namespace TShockAPI.DB
String world = "";
int x1 = 0;
int y1 = 0;
if (File.Exists(file))
{
XmlReader reader;
using (reader = XmlReader.Create(new StreamReader(file)))
if (!File.Exists(file))
return;
using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings { CloseInput = true }))
{
// Parse the file and display each of the nodes.
while (reader.Read())
@ -102,9 +103,9 @@ namespace TShockAPI.DB
case XmlNodeType.EndElement:
if (reader.Name.Equals("Warp"))
{
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO Warps VALUES (@0, @1,@2, @3);" :
"INSERT IGNORE INTO Warps SET X=@0, Y=@1, WarpName=@2, WorldID=@3;";
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
? "INSERT OR IGNORE INTO Warps VALUES (@0, @1,@2, @3);"
: "INSERT IGNORE INTO Warps SET X=@0, Y=@1, WarpName=@2, WorldID=@3;";
database.Query(query, x1, y1, name, world);
}
break;
@ -112,16 +113,14 @@ namespace TShockAPI.DB
}
}
reader.Close();
String path = Path.Combine(TShock.SavePath, "old_configs");
String file2 = Path.Combine(path, "warps.xml");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
if (File.Exists(file2))
File.Delete(file2);
//File.Move(file, file2);
}
File.Move(file, file2);
}
public void ConvertDB()

View file

@ -14,6 +14,7 @@ namespace TShockAPI.DB
/// <param name="query">Query string with parameters as @0, @1, etc.</param>
/// <param name="args">Parameters to be put in the query</param>
/// <returns>Rows affected by query</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
public static int Query(this IDbConnection olddb, string query, params object[] args)
{
using (var db = olddb.CloneEx())
@ -36,6 +37,7 @@ namespace TShockAPI.DB
/// <param name="query">Query string with parameters as @0, @1, etc.</param>
/// <param name="args">Parameters to be put in the query</param>
/// <returns>Query result as IDataReader</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
public static QueryResult QueryReader(this IDbConnection olddb, string query, params object[] args)
{
var db = olddb.CloneEx();
@ -125,10 +127,32 @@ namespace TShockAPI.DB
Reader = reader;
}
~QueryResult()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Reader != null)
{
Reader.Dispose();
Reader = null;
}
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
}
public bool Read()

View file

@ -88,14 +88,13 @@ namespace TShockAPI
return true;
}
CreateIfNot(WhitelistPath, "127.0.0.1");
TextReader tr = new StreamReader(WhitelistPath);
using (var tr = new StreamReader(WhitelistPath))
{
string whitelist = tr.ReadToEnd();
ip = Tools.GetRealIP(ip);
bool contains = whitelist.Contains(ip);
if (!contains)
{
var char2 = Environment.NewLine.ToCharArray();
var array = whitelist.Split(Environment.NewLine.ToCharArray());
foreach (var line in whitelist.Split(Environment.NewLine.ToCharArray()))
{
if (string.IsNullOrWhiteSpace(line))
@ -106,8 +105,8 @@ namespace TShockAPI
}
return false;
}
else
return true;
}
}
}
}

View file

@ -24,8 +24,10 @@ namespace TShockAPI
int[] Packets = new int[52];
int[] Compressed = new int[52];
#if DEBUG_NET
Command dump;
Command flush;
#endif
public PacketBufferer()
{
@ -45,8 +47,21 @@ namespace TShockAPI
GameHooks.PostUpdate += GameHooks_Update;
}
~PacketBufferer()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
#if DEBUG_NET
Commands.ChatCommands.Remove(dump);
Commands.ChatCommands.Remove(flush);
@ -55,6 +70,7 @@ namespace TShockAPI
ServerHooks.SocketReset -= ServerHooks_SocketReset;
GameHooks.PostUpdate -= GameHooks_Update;
}
}
void Dump(CommandArgs args)
{
@ -120,7 +136,10 @@ namespace TShockAPI
Bytes[pt] += size;
Compressed[pt] += Compress(buffer, offset, count);
#endif
buffers[socket.whoAmI].AddRange(new MemoryStream(buffer, offset, count).ToArray());
using (var ms = new MemoryStream(buffer, offset, count))
{
buffers[socket.whoAmI].AddRange(ms.ToArray());
}
}
}
#if DEBUG_NET

View file

@ -36,5 +36,5 @@ using System.Runtime.InteropServices;
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.2.1.0805")]
[assembly: AssemblyFileVersion("3.2.1.0805")]
[assembly: AssemblyVersion("3.2.1.0806")]
[assembly: AssemblyFileVersion("3.2.1.0806")]

View file

@ -24,6 +24,7 @@ using System.Net.Sockets;
using System.Text;
using System.Threading;
using Terraria;
using XNAHelpers;
namespace TShockAPI
{
@ -116,12 +117,14 @@ namespace TShockAPI
try
{
var EP = new IPEndPoint(IPAddress.Any, port);
UdpClient client = new UdpClient();
using (var client = new UdpClient())
{
client.Connect(hostname, port);
client.Client.ReceiveTimeout = 500;
client.Send(bytes, bytes.Length);
response = Encoding.UTF8.GetString(client.Receive(ref EP));
}
}
catch (Exception e)
{
Log.Error(e.ToString());
@ -259,7 +262,7 @@ namespace TShockAPI
if (player != null && player.Active)
{
count++;
Response += (string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name, Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint)) + "\n";
Response += (string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name, Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint, "")) + "\n";
}
}
}
@ -288,18 +291,19 @@ namespace TShockAPI
private static byte[] ConstructPacket(string response, bool print)
{
var oob = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF };
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(oob);
using (var stream = new MemoryStream())
{
stream.WriteBytes(oob);
if (print)
writer.Write(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response)));
stream.WriteBytes(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response)));
else
writer.Write(Encoding.UTF8.GetBytes(response));
stream.WriteBytes(Encoding.UTF8.GetBytes(response));
var trimmedpacket = new byte[(int)stream.Length];
var packet = stream.GetBuffer();
Array.Copy(packet, trimmedpacket, (int)stream.Length);
return trimmedpacket;
}
}
private static byte[] PadPacket(byte[] packet)
{

View file

@ -178,10 +178,12 @@ namespace TShockAPI
};
var ms = new MemoryStream();
using (var ms = new MemoryStream())
{
msg.PackFull(ms);
SendRawData(ms.ToArray());
}
}
public bool Teleport(int tilex, int tiley)
{

View file

@ -94,6 +94,7 @@ namespace TShockAPI
Order = 0;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public override void Initialize()
{
if (!Directory.Exists(SavePath))
@ -315,15 +316,17 @@ namespace TShockAPI
Console.WriteLine("This token will display until disabled by verification. (/auth-verify)");
Console.ForegroundColor = ConsoleColor.Gray;
FileTools.CreateFile(Path.Combine(SavePath, "authcode.txt"));
TextWriter tw = new StreamWriter(Path.Combine(SavePath, "authcode.txt"));
using (var tw = new StreamWriter(Path.Combine(SavePath, "authcode.txt")))
{
tw.WriteLine(AuthToken);
tw.Close();
}
}
else if (File.Exists(Path.Combine(SavePath, "authcode.txt")))
{
TextReader tr = new StreamReader(Path.Combine(SavePath, "authcode.txt"));
using (var tr = new StreamReader(Path.Combine(SavePath, "authcode.txt")))
{
AuthToken = Convert.ToInt32(tr.ReadLine());
tr.Close();
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(
"TShock Notice: authcode.txt is still present, and the AuthToken located in that file will be used.");

View file

@ -428,7 +428,8 @@ namespace TShockAPI
public static void ShowFileToUser(TSPlayer player, string file)
{
string foo = "";
TextReader tr = new StreamReader(Path.Combine(TShock.SavePath, file));
using (var tr = new StreamReader(Path.Combine(TShock.SavePath, file)))
{
while ((foo = tr.ReadLine()) != null)
{
foo = foo.Replace("%map%", Main.worldName);
@ -444,7 +445,8 @@ namespace TShockAPI
{
try
{
player.SendMessage(foo, (byte)Convert.ToInt32(pCc[0]), (byte)Convert.ToInt32(pCc[1]), (byte)Convert.ToInt32(pCc[2]));
player.SendMessage(foo, (byte) Convert.ToInt32(pCc[0]), (byte) Convert.ToInt32(pCc[1]),
(byte) Convert.ToInt32(pCc[2]));
continue;
}
catch (Exception e)
@ -455,7 +457,7 @@ namespace TShockAPI
}
player.SendMessage(foo);
}
tr.Close();
}
}
/// <summary>

View file

@ -55,7 +55,8 @@ namespace TShockAPI
/// <returns></returns>
private static bool ServerIsOutOfDate()
{
WebClient client = new WebClient();
using (var client = new WebClient())
{
client.Headers.Add("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
@ -76,6 +77,7 @@ namespace TShockAPI
}
return false;
}
}
private static void NotifyAdministrators(string[] changes)
{