Changeset 244 for binary-improvements/MapRendering/Web/Web.cs
- Timestamp:
- Jul 21, 2015, 9:51:32 PM (9 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
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
Note:
See TracChangeset
for help on using the changeset viewer.