Changeset 244 for binary-improvements/MapRendering
- Timestamp:
- Jul 21, 2015, 9:51:32 PM (9 years ago)
- Location:
- binary-improvements/MapRendering
- Files:
-
- 11 added
- 7 edited
- 5 moved
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements/MapRendering/Web/API/GetLandClaims.cs
r238 r244 9 9 public class GetLandClaims : WebAPI 10 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 12 { 13 13 string steamid = string.Empty; … … 17 17 steamid = req.QueryString ["steamid"]; 18 18 if (steamid.Length != 17 || !long.TryParse (steamid, out tempLong)) { 19 resp.StatusCode = (int)HttpStatusCode. InternalServerError;19 resp.StatusCode = (int)HttpStatusCode.BadRequest; 20 20 Web.SetResponseTextContent (resp, "Invalid SteamID given"); 21 21 return; -
binary-improvements/MapRendering/Web/API/GetPlayerInventory.cs
r233 r244 9 9 public class GetPlayerInventory : WebAPI 10 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 12 { 13 13 if (req.QueryString ["steamid"] == null) { -
binary-improvements/MapRendering/Web/API/GetPlayersLocation.cs
r233 r244 9 9 public class GetPlayersLocation : WebAPI 10 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 12 { 13 13 JSONArray playersJsResult = new JSONArray (); -
binary-improvements/MapRendering/Web/API/GetPlayersOnline.cs
r233 r244 9 9 public class GetPlayersOnline : WebAPI 10 10 { 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 12 12 { 13 13 JSONArray players = new JSONArray(); -
binary-improvements/MapRendering/Web/API/WebAPI.cs
r230 r244 16 16 } 17 17 18 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user);18 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel); 19 19 } 20 20 } -
binary-improvements/MapRendering/Web/Handlers/ApiHandler.cs
r230 r244 6 6 using System.Threading; 7 7 8 namespace AllocsFixes.NetConnections.Servers.Web 8 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 9 9 { 10 public class ApiHandler : PathHandler 11 { 10 public class ApiHandler : PathHandler { 12 11 private string staticPart; 13 12 private Dictionary<String, WebAPI> apis = new Dictionary<string, WebAPI> (); 14 13 15 public ApiHandler (string staticPart) 16 { 14 public ApiHandler (string staticPart, string moduleName = null) : base(moduleName) { 17 15 this.staticPart = staticPart; 18 apis.Add ("getlandclaims", new GetLandClaims ()); 19 apis.Add ("getplayersonline", new GetPlayersOnline ()); 20 apis.Add ("getplayerslocation", new GetPlayersLocation ()); 21 apis.Add ("getplayerinventory", new GetPlayerInventory ()); 16 addApi ("getlandclaims", new GetLandClaims ()); 17 addApi ("getplayersonline", new GetPlayersOnline ()); 18 addApi ("getplayerslocation", new GetPlayersLocation ()); 19 addApi ("getplayerinventory", new GetPlayerInventory ()); 20 addApi ("getstats", new GetStats ()); 22 21 } 23 22 24 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user) 25 { 23 private void addApi (string _apiName, WebAPI _api) { 24 apis.Add (_apiName, _api); 25 WebPermissions.Instance.AddKnownModule ("webapi." + _apiName); 26 } 27 28 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 26 29 string apiName = req.Url.AbsolutePath.Remove (0, staticPart.Length); 27 if (!AuthorizeForCommand (apiName, user )) {30 if (!AuthorizeForCommand (apiName, user, permissionLevel)) { 28 31 resp.StatusCode = (int)HttpStatusCode.Forbidden; 32 if (user != null) { 33 Log.Out ("ApiHandler: user '{0}' not allowed to execute '{1}'", user.SteamID, apiName); 34 } else { 35 Log.Out ("ApiHandler: unidentified user from '{0}' not allowed to execute '{1}'", req.RemoteEndPoint.Address, apiName); 36 } 37 return; 29 38 } else { 30 39 foreach (KeyValuePair<string, WebAPI> kvp in apis) { 31 40 try { 32 41 if (apiName.StartsWith (kvp.Key)) { 33 kvp.Value.HandleRequest (req, resp, user );42 kvp.Value.HandleRequest (req, resp, user, permissionLevel); 34 43 return; 35 44 } … … 46 55 } 47 56 48 private bool AuthorizeForCommand (string apiName, HttpListenerBasicIdentity user) 49 { 50 return true; 57 private bool AuthorizeForCommand (string apiName, WebConnection user, int permissionLevel) { 58 return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi." + apiName, permissionLevel); 51 59 } 52 60 -
binary-improvements/MapRendering/Web/Handlers/ItemIconHandler.cs
r242 r244 7 7 using UnityEngine; 8 8 9 namespace AllocsFixes.NetConnections.Servers.Web 9 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 10 10 { 11 11 public class ItemIconHandler : PathHandler … … 16 16 private bool loaded = false; 17 17 18 public ItemIconHandler (string staticPart, bool logMissingFiles ) {18 public ItemIconHandler (string staticPart, bool logMissingFiles, string moduleName = null) : base(moduleName) { 19 19 this.staticPart = staticPart; 20 20 this.logMissingFiles = logMissingFiles; 21 21 } 22 22 23 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user) {23 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) { 24 24 if (!loaded) { 25 25 if (!LoadIcons ()) { -
binary-improvements/MapRendering/Web/Handlers/PathHandler.cs
r230 r244 2 2 using System.Net; 3 3 4 namespace AllocsFixes.NetConnections.Servers.Web 4 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 5 5 { 6 6 public abstract class PathHandler 7 7 { 8 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user); 8 private string moduleName = null; 9 public string ModuleName { 10 get { return moduleName; } 11 } 12 13 protected PathHandler (string _moduleName) { 14 this.moduleName = _moduleName; 15 WebPermissions.Instance.AddKnownModule (_moduleName); 16 } 17 18 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel); 19 20 public bool IsAuthorizedForHandler (WebConnection user, int permissionLevel) { 21 if (moduleName != null) { 22 return WebPermissions.Instance.ModuleAllowedWithLevel (moduleName, permissionLevel); 23 } else { 24 return true; 25 } 26 } 9 27 } 10 28 } -
binary-improvements/MapRendering/Web/Handlers/SimpleRedirectHandler.cs
r230 r244 2 2 using System.Net; 3 3 4 namespace AllocsFixes.NetConnections.Servers.Web 4 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 5 5 { 6 6 public class SimpleRedirectHandler : PathHandler … … 8 8 string target; 9 9 10 public SimpleRedirectHandler (string target )10 public SimpleRedirectHandler (string target, string moduleName = null) : base(moduleName) 11 11 { 12 12 this.target = target; 13 13 } 14 14 15 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)15 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 16 16 { 17 17 resp.Redirect (target); -
binary-improvements/MapRendering/Web/Handlers/StaticHandler.cs
r230 r244 5 5 using System.Threading; 6 6 7 namespace AllocsFixes.NetConnections.Servers.Web 7 namespace AllocsFixes.NetConnections.Servers.Web.Handlers 8 8 { 9 9 public class StaticHandler : PathHandler … … 14 14 private bool logMissingFiles; 15 15 16 public StaticHandler (string staticPart, string filePath, AllocsFixes.FileCache.AbstractCache cache, bool logMissingFiles )16 public StaticHandler (string staticPart, string filePath, AllocsFixes.FileCache.AbstractCache cache, bool logMissingFiles, string moduleName = null) : base(moduleName) 17 17 { 18 18 this.staticPart = staticPart; … … 22 22 } 23 23 24 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, HttpListenerBasicIdentity user)24 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, int permissionLevel) 25 25 { 26 26 string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length); -
binary-improvements/MapRendering/Web/Web.cs
r238 r244 1 1 using System; 2 2 using System.Collections.Generic; 3 using System.Collections.Specialized; 3 4 using System.IO; 4 5 using System.Net; … … 9 10 using UnityEngine; 10 11 12 using AllocsFixes.NetConnections.Servers.Web.Handlers; 13 11 14 namespace AllocsFixes.NetConnections.Servers.Web 12 15 { 13 16 public class Web : IConsoleServer { 17 private const int GUEST_PERMISSION_LEVEL = 2000; 14 18 private readonly HttpListener _listener = new HttpListener (); 15 19 private Dictionary<string, PathHandler> handlers = new Dictionary<string, PathHandler> (); 16 private bool authEnabled = false;17 private string realm = "7dtd Admin Panel";18 20 public static int handlingCount = 0; 19 21 public static int currentHandlers = 0; 20 22 private string dataFolder; 21 private bool mapEnabled = false; 23 private bool useStaticCache = false; 24 25 public bool isSslRedirected { 26 private set; 27 get; 28 } 29 30 public ConnectionHandler connectionHandler; 22 31 23 32 public Web () { … … 25 34 int webPort = GamePrefs.GetInt (EnumGamePrefs.ControlPanelPort); 26 35 if (webPort < 1 || webPort > 65533) { 27 Log.Out ("Webserver not started (ControlPanelPort not within 1-6553 4)");36 Log.Out ("Webserver not started (ControlPanelPort not within 1-65533)"); 28 37 return; 29 38 } … … 33 42 } 34 43 44 // TODO: Read from config 45 isSslRedirected = false; 46 useStaticCache = false; 47 35 48 dataFolder = Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + "/webserver"; 36 49 … … 47 60 new SimpleRedirectHandler ("/static/favicon.ico")); 48 61 handlers.Add ( 49 "/static/", 50 new StaticHandler ( 51 "/static/", 52 dataFolder, 53 new AllocsFixes.FileCache.DirectAccess (), 54 true) 55 ); // TODO: Enable cache 62 "/session/", 63 new SessionHandler ( 64 "/session/", 65 dataFolder, 66 this) 67 ); 68 handlers.Add ( 69 "/userstatus", 70 new UserStatusHandler () 71 ); 72 if (useStaticCache) { 73 handlers.Add ( 74 "/static/", 75 new StaticHandler ( 76 "/static/", 77 dataFolder, 78 new AllocsFixes.FileCache.SimpleCache (), 79 true) 80 ); 81 } else { 82 handlers.Add ( 83 "/static/", 84 new StaticHandler ( 85 "/static/", 86 dataFolder, 87 new AllocsFixes.FileCache.DirectAccess (), 88 true) 89 ); 90 } 56 91 57 92 handlers.Add ( … … 68 103 GameUtils.GetSaveGameDir () + "/map", 69 104 MapRendering.MapRendering.GetTileCache (), 70 false) 71 ); 72 73 handlers.Add ("/api/", new ApiHandler ("/api/")); 105 false, 106 "web.map") 107 ); 108 109 handlers.Add ( 110 "/api/", 111 new ApiHandler ("/api/") 112 ); 113 114 connectionHandler = new ConnectionHandler (this); 74 115 75 116 _listener.Prefixes.Add (String.Format ("http://*:{0}/", webPort + 2)); 76 authEnabled = File.Exists (dataFolder + "/protect");77 if (authEnabled) {78 _listener.AuthenticationSchemes = AuthenticationSchemes.Basic;79 }80 117 _listener.Start (); 81 _listener.Realm = realm;82 118 83 119 SdtdConsole.Instance.RegisterServer (this); … … 85 121 _listener.BeginGetContext (new AsyncCallback (HandleRequest), _listener); 86 122 87 Log.Out ("Started Webserver on " + (webPort + 2) + " (authentication " + (authEnabled ? "enabled" : "disabled") + ")");123 Log.Out ("Started Webserver on " + (webPort + 2)); 88 124 } catch (Exception e) { 89 125 Log.Out ("Error in Web.ctor: " + e); … … 98 134 _listener.BeginGetContext (new AsyncCallback (HandleRequest), _listener); 99 135 try { 100 ctx.Response.ProtocolVersion = new Version ("1.0"); 101 102 HttpListenerBasicIdentity user = Authorize (ctx); 103 104 if (!authEnabled || (user.Name.ToLower ().Equals ("admin") && user.Password.Equals (GamePrefs.GetString (EnumGamePrefs.ControlPanelPassword)))) { 105 if (ctx.Request.Url.AbsolutePath.Length < 2) { 106 handlers ["/index.htm"].HandleRequest (ctx.Request, ctx.Response, user); 107 return; 108 } else { 109 foreach (KeyValuePair<string, PathHandler> kvp in handlers) { 110 if (ctx.Request.Url.AbsolutePath.StartsWith (kvp.Key)) { 111 kvp.Value.HandleRequest (ctx.Request, ctx.Response, user); 112 return; 136 HttpListenerRequest request = ctx.Request; 137 HttpListenerResponse response = ctx.Response; 138 139 response.ProtocolVersion = new Version ("1.1"); 140 141 WebConnection conn; 142 int permissionLevel = DoAuthentication (request, out conn); 143 144 145 //Log.Out ("Login status: conn!=null: {0}, permissionlevel: {1}", conn != null, permissionLevel); 146 147 148 if (conn != null) { 149 Cookie cookie = new Cookie ("sid", conn.SessionID, "/"); 150 cookie.Expired = false; 151 cookie.Expires = new DateTime (2020, 1, 1); 152 cookie.HttpOnly = true; 153 cookie.Secure = false; 154 response.AppendCookie (cookie); 155 } 156 157 if (request.Url.AbsolutePath.Length < 2) { 158 handlers ["/index.htm"].HandleRequest (request, response, conn, permissionLevel); 159 return; 160 } else { 161 foreach (KeyValuePair<string, PathHandler> kvp in handlers) { 162 if (request.Url.AbsolutePath.StartsWith (kvp.Key)) { 163 if (!kvp.Value.IsAuthorizedForHandler (conn, permissionLevel)) { 164 response.StatusCode = (int)HttpStatusCode.Forbidden; 165 if (conn != null) { 166 Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", conn.SteamID, kvp.Value.ModuleName); 167 } else { 168 Log.Out ("Web.HandleRequest: unidentified user from '{0}' not allowed to access '{1}'", request.RemoteEndPoint.Address, kvp.Value.ModuleName); 169 } 170 } else { 171 kvp.Value.HandleRequest (request, response, conn, permissionLevel); 113 172 } 173 return; 114 174 } 115 175 } 116 117 Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + ctx.Request.Url.AbsolutePath + "\""); 118 ctx.Response.StatusCode = (int)HttpStatusCode.NotFound; 119 } else { 120 ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized; 121 ctx.Response.Headers ["WWW-Authenticate"] = "Basic realm=\"" + realm + "\""; 122 } 176 } 177 178 Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + request.Url.AbsolutePath + "\""); 179 response.StatusCode = (int)HttpStatusCode.NotFound; 123 180 } catch (IOException e) { 124 181 if (e.InnerException is SocketException) { … … 131 188 } finally { 132 189 if (ctx != null) { 133 ctx.Response. OutputStream.Close ();190 ctx.Response.Close (); 134 191 } 135 192 Interlocked.Decrement (ref currentHandlers); … … 138 195 } 139 196 140 private HttpListenerBasicIdentity Authorize (HttpListenerContext ctx) { 141 try { 142 return (HttpListenerBasicIdentity)ctx.User.Identity; 143 } catch (NullReferenceException) { 144 return null; 145 } 197 private int DoAuthentication (HttpListenerRequest _req, out WebConnection _con) { 198 _con = null; 199 200 string sessionId = null; 201 if (_req.Cookies ["sid"] != null) { 202 sessionId = _req.Cookies ["sid"].Value; 203 } 204 205 if (!string.IsNullOrEmpty (sessionId)) { 206 WebConnection con = connectionHandler.IsLoggedIn (sessionId, _req.RemoteEndPoint.Address.ToString ()); 207 if (con != null) { 208 _con = con; 209 return GameManager.Instance.adminTools.GetAdminToolsClientInfo (_con.SteamID.ToString ()).PermissionLevel; 210 } 211 } 212 213 if (_req.QueryString ["adminuser"] != null && _req.QueryString ["admintoken"] != null) { 214 WebPermissions.AdminToken admin = WebPermissions.Instance.GetWebAdmin (_req.QueryString ["adminuser"], _req.QueryString ["admintoken"]); 215 if (admin != null) { 216 return admin.permissionLevel; 217 } else { 218 Log.Warning ("Invalid Admintoken used from " + _req.RemoteEndPoint.ToString ()); 219 } 220 } 221 222 if (_req.Url.AbsolutePath.StartsWith ("/session/verify")) { 223 ulong id = OpenID.Validate (_req); 224 if (id > 0) { 225 WebConnection con = connectionHandler.LogIn (id, _req.RemoteEndPoint.Address.ToString ()); 226 _con = con; 227 //Log.Out ("Logged in with session id: {0}", con.SessionID); 228 return GameManager.Instance.adminTools.GetAdminToolsClientInfo (id.ToString ()).PermissionLevel; 229 } else { 230 Log.Out ("Steam OpenID login failed from {0}", _req.RemoteEndPoint.ToString ()); 231 } 232 } 233 234 return GUEST_PERMISSION_LEVEL; 146 235 } 147 236 … … 156 245 157 246 public void SendLine (string line) { 158 try { 159 //Log.Out ("NOT IMPLEMENTED: Web.WriteToClient"); 160 } catch (Exception e) { 161 Log.Out ("Error in Web.WriteToClient: " + e); 162 } 247 connectionHandler.SendLine (line); 163 248 } 164 249 165 250 public void SendLog (string text, string trace, UnityEngine.LogType type) { 166 //throw new System.NotImplementedException ();251 connectionHandler.SendLog (text, trace, type); 167 252 } 168 253 -
binary-improvements/MapRendering/WebAndMapRendering.csproj
r238 r244 38 38 <Private>False</Private> 39 39 </Reference> 40 <Reference Include="System.Xml"> 41 <HintPath>..\7dtd-binaries\System.Xml.dll</HintPath> 42 <Private>False</Private> 43 </Reference> 40 44 </ItemGroup> 41 45 <ItemGroup> … … 48 52 <Compile Include="API.cs" /> 49 53 <Compile Include="Web\Web.cs" /> 50 <Compile Include="Web\PathHandler.cs" />51 <Compile Include="Web\StaticHandler.cs" />52 <Compile Include="Web\SimpleRedirectHandler.cs" />53 54 <Compile Include="Web\MimeType.cs" /> 54 <Compile Include="Web\ApiHandler.cs" />55 55 <Compile Include="Web\API\GetPlayersOnline.cs" /> 56 56 <Compile Include="Web\API\WebAPI.cs" /> … … 59 59 <Compile Include="Web\API\GetLandClaims.cs" /> 60 60 <Compile Include="Commands\webstat.cs" /> 61 <Compile Include="Web\ItemIconHandler.cs" /> 61 <Compile Include="Web\API\GetStats.cs" /> 62 <Compile Include="Web\WebConnection.cs" /> 63 <Compile Include="Web\OpenID.cs" /> 64 <Compile Include="Web\ConnectionHandler.cs" /> 65 <Compile Include="Web\WebPermissions.cs" /> 66 <Compile Include="Web\Handlers\ApiHandler.cs" /> 67 <Compile Include="Web\Handlers\ItemIconHandler.cs" /> 68 <Compile Include="Web\Handlers\PathHandler.cs" /> 69 <Compile Include="Web\Handlers\SimpleRedirectHandler.cs" /> 70 <Compile Include="Web\Handlers\StaticHandler.cs" /> 71 <Compile Include="Web\Handlers\SessionHandler.cs" /> 72 <Compile Include="Web\API\ExecuteConsoleCommand.cs" /> 73 <Compile Include="Commands\ReloadWebPermissions.cs" /> 74 <Compile Include="Web\Handlers\UserStatusHandler.cs" /> 75 <Compile Include="Commands\WebTokens.cs" /> 76 <Compile Include="Commands\WebPermissionsCmd.cs" /> 62 77 </ItemGroup> 63 78 <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> … … 71 86 <ItemGroup> 72 87 <Folder Include="Commands\" /> 88 <Folder Include="Web\Handlers\" /> 73 89 </ItemGroup> 74 90 <ItemGroup>
Note:
See TracChangeset
for help on using the changeset viewer.