Changeset 387
- Timestamp:
- Aug 6, 2022, 11:32:32 PM (2 years ago)
- Location:
- binary-improvements2/MapRendering
- Files:
-
- 2 added
- 30 edited
- 1 moved
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements2/MapRendering/Web/API/AbsWebAPI.cs
r386 r387 1 using System.Text;2 using AllocsFixes.JSON;3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 6 1 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public abstract class WebAPI {2 public abstract class AbsWebAPI { 8 3 public readonly string Name; 9 4 10 protected WebAPI (string _name = null) {5 protected AbsWebAPI (string _name = null) { 11 6 Name = _name ?? GetType ().Name; 12 7 } 13 8 14 #if ENABLE_PROFILER 15 private static readonly UnityEngine.Profiling.CustomSampler jsonSerializeSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Serialize"); 16 private static readonly UnityEngine.Profiling.CustomSampler netWriteSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Write"); 17 #endif 18 19 public static void WriteJSON (HttpListenerResponse _resp, JSONNode _root) { 20 #if ENABLE_PROFILER 21 jsonSerializeSampler.Begin (); 22 #endif 23 StringBuilder sb = new StringBuilder (); 24 _root.ToString (sb); 25 #if ENABLE_PROFILER 26 jsonSerializeSampler.End (); 27 netWriteSampler.Begin (); 28 #endif 29 byte[] buf = Encoding.UTF8.GetBytes (sb.ToString ()); 30 _resp.ContentLength64 = buf.Length; 31 _resp.ContentType = "application/json"; 32 _resp.ContentEncoding = Encoding.UTF8; 33 _resp.OutputStream.Write (buf, 0, buf.Length); 34 #if ENABLE_PROFILER 35 netWriteSampler.End (); 36 #endif 37 } 38 39 public static void WriteText (HttpListenerResponse _resp, string _text) { 40 byte[] buf = Encoding.UTF8.GetBytes (_text); 41 _resp.ContentLength64 = buf.Length; 42 _resp.ContentType = "text/plain"; 43 _resp.ContentEncoding = Encoding.UTF8; 44 _resp.OutputStream.Write (buf, 0, buf.Length); 45 } 46 47 public abstract void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, 48 WebConnection _user, int _permissionLevel); 9 public abstract void HandleRequest (RequestContext _context); 49 10 50 11 public virtual int DefaultPermissionLevel () { -
binary-improvements2/MapRendering/Web/API/ExecuteConsoleCommand.cs
r382 r387 1 1 using System; 2 2 using System.Net; 3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 3 6 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public class ExecuteConsoleCommand : WebAPI { 8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 10 if (string.IsNullOrEmpty (_req.QueryString ["command"])) { 11 _resp.StatusCode = (int) HttpStatusCode.BadRequest; 12 Web.SetResponseTextContent (_resp, "No command given"); 5 public class ExecuteConsoleCommand : AbsWebAPI { 6 public override void HandleRequest (RequestContext _context) { 7 if (string.IsNullOrEmpty (_context.Request.QueryString ["command"])) { 8 WebUtils.WriteText (_context.Response, "No command given", HttpStatusCode.BadRequest); 13 9 return; 14 10 } 15 11 16 12 WebCommandResult.ResultType responseType = 17 _ req.QueryString ["raw"] != null13 _context.Request.QueryString ["raw"] != null 18 14 ? WebCommandResult.ResultType.Raw 19 : (_ req.QueryString ["simple"] != null15 : (_context.Request.QueryString ["simple"] != null 20 16 ? WebCommandResult.ResultType.ResultOnly 21 17 : WebCommandResult.ResultType.Full); 22 18 23 string commandline = _ req.QueryString ["command"];19 string commandline = _context.Request.QueryString ["command"]; 24 20 string commandPart = commandline.Split (' ') [0]; 25 21 string argumentsPart = commandline.Substring (Math.Min (commandline.Length, commandPart.Length + 1)); … … 28 24 29 25 if (command == null) { 30 _resp.StatusCode = (int) HttpStatusCode.NotFound; 31 Web.SetResponseTextContent (_resp, "Unknown command"); 26 WebUtils.WriteText (_context.Response, "Unknown command", HttpStatusCode.NotFound); 32 27 return; 33 28 } … … 35 30 int commandPermissionLevel = GameManager.Instance.adminTools.GetCommandPermissionLevel (command.GetCommands ()); 36 31 37 if (_permissionLevel > commandPermissionLevel) { 38 _resp.StatusCode = (int) HttpStatusCode.Forbidden; 39 Web.SetResponseTextContent (_resp, "You are not allowed to execute this command"); 32 if (_context.PermissionLevel > commandPermissionLevel) { 33 WebUtils.WriteText (_context.Response, "You are not allowed to execute this command", HttpStatusCode.Forbidden); 40 34 return; 41 35 } 42 36 43 _ resp.SendChunked = true;44 WebCommandResult wcr = new WebCommandResult (commandPart, argumentsPart, responseType, _ resp);37 _context.Response.SendChunked = true; 38 WebCommandResult wcr = new WebCommandResult (commandPart, argumentsPart, responseType, _context.Response); 45 39 SdtdConsole.Instance.ExecuteAsync (commandline, wcr); 46 40 } -
binary-improvements2/MapRendering/Web/API/GetAllowedCommands.cs
r383 r387 1 1 using AllocsFixes.JSON; 2 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;3 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;4 2 5 3 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public class GetAllowedCommands : WebAPI { 7 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 8 int _permissionLevel) { 4 public class GetAllowedCommands : AbsWebAPI { 5 public override void HandleRequest (RequestContext _context) { 9 6 JSONObject result = new JSONObject (); 10 7 JSONArray entries = new JSONArray (); 11 8 foreach (IConsoleCommand cc in SdtdConsole.Instance.GetCommands ()) { 12 9 int commandPermissionLevel = GameManager.Instance.adminTools.GetCommandPermissionLevel (cc.GetCommands ()); 13 if (_ permissionLevel <= commandPermissionLevel) {10 if (_context.PermissionLevel <= commandPermissionLevel) { 14 11 string cmd = string.Empty; 15 12 foreach (string s in cc.GetCommands ()) { … … 29 26 result.Add ("commands", entries); 30 27 31 W riteJSON (_resp, result);28 WebUtils.WriteJson (_context.Response, result); 32 29 } 33 30 -
binary-improvements2/MapRendering/Web/API/GetAnimalsLocation.cs
r383 r387 2 2 using AllocsFixes.JSON; 3 3 using AllocsFixes.LiveData; 4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 8 internal class GetAnimalsLocation : WebAPI {6 internal class GetAnimalsLocation : AbsWebAPI { 9 7 private readonly List<EntityAnimal> animals = new List<EntityAnimal> (); 10 8 11 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 12 int _permissionLevel) { 9 public override void HandleRequest (RequestContext _context) { 13 10 JSONArray animalsJsResult = new JSONArray (); 14 11 … … 37 34 } 38 35 39 W riteJSON (_resp, animalsJsResult);36 WebUtils.WriteJson (_context.Response, animalsJsResult); 40 37 } 41 38 } -
binary-improvements2/MapRendering/Web/API/GetHostileLocation.cs
r383 r387 2 2 using AllocsFixes.JSON; 3 3 using AllocsFixes.LiveData; 4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 8 internal class GetHostileLocation : WebAPI {6 internal class GetHostileLocation : AbsWebAPI { 9 7 private readonly List<EntityEnemy> enemies = new List<EntityEnemy> (); 10 8 11 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 12 int _permissionLevel) { 9 public override void HandleRequest (RequestContext _context) { 13 10 JSONArray hostilesJsResult = new JSONArray (); 14 11 … … 37 34 } 38 35 39 W riteJSON (_resp, hostilesJsResult);36 WebUtils.WriteJson (_context.Response, hostilesJsResult); 40 37 } 41 38 } -
binary-improvements2/MapRendering/Web/API/GetLandClaims.cs
r382 r387 3 3 using AllocsFixes.JSON; 4 4 using AllocsFixes.PersistentData; 5 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;6 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;7 5 8 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 9 public class GetLandClaims : WebAPI { 10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 11 int _permissionLevel) { 7 public class GetLandClaims : AbsWebAPI { 8 public override void HandleRequest (RequestContext _context) { 12 9 PlatformUserIdentifierAbs requestedUserId = null; 13 if (_req.QueryString ["userid"] != null) { 14 if (!PlatformUserIdentifierAbs.TryFromCombinedString (_req.QueryString ["userid"], out requestedUserId)) { 15 _resp.StatusCode = (int) HttpStatusCode.BadRequest; 16 Web.SetResponseTextContent (_resp, "Invalid user id given"); 10 if (_context.Request.QueryString ["userid"] != null) { 11 if (!PlatformUserIdentifierAbs.TryFromCombinedString (_context.Request.QueryString ["userid"], out requestedUserId)) { 12 WebUtils.WriteText (_context.Response, "Invalid user id given", HttpStatusCode.BadRequest); 17 13 return; 18 14 } … … 20 16 21 17 // default user, cheap way to avoid 'null reference exception' 22 PlatformUserIdentifierAbs userId = _ user?.UserId;18 PlatformUserIdentifierAbs userId = _context.Connection?.UserId; 23 19 24 bool bViewAll = WebConnection.CanViewAllClaims (_ permissionLevel);20 bool bViewAll = WebConnection.CanViewAllClaims (_context.PermissionLevel); 25 21 26 22 JSONObject result = new JSONObject (); … … 74 70 } 75 71 76 W riteJSON (_resp, result);72 WebUtils.WriteJson (_context.Response, result); 77 73 } 78 74 } -
binary-improvements2/MapRendering/Web/API/GetLog.cs
r383 r387 1 1 using System.Collections.Generic; 2 2 using AllocsFixes.JSON; 3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 3 6 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public class GetLog : WebAPI {5 public class GetLog : AbsWebAPI { 8 6 private const int MAX_COUNT = 1000; 9 7 10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 11 int _permissionLevel) { 12 if (_req.QueryString ["count"] == null || !int.TryParse (_req.QueryString ["count"], out int count)) { 8 public override void HandleRequest (RequestContext _context) { 9 if (_context.Request.QueryString ["count"] == null || !int.TryParse (_context.Request.QueryString ["count"], out int count)) { 13 10 count = 50; 14 11 } … … 26 23 } 27 24 28 if (_ req.QueryString ["firstLine"] == null || !int.TryParse (_req.QueryString ["firstLine"], out int firstLine)) {25 if (_context.Request.QueryString ["firstLine"] == null || !int.TryParse (_context.Request.QueryString ["firstLine"], out int firstLine)) { 29 26 firstLine = count > 0 ? LogBuffer.Instance.OldestLine : LogBuffer.Instance.LatestLine; 30 27 } … … 37 34 foreach (LogBuffer.LogEntry logEntry in logEntries) { 38 35 JSONObject entry = new JSONObject (); 39 entry.Add ("date", new JSONString (logEntry.date));40 entry.Add ("time", new JSONString (logEntry.time));41 36 entry.Add ("isotime", new JSONString (logEntry.isoTime)); 42 37 entry.Add ("uptime", new JSONString (logEntry.uptime.ToString ())); … … 51 46 result.Add ("entries", entries); 52 47 53 W riteJSON (_resp, result);48 WebUtils.WriteJson (_context.Response, result); 54 49 } 55 50 } -
binary-improvements2/MapRendering/Web/API/GetPlayerInventories.cs
r383 r387 2 2 using AllocsFixes.JSON; 3 3 using AllocsFixes.PersistentData; 4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 8 public class GetPlayerInventories : WebAPI { 9 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 10 int _permissionLevel) { 11 GetPlayerInventory.GetInventoryArguments (_req, out bool showIconColor, out bool showIconName); 6 public class GetPlayerInventories : AbsWebAPI { 7 public override void HandleRequest (RequestContext _context) { 8 GetPlayerInventory.GetInventoryArguments (_context.Request, out bool showIconColor, out bool showIconName); 12 9 13 10 JSONArray AllInventoriesResult = new JSONArray (); … … 25 22 } 26 23 27 W riteJSON (_resp, AllInventoriesResult);24 WebUtils.WriteJson (_context.Response, AllInventoriesResult); 28 25 } 29 26 } -
binary-improvements2/MapRendering/Web/API/GetPlayerInventory.cs
r382 r387 4 4 using AllocsFixes.PersistentData; 5 5 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest; 6 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;7 6 8 7 namespace AllocsFixes.NetConnections.Servers.Web.API { 9 public class GetPlayerInventory : WebAPI { 10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, 11 WebConnection _user, int _permissionLevel) { 12 if (_req.QueryString ["userid"] == null) { 13 _resp.StatusCode = (int) HttpStatusCode.BadRequest; 14 Web.SetResponseTextContent (_resp, "No user id given"); 8 public class GetPlayerInventory : AbsWebAPI { 9 public override void HandleRequest (RequestContext _context) { 10 if (_context.Request.QueryString ["userid"] == null) { 11 WebUtils.WriteText (_context.Response, "No user id given", HttpStatusCode.BadRequest); 15 12 return; 16 13 } 17 14 18 string userIdString = _ req.QueryString ["userid"];15 string userIdString = _context.Request.QueryString ["userid"]; 19 16 if (!PlatformUserIdentifierAbs.TryFromCombinedString (userIdString, out PlatformUserIdentifierAbs userId)) { 20 _resp.StatusCode = (int) HttpStatusCode.BadRequest; 21 Web.SetResponseTextContent (_resp, "Invalid user id given"); 17 WebUtils.WriteText (_context.Response, "Invalid user id given", HttpStatusCode.BadRequest); 22 18 return; 23 19 } … … 25 21 Player p = PersistentContainer.Instance.Players [userId, false]; 26 22 if (p == null) { 27 _resp.StatusCode = (int) HttpStatusCode.NotFound; 28 Web.SetResponseTextContent (_resp, "Unknown user id given"); 23 WebUtils.WriteText (_context.Response, "Unknown user id given", HttpStatusCode.NotFound); 29 24 return; 30 25 } 31 26 32 GetInventoryArguments (_ req, out bool showIconColor, out bool showIconName);27 GetInventoryArguments (_context.Request, out bool showIconColor, out bool showIconName); 33 28 34 29 JSONObject result = DoPlayer (userIdString, p, showIconColor, showIconName); 35 30 36 W riteJSON (_resp, result);31 WebUtils.WriteJson (_context.Response, result); 37 32 } 38 33 -
binary-improvements2/MapRendering/Web/API/GetPlayerList.cs
r383 r387 5 5 using AllocsFixes.JSON; 6 6 using AllocsFixes.PersistentData; 7 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;8 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;9 7 10 8 namespace AllocsFixes.NetConnections.Servers.Web.API { 11 public class GetPlayerList : WebAPI {9 public class GetPlayerList : AbsWebAPI { 12 10 private static readonly Regex numberFilterMatcher = 13 11 new Regex (@"^(>=|=>|>|<=|=<|<|==|=)?\s*([0-9]+(\.[0-9]*)?)$"); … … 17 15 #endif 18 16 19 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 20 int _permissionLevel) { 17 public override void HandleRequest (RequestContext _context) { 21 18 AdminTools admTools = GameManager.Instance.adminTools; 22 PlatformUserIdentifierAbs userId = _ user?.UserId;23 24 bool bViewAll = WebConnection.CanViewAllPlayers (_ permissionLevel);19 PlatformUserIdentifierAbs userId = _context.Connection?.UserId; 20 21 bool bViewAll = WebConnection.CanViewAllPlayers (_context.PermissionLevel); 25 22 26 23 // TODO: Sort (and filter?) prior to converting to JSON ... hard as how to get the correct column's data? (i.e. column name matches JSON object field names, not source data) 27 24 28 25 int rowsPerPage = 25; 29 if (_ req.QueryString ["rowsperpage"] != null) {30 int.TryParse (_ req.QueryString ["rowsperpage"], out rowsPerPage);26 if (_context.Request.QueryString ["rowsperpage"] != null) { 27 int.TryParse (_context.Request.QueryString ["rowsperpage"], out rowsPerPage); 31 28 } 32 29 33 30 int page = 0; 34 if (_ req.QueryString ["page"] != null) {35 int.TryParse (_ req.QueryString ["page"], out page);31 if (_context.Request.QueryString ["page"] != null) { 32 int.TryParse (_context.Request.QueryString ["page"], out page); 36 33 } 37 34 … … 83 80 IEnumerable<JSONObject> list = playerList; 84 81 85 foreach (string key in _ req.QueryString.AllKeys) {82 foreach (string key in _context.Request.QueryString.AllKeys) { 86 83 if (!string.IsNullOrEmpty (key) && key.StartsWith ("filter[")) { 87 84 string filterCol = key.Substring (key.IndexOf ('[') + 1); 88 85 filterCol = filterCol.Substring (0, filterCol.Length - 1); 89 string filterVal = _ req.QueryString.Get (key).Trim ();86 string filterVal = _context.Request.QueryString.Get (key).Trim (); 90 87 91 88 list = ExecuteFilter (list, filterCol, filterVal); … … 95 92 int totalAfterFilter = list.Count (); 96 93 97 foreach (string key in _ req.QueryString.AllKeys) {94 foreach (string key in _context.Request.QueryString.AllKeys) { 98 95 if (!string.IsNullOrEmpty (key) && key.StartsWith ("sort[")) { 99 96 string sortCol = key.Substring (key.IndexOf ('[') + 1); 100 97 sortCol = sortCol.Substring (0, sortCol.Length - 1); 101 string sortVal = _ req.QueryString.Get (key);98 string sortVal = _context.Request.QueryString.Get (key); 102 99 103 100 list = ExecuteSort (list, sortCol, sortVal == "0"); … … 120 117 result.Add ("players", playersJsResult); 121 118 122 W riteJSON (_resp, result);119 WebUtils.WriteJson (_context.Response, result); 123 120 } 124 121 -
binary-improvements2/MapRendering/Web/API/GetPlayersLocation.cs
r383 r387 2 2 using AllocsFixes.JSON; 3 3 using AllocsFixes.PersistentData; 4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 8 public class GetPlayersLocation : WebAPI { 9 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 10 int _permissionLevel) { 6 public class GetPlayersLocation : AbsWebAPI { 7 public override void HandleRequest (RequestContext _context) { 11 8 AdminTools admTools = GameManager.Instance.adminTools; 12 PlatformUserIdentifierAbs userId = _ user?.UserId;9 PlatformUserIdentifierAbs userId = _context.Connection?.UserId; 13 10 14 11 bool listOffline = false; 15 if (_ req.QueryString ["offline"] != null) {16 bool.TryParse (_ req.QueryString ["offline"], out listOffline);12 if (_context.Request.QueryString ["offline"] != null) { 13 bool.TryParse (_context.Request.QueryString ["offline"], out listOffline); 17 14 } 18 15 19 bool bViewAll = WebConnection.CanViewAllPlayers (_ permissionLevel);16 bool bViewAll = WebConnection.CanViewAllPlayers (_context.PermissionLevel); 20 17 21 18 JSONArray playersJsResult = new JSONArray (); … … 57 54 } 58 55 59 W riteJSON (_resp, playersJsResult);56 WebUtils.WriteJson (_context.Response, playersJsResult); 60 57 } 61 58 } -
binary-improvements2/MapRendering/Web/API/GetPlayersOnline.cs
r383 r387 2 2 using AllocsFixes.JSON; 3 3 using AllocsFixes.PersistentData; 4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 8 public class GetPlayersOnline : WebAPI { 9 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 10 int _permissionLevel) { 6 public class GetPlayersOnline : AbsWebAPI { 7 public override void HandleRequest (RequestContext _context) { 11 8 JSONArray players = new JSONArray (); 12 9 … … 44 41 } 45 42 46 W riteJSON (_resp, players);43 WebUtils.WriteJson (_context.Response, players); 47 44 } 48 45 } -
binary-improvements2/MapRendering/Web/API/GetServerInfo.cs
r383 r387 1 1 using System; 2 2 using AllocsFixes.JSON; 3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 3 6 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public class GetServerInfo : WebAPI { 8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 5 public class GetServerInfo : AbsWebAPI { 6 public override void HandleRequest (RequestContext _context) { 10 7 JSONObject serverInfo = new JSONObject (); 11 8 … … 43 40 44 41 45 W riteJSON (_resp, serverInfo);42 WebUtils.WriteJson (_context.Response, serverInfo); 46 43 } 47 44 } -
binary-improvements2/MapRendering/Web/API/GetStats.cs
r383 r387 1 1 using AllocsFixes.JSON; 2 2 using AllocsFixes.LiveData; 3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 3 6 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public class GetStats : WebAPI { 8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 5 public class GetStats : AbsWebAPI { 6 public override void HandleRequest (RequestContext _context) { 10 7 JSONObject result = new JSONObject (); 11 8 … … 20 17 result.Add ("animals", new JSONNumber (Animals.Instance.GetCount ())); 21 18 22 W riteJSON (_resp, result);19 WebUtils.WriteJson (_context.Response, result); 23 20 } 24 21 -
binary-improvements2/MapRendering/Web/API/GetWebMods.cs
r384 r387 1 1 using AllocsFixes.JSON; 2 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;3 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;4 2 5 3 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public class GetWebMods : WebAPI {4 public class GetWebMods : AbsWebAPI { 7 5 private readonly JSONArray loadedWebMods = new JSONArray (); 8 6 … … 27 25 } 28 26 29 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 30 int _permissionLevel) { 31 32 WriteJSON (_resp, loadedWebMods); 27 public override void HandleRequest (RequestContext _context) { 28 WebUtils.WriteJson (_context.Response, loadedWebMods); 33 29 } 34 30 -
binary-improvements2/MapRendering/Web/API/GetWebUIUpdates.cs
r383 r387 1 1 using AllocsFixes.JSON; 2 2 using AllocsFixes.LiveData; 3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 3 6 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 public class GetWebUIUpdates : WebAPI { 8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 5 public class GetWebUIUpdates : AbsWebAPI { 6 public override void HandleRequest (RequestContext _context) { 10 7 int latestLine; 11 if (_ req.QueryString ["latestLine"] == null ||12 !int.TryParse (_ req.QueryString ["latestLine"], out latestLine)) {8 if (_context.Request.QueryString ["latestLine"] == null || 9 !int.TryParse (_context.Request.QueryString ["latestLine"], out latestLine)) { 13 10 latestLine = 0; 14 11 } … … 28 25 result.Add ("newlogs", new JSONNumber (LogBuffer.Instance.LatestLine - latestLine)); 29 26 30 W riteJSON (_resp, result);27 WebUtils.WriteJson (_context.Response, result); 31 28 } 32 29 -
binary-improvements2/MapRendering/Web/API/Null.cs
r383 r387 1 1 using System.Text; 2 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;3 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;4 2 5 3 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 public class Null : WebAPI {4 public class Null : AbsWebAPI { 7 5 public Null (string _name) : base(_name) { 8 6 } 9 7 10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 11 int _permissionLevel) { 12 _resp.ContentLength64 = 0; 13 _resp.ContentType = "text/plain"; 14 _resp.ContentEncoding = Encoding.ASCII; 15 _resp.OutputStream.Write (new byte[] { }, 0, 0); 8 public override void HandleRequest (RequestContext _context) { 9 _context.Response.ContentLength64 = 0; 10 _context.Response.ContentType = "text/plain"; 11 _context.Response.ContentEncoding = Encoding.ASCII; 12 _context.Response.OutputStream.Write (new byte[] { }, 0, 0); 16 13 } 17 14 } -
binary-improvements2/MapRendering/Web/Handlers/AbsHandler.cs
r383 r387 1 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;2 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;3 4 1 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 5 2 public abstract class AbsHandler { … … 16 13 } 17 14 18 public abstract void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 19 int _permissionLevel); 15 public abstract void HandleRequest (RequestContext _context); 20 16 21 17 public virtual bool IsAuthorizedForHandler (WebConnection _user, int _permissionLevel) { -
binary-improvements2/MapRendering/Web/Handlers/ApiHandler.cs
r384 r387 4 4 using System.Reflection; 5 5 using AllocsFixes.NetConnections.Servers.Web.API; 6 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;7 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;8 6 9 7 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 10 8 public class ApiHandler : AbsHandler { 11 private readonly Dictionary<string, WebAPI> apis = new CaseInsensitiveStringDictionary<WebAPI> ();9 private readonly Dictionary<string, AbsWebAPI> apis = new CaseInsensitiveStringDictionary<AbsWebAPI> (); 12 10 13 11 public ApiHandler () : base (null) { … … 25 23 26 24 foreach (Type t in Assembly.GetExecutingAssembly ().GetTypes ()) { 27 if (!t.IsAbstract && t.IsSubclassOf (typeof ( WebAPI))) {25 if (!t.IsAbstract && t.IsSubclassOf (typeof (AbsWebAPI))) { 28 26 ConstructorInfo ctor = t.GetConstructor (apiWithParentCtorTypes); 29 27 if (ctor != null) { 30 WebAPI apiInstance = (WebAPI) ctor.Invoke (apiWithParentCtorArgs);28 AbsWebAPI apiInstance = (AbsWebAPI) ctor.Invoke (apiWithParentCtorArgs); 31 29 addApi (apiInstance); 32 30 continue; … … 35 33 ctor = t.GetConstructor (apiEmptyCtorTypes); 36 34 if (ctor != null) { 37 WebAPI apiInstance = (WebAPI) ctor.Invoke (apiEmptyCtorArgs);35 AbsWebAPI apiInstance = (AbsWebAPI) ctor.Invoke (apiEmptyCtorArgs); 38 36 addApi (apiInstance); 39 37 } … … 46 44 } 47 45 48 private void addApi ( WebAPI _api) {46 private void addApi (AbsWebAPI _api) { 49 47 apis.Add (_api.Name, _api); 50 48 WebPermissions.Instance.AddKnownModule ("webapi." + _api.Name, _api.DefaultPermissionLevel ()); … … 55 53 #endif 56 54 57 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 58 int _permissionLevel) { 59 string apiName = _requestPath.Remove (0, urlBasePath.Length); 55 public override void HandleRequest (RequestContext _context) { 60 56 61 if (!apis.TryGetValue (apiName, out WebAPI api)) { 57 string apiName; 58 string subPath = null; 59 60 int pathSeparatorIndex = _context.RequestPath.IndexOf ('/', urlBasePath.Length); 61 if (pathSeparatorIndex >= 0) { 62 apiName = _context.RequestPath.Substring (urlBasePath.Length, pathSeparatorIndex - urlBasePath.Length); 63 subPath = _context.RequestPath.Substring (pathSeparatorIndex + 1); 64 } else { 65 apiName = _context.RequestPath.Substring (urlBasePath.Length); 66 } 67 68 if (!apis.TryGetValue (apiName, out AbsWebAPI api)) { 62 69 Log.Out ($"Error in {nameof(ApiHandler)}.HandleRequest(): No handler found for API \"{apiName}\""); 63 _ resp.StatusCode = (int) HttpStatusCode.NotFound;70 _context.Response.StatusCode = (int) HttpStatusCode.NotFound; 64 71 return; 65 72 } 66 73 67 if (!AuthorizeForApi (apiName, _ permissionLevel)) {68 _ resp.StatusCode = (int) HttpStatusCode.Forbidden;69 if (_con != null) {74 if (!AuthorizeForApi (apiName, _context.PermissionLevel)) { 75 _context.Response.StatusCode = (int) HttpStatusCode.Forbidden; 76 if (_context.Connection != null) { 70 77 //Log.Out ($"{nameof(ApiHandler)}: user '{user.SteamID}' not allowed to execute '{apiName}'"); 71 78 } … … 74 81 } 75 82 83 _context.RequestPath = subPath; 84 76 85 try { 77 86 #if ENABLE_PROFILER 78 87 apiHandlerSampler.Begin (); 79 88 #endif 80 api.HandleRequest (_ req, _resp, _con, _permissionLevel);89 api.HandleRequest (_context); 81 90 #if ENABLE_PROFILER 82 91 apiHandlerSampler.End (); … … 85 94 Log.Error ($"Error in {nameof(ApiHandler)}.HandleRequest(): Handler {api.Name} threw an exception:"); 86 95 Log.Exception (e); 87 _ resp.StatusCode = (int) HttpStatusCode.InternalServerError;96 _context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; 88 97 } 89 98 } -
binary-improvements2/MapRendering/Web/Handlers/ItemIconHandler.cs
r382 r387 4 4 using System.Net; 5 5 using UnityEngine; 6 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;7 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;8 6 using Object = UnityEngine.Object; 9 7 … … 26 24 public static ItemIconHandler Instance { get; private set; } 27 25 28 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 29 int _permissionLevel) { 26 public override void HandleRequest (RequestContext _context) { 30 27 if (!loaded) { 31 _ resp.StatusCode = (int) HttpStatusCode.InternalServerError;28 _context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; 32 29 Log.Out ("Web:IconHandler: Icons not loaded"); 33 30 return; 34 31 } 35 32 36 string requestFileName = _ requestPath.Remove (0, urlBasePath.Length);33 string requestFileName = _context.RequestPath.Remove (0, urlBasePath.Length); 37 34 requestFileName = requestFileName.Remove (requestFileName.LastIndexOf ('.')); 38 35 39 if (icons.ContainsKey (requestFileName) && _ requestPath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {40 _ resp.ContentType = MimeType.GetMimeType (".png");36 if (icons.ContainsKey (requestFileName) && _context.RequestPath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) { 37 _context.Response.ContentType = MimeType.GetMimeType (".png"); 41 38 42 39 byte[] itemIconData = icons [requestFileName]; 43 40 44 _ resp.ContentLength64 = itemIconData.Length;45 _ resp.OutputStream.Write (itemIconData, 0, itemIconData.Length);41 _context.Response.ContentLength64 = itemIconData.Length; 42 _context.Response.OutputStream.Write (itemIconData, 0, itemIconData.Length); 46 43 } else { 47 _ resp.StatusCode = (int) HttpStatusCode.NotFound;44 _context.Response.StatusCode = (int) HttpStatusCode.NotFound; 48 45 if (logMissingFiles) { 49 Log.Out ("Web:IconHandler:FileNotFound: \"" + _ requestPath + "\" ");46 Log.Out ("Web:IconHandler:FileNotFound: \"" + _context.RequestPath + "\" "); 50 47 } 51 48 } -
binary-improvements2/MapRendering/Web/Handlers/RewriteHandler.cs
r382 r387 1 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;2 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;3 4 1 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 5 2 public class RewriteHandler : AbsHandler { … … 12 9 } 13 10 14 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 15 int _permissionLevel) { 16 string newRequestPath = fixedTarget ? target : target + _requestPath.Remove (0, urlBasePath.Length); 17 parent.ApplyPathHandler (newRequestPath, _req, _resp, _con, _permissionLevel); 11 public override void HandleRequest (RequestContext _context) { 12 _context.RequestPath = fixedTarget ? target : target + _context.RequestPath.Remove (0, urlBasePath.Length); 13 parent.ApplyPathHandler (_context); 18 14 } 19 15 } -
binary-improvements2/MapRendering/Web/Handlers/SessionHandler.cs
r382 r387 3 3 using System.Net; 4 4 using System.Text; 5 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;6 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;7 5 8 6 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { … … 29 27 } 30 28 31 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 32 int _permissionLevel) { 29 public override void HandleRequest (RequestContext _context) { 33 30 34 IPEndPoint reqRemoteEndPoint = _ req.RemoteEndPoint;31 IPEndPoint reqRemoteEndPoint = _context.Request.RemoteEndPoint; 35 32 if (reqRemoteEndPoint == null) { 36 _ resp.Redirect (pageBasePath);33 _context.Response.Redirect (pageBasePath); 37 34 return; 38 35 } 39 36 40 string subpath = _ requestPath.Remove (0, urlBasePath.Length);37 string subpath = _context.RequestPath.Remove (0, urlBasePath.Length); 41 38 42 39 StringBuilder result = new StringBuilder (); … … 47 44 48 45 try { 49 ulong id = OpenID.Validate (_ req);46 ulong id = OpenID.Validate (_context.Request); 50 47 if (id > 0) { 51 48 WebConnection con = connectionHandler.LogIn (id, reqRemoteEndPoint.Address); … … 60 57 Secure = false 61 58 }; 62 _ resp.AppendCookie (cookie);63 _ resp.Redirect (pageBasePath);59 _context.Response.AppendCookie (cookie); 60 _context.Response.Redirect (pageBasePath); 64 61 65 62 return; … … 73 70 result.Append ($"<h1>Login failed, <a href=\"{pageBasePath}\">click to return to main page</a>.</h1>"); 74 71 } else if (subpath.StartsWith ("logout")) { 75 if (_con != null) {76 connectionHandler.LogOut (_con .SessionID);72 if (_context.Connection != null) { 73 connectionHandler.LogOut (_context.Connection.SessionID); 77 74 Cookie cookie = new Cookie ("sid", "", "/") { 78 75 Expired = true 79 76 }; 80 _ resp.AppendCookie (cookie);81 _ resp.Redirect (pageBasePath);77 _context.Response.AppendCookie (cookie); 78 _context.Response.Redirect (pageBasePath); 82 79 return; 83 80 } … … 85 82 result.Append ($"<h1>Not logged in, <a href=\"{pageBasePath}\">click to return to main page</a>.</h1>"); 86 83 } else if (subpath.StartsWith (steamLoginUrl)) { 87 string host = (Web.IsSslRedirected (_ req) ? "https://" : "http://") + _req.UserHostName;84 string host = (Web.IsSslRedirected (_context.Request) ? "https://" : "http://") + _context.Request.UserHostName; 88 85 string url = OpenID.GetOpenIdLoginUrl (host, host + urlBasePath + steamOpenIdVerifyUrl); 89 _ resp.Redirect (url);86 _context.Response.Redirect (url); 90 87 return; 91 88 } else { … … 95 92 result.Append (footer); 96 93 97 _resp.ContentType = MimeType.GetMimeType (".html"); 98 _resp.ContentEncoding = Encoding.UTF8; 99 byte[] buf = Encoding.UTF8.GetBytes (result.ToString ()); 100 _resp.ContentLength64 = buf.Length; 101 _resp.OutputStream.Write (buf, 0, buf.Length); 94 WebUtils.WriteText (_context.Response, result.ToString (), _mimeType: WebUtils.MimeHtml); 102 95 } 103 96 } -
binary-improvements2/MapRendering/Web/Handlers/SimpleRedirectHandler.cs
r383 r387 1 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;2 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;3 4 1 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 5 2 public class SimpleRedirectHandler : AbsHandler { … … 10 7 } 11 8 12 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 13 int _permissionLevel) { 14 _resp.Redirect (target); 9 public override void HandleRequest (RequestContext _context) { 10 _context.Response.Redirect (target); 15 11 } 16 12 } -
binary-improvements2/MapRendering/Web/Handlers/StaticHandler.cs
r382 r387 2 2 using System.Net; 3 3 using AllocsFixes.FileCache; 4 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;5 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;6 4 7 5 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { … … 18 16 } 19 17 20 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 21 int _permissionLevel) { 22 string fn = _requestPath.Remove (0, urlBasePath.Length); 18 public override void HandleRequest (RequestContext _context) { 19 string fn = _context.RequestPath.Remove (0, urlBasePath.Length); 23 20 24 21 byte[] content = cache.GetFileContent (datapath + fn); 25 22 26 23 if (content != null) { 27 _ resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn));28 _ resp.ContentLength64 = content.Length;29 _ resp.OutputStream.Write (content, 0, content.Length);24 _context.Response.ContentType = MimeType.GetMimeType (Path.GetExtension (fn)); 25 _context.Response.ContentLength64 = content.Length; 26 _context.Response.OutputStream.Write (content, 0, content.Length); 30 27 } else { 31 _ resp.StatusCode = (int) HttpStatusCode.NotFound;28 _context.Response.StatusCode = (int) HttpStatusCode.NotFound; 32 29 if (logMissingFiles) { 33 Log.Out ("Web:Static:FileNotFound: \"" + _ requestPath + "\" @ \"" + datapath + fn + "\"");30 Log.Out ("Web:Static:FileNotFound: \"" + _context.RequestPath + "\" @ \"" + datapath + fn + "\""); 34 31 } 35 32 } -
binary-improvements2/MapRendering/Web/Handlers/UserStatusHandler.cs
r382 r387 1 1 using AllocsFixes.JSON; 2 using AllocsFixes.NetConnections.Servers.Web.API;3 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;4 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;5 2 6 3 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { … … 9 6 } 10 7 11 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 12 int _permissionLevel) { 8 public override void HandleRequest (RequestContext _context) { 13 9 JSONObject result = new JSONObject (); 14 10 15 result.Add ("loggedin", new JSONBoolean (_con != null));16 result.Add ("username", new JSONString (_con != null ? _con.UserId.ToString () : string.Empty));11 result.Add ("loggedin", new JSONBoolean (_context.Connection != null)); 12 result.Add ("username", new JSONString (_context.Connection != null ? _context.Connection.UserId.ToString () : string.Empty)); 17 13 18 14 JSONArray perms = new JSONArray (); … … 20 16 JSONObject permObj = new JSONObject (); 21 17 permObj.Add ("module", new JSONString (perm.module)); 22 permObj.Add ("allowed", new JSONBoolean (perm.permissionLevel >= _ permissionLevel));18 permObj.Add ("allowed", new JSONBoolean (perm.permissionLevel >= _context.PermissionLevel)); 23 19 perms.Add (permObj); 24 20 } … … 26 22 result.Add ("permissions", perms); 27 23 28 Web API.WriteJSON (_resp, result);24 WebUtils.WriteJson (_context.Response, result); 29 25 } 30 26 } -
binary-improvements2/MapRendering/Web/LogBuffer.cs
r382 r387 127 127 public class LogEntry { 128 128 public readonly DateTime timestamp; 129 public readonly string date;130 public readonly string time;131 129 public readonly string isoTime; 132 130 public readonly string message; … … 137 135 public LogEntry (DateTime _timestamp, string _message, string _trace, LogType _type, long _uptime) { 138 136 timestamp = _timestamp; 139 date = $"{_timestamp.Year:0000}-{_timestamp.Month:00}-{_timestamp.Day:00}";140 time = $"{_timestamp.Hour:00}:{_timestamp.Minute:00}:{_timestamp.Second:00}";141 137 isoTime = _timestamp.ToString ("o"); 142 138 -
binary-improvements2/MapRendering/Web/SSE/EventLog.cs
r382 r387 10 10 11 11 private void LogCallback (string _formattedMsg, string _plainMsg, string _trace, LogType _type, DateTime _timestamp, long _uptime) { 12 string date = $"{_timestamp.Year:0000}-{_timestamp.Month:00}-{_timestamp.Day:00}";13 string time = $"{_timestamp.Hour:00}:{_timestamp.Minute:00}:{_timestamp.Second:00}";14 12 string isotime = _timestamp.ToString ("o"); 15 13 string uptime = _uptime.ToString (); … … 20 18 data.Add ("type", new JSONString (_type.ToStringCached ())); 21 19 data.Add ("trace", new JSONString (_trace)); 22 data.Add ("date", new JSONString (date));23 data.Add ("time", new JSONString (time));24 20 data.Add ("isotime", new JSONString (isotime)); 25 21 data.Add ("uptime", new JSONString (uptime)); -
binary-improvements2/MapRendering/Web/SSE/SseHandler.cs
r382 r387 5 5 using System.Threading; 6 6 using AllocsFixes.NetConnections.Servers.Web.Handlers; 7 using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;8 using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;9 7 10 8 // Implemented following HTML spec … … 52 50 } 53 51 54 public override void HandleRequest (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 55 int _permissionLevel) { 56 string eventName = _requestPath.Remove (0, urlBasePath.Length); 52 public override void HandleRequest (RequestContext _context) { 53 string eventName = _context.RequestPath.Remove (0, urlBasePath.Length); 57 54 58 55 if (!events.TryGetValue (eventName, out EventBase eventInstance)) { 59 56 Log.Out ($"Error in {nameof (SseHandler)}.HandleRequest(): No handler found for event \"{eventName}\""); 60 _ resp.StatusCode = (int)HttpStatusCode.NotFound;57 _context.Response.StatusCode = (int)HttpStatusCode.NotFound; 61 58 return; 62 59 } 63 60 64 if (!IsAuthorizedForEvent (eventName, _ permissionLevel)) {65 _ resp.StatusCode = (int)HttpStatusCode.Forbidden;66 if (_con != null) {61 if (!IsAuthorizedForEvent (eventName, _context.PermissionLevel)) { 62 _context.Response.StatusCode = (int)HttpStatusCode.Forbidden; 63 if (_context.Connection != null) { 67 64 //Log.Out ($"{nameof(SseHandler)}: user '{user.SteamID}' not allowed to access '{eventName}'"); 68 65 } … … 72 69 73 70 try { 74 eventInstance.AddListener (_ resp);71 eventInstance.AddListener (_context.Response); 75 72 76 73 // Keep the request open 77 _ resp.SendChunked = true;74 _context.Response.SendChunked = true; 78 75 79 _ resp.AddHeader ("Content-Type", "text/event-stream");80 _ resp.OutputStream.Flush ();76 _context.Response.AddHeader ("Content-Type", "text/event-stream"); 77 _context.Response.OutputStream.Flush (); 81 78 } catch (Exception e) { 82 79 Log.Error ($"Error in {nameof (SseHandler)}.HandleRequest(): Handler {eventInstance.Name} threw an exception:"); 83 80 Log.Exception (e); 84 _ resp.StatusCode = (int)HttpStatusCode.InternalServerError;81 _context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; 85 82 } 86 83 } -
binary-improvements2/MapRendering/Web/Web.cs
r384 r387 6 6 using HttpStatusCode = System.Net.HttpStatusCode; 7 7 using IPEndPoint = System.Net.IPEndPoint; 8 using System.Text;9 8 using System.Threading; 10 9 using AllocsFixes.FileCache; … … 226 225 return; 227 226 } 228 229 ApplyPathHandler (requestPath, request, response, conn, permissionLevel); 227 228 RequestContext context = new RequestContext (requestPath, request, response, conn, permissionLevel); 229 230 ApplyPathHandler (context); 230 231 231 232 } catch (IOException e) { … … 252 253 } 253 254 254 public void ApplyPathHandler (string _requestPath, HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _con, 255 int _permissionLevel) { 255 public void ApplyPathHandler (RequestContext _context) { 256 256 for (int i = handlers.Count - 1; i >= 0; i--) { 257 257 AbsHandler handler = handlers [i]; 258 258 259 if (_ requestPath.StartsWith (handler.UrlBasePath)) {260 if (!handler.IsAuthorizedForHandler (_con , _permissionLevel)) {261 _ resp.StatusCode = (int)HttpStatusCode.Forbidden;262 if (_con != null) {259 if (_context.RequestPath.StartsWith (handler.UrlBasePath)) { 260 if (!handler.IsAuthorizedForHandler (_context.Connection, _context.PermissionLevel)) { 261 _context.Response.StatusCode = (int)HttpStatusCode.Forbidden; 262 if (_context.Connection != null) { 263 263 //Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", _con.SteamID, handler.ModuleName); 264 264 } … … 267 267 handlerSampler.Begin (); 268 268 #endif 269 handler.HandleRequest (_ requestPath, _req, _resp, _con, _permissionLevel);269 handler.HandleRequest (_context); 270 270 #if ENABLE_PROFILER 271 271 handlerSampler.End (); … … 279 279 // Not really relevant for non-debugging purposes: 280 280 //Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + _requestPath + "\""); 281 _ resp.StatusCode = (int) HttpStatusCode.NotFound;281 _context.Response.StatusCode = (int) HttpStatusCode.NotFound; 282 282 } 283 283 … … 314 314 return guestPermissionLevel; 315 315 } 316 317 public static void SetResponseTextContent (HttpListenerResponse _resp, string _text) {318 byte[] buf = Encoding.UTF8.GetBytes (_text);319 _resp.ContentLength64 = buf.Length;320 _resp.ContentType = "text/html";321 _resp.ContentEncoding = Encoding.UTF8;322 _resp.OutputStream.Write (buf, 0, buf.Length);323 }324 316 } 325 317 } -
binary-improvements2/MapRendering/Web/WebCommandResult.cs
r382 r387 49 49 50 50 if (responseType == ResultType.Raw) { 51 Web API.WriteText (response, sb.ToString ());51 WebUtils.WriteText (response, sb.ToString ()); 52 52 } else { 53 53 JSONNode result; … … 64 64 } 65 65 66 Web API.WriteJSON(response, result);66 WebUtils.WriteJson (response, result); 67 67 } 68 68 } catch (IOException e) { -
binary-improvements2/MapRendering/WebAndMapRendering.csproj
r386 r387 11 11 <AssemblyName>MapRendering</AssemblyName> 12 12 <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> 13 <LangVersion>8</LangVersion> 13 14 </PropertyGroup> 14 15 <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> … … 86 87 <Compile Include="Commands\EnableRendering.cs" /> 87 88 <Compile Include="API.cs" /> 89 <Compile Include="Web\API\AbsRestApi.cs" /> 88 90 <Compile Include="Web\API\GetAnimalsLocation.cs" /> 89 91 <Compile Include="Web\API\GetHostileLocation.cs" /> 90 92 <Compile Include="Web\API\GetWebMods.cs" /> 93 <Compile Include="Web\API\Markers.cs" /> 91 94 <Compile Include="Web\API\Null.cs" /> 92 95 <Compile Include="Web\Handlers\RewriteHandler.cs" /> 96 <Compile Include="Web\RequestContext.cs" /> 93 97 <Compile Include="Web\SSE\EventLog.cs" /> 94 98 <Compile Include="Web\SSE\SseHandler.cs" /> … … 97 101 <Compile Include="Web\MimeType.cs" /> 98 102 <Compile Include="Web\API\GetPlayersOnline.cs" /> 99 <Compile Include="Web\API\ WebAPI.cs" />103 <Compile Include="Web\API\AbsWebAPI.cs" /> 100 104 <Compile Include="Web\API\GetPlayersLocation.cs" /> 101 105 <Compile Include="Web\API\GetPlayerInventory.cs" /> … … 128 132 <Compile Include="Commands\EnableOpenIDDebug.cs" /> 129 133 <Compile Include="Web\API\GetPlayerInventories.cs" /> 134 <Compile Include="Web\WebUtils.cs" /> 130 135 </ItemGroup> 131 136 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
Note:
See TracChangeset
for help on using the changeset viewer.