[391] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.IO;
|
---|
| 4 | using System.Net.Sockets;
|
---|
| 5 | using SpaceWizards.HttpListener;
|
---|
| 6 | using UnityEngine;
|
---|
[402] | 7 | using Webserver.FileCache;
|
---|
[404] | 8 | using Webserver.Permissions;
|
---|
[391] | 9 | using Webserver.UrlHandlers;
|
---|
| 10 | using Cookie = System.Net.Cookie;
|
---|
| 11 | using HttpStatusCode = System.Net.HttpStatusCode;
|
---|
| 12 | using IPEndPoint = System.Net.IPEndPoint;
|
---|
| 13 |
|
---|
| 14 | namespace Webserver {
|
---|
| 15 | public class Web : IConsoleServer {
|
---|
[402] | 16 | public static event Action<Web> ServerInitialized;
|
---|
| 17 |
|
---|
[391] | 18 | private const string indexPageUrl = "/app";
|
---|
| 19 |
|
---|
| 20 | private readonly List<AbsHandler> handlers = new List<AbsHandler> ();
|
---|
[434] | 21 | public readonly List<WebMod> WebMods = new List<WebMod> ();
|
---|
[412] | 22 | public readonly ConnectionHandler ConnectionHandler;
|
---|
[391] | 23 |
|
---|
| 24 | private readonly HttpListener listener = new HttpListener ();
|
---|
| 25 | private readonly Version httpProtocolVersion = new Version(1, 1);
|
---|
| 26 |
|
---|
[404] | 27 | private readonly AsyncCallback handleRequestDelegate;
|
---|
| 28 |
|
---|
[391] | 29 | public Web (string _modInstancePath) {
|
---|
| 30 | try {
|
---|
[412] | 31 | bool dashboardEnabled = GamePrefs.GetBool (EnumUtils.Parse<EnumGamePrefs> (nameof (EnumGamePrefs.WebDashboardEnabled)));
|
---|
| 32 | if (!dashboardEnabled) {
|
---|
| 33 | Log.Out ($"[Web] Webserver not started, {nameof (EnumGamePrefs.WebDashboardEnabled)} set to false");
|
---|
| 34 | return;
|
---|
| 35 | }
|
---|
| 36 |
|
---|
| 37 | int webPort = GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> (nameof (EnumGamePrefs.WebDashboardPort)));
|
---|
[391] | 38 | if (webPort < 1 || webPort > 65533) {
|
---|
[412] | 39 | Log.Out ($"[Web] Webserver not started ({nameof (EnumGamePrefs.WebDashboardPort)} not within 1-65535)");
|
---|
[391] | 40 | return;
|
---|
| 41 | }
|
---|
| 42 |
|
---|
| 43 | if (!HttpListener.IsSupported) {
|
---|
[398] | 44 | Log.Out ("[Web] Webserver not started (HttpListener.IsSupported returned false)");
|
---|
[391] | 45 | return;
|
---|
| 46 | }
|
---|
| 47 |
|
---|
[412] | 48 | if (string.IsNullOrEmpty (GamePrefs.GetString (EnumUtils.Parse<EnumGamePrefs> (nameof (EnumGamePrefs.WebDashboardUrl))))) {
|
---|
| 49 | Log.Warning ($"[Web] {nameof (EnumGamePrefs.WebDashboardUrl)} not set. Recommended to set it to the public URL pointing to your dashboard / reverse proxy");
|
---|
| 50 | }
|
---|
| 51 |
|
---|
| 52 | ConnectionHandler = new ConnectionHandler ();
|
---|
[391] | 53 |
|
---|
[426] | 54 | RegisterDefaultHandlers (_modInstancePath);
|
---|
[391] | 55 |
|
---|
[402] | 56 | // Allow other code to add their stuff
|
---|
| 57 | ServerInitialized?.Invoke (this);
|
---|
[391] | 58 |
|
---|
| 59 | listener.Prefixes.Add ($"http://+:{webPort}/");
|
---|
| 60 | listener.Start ();
|
---|
[404] | 61 | handleRequestDelegate = HandleRequest;
|
---|
| 62 | listener.BeginGetContext (handleRequestDelegate, listener);
|
---|
[391] | 63 |
|
---|
| 64 | SdtdConsole.Instance.RegisterServer (this);
|
---|
| 65 |
|
---|
[402] | 66 | Log.Out ($"[Web] Started Webserver on port {webPort}");
|
---|
[391] | 67 | } catch (Exception e) {
|
---|
[398] | 68 | Log.Error ("[Web] Error in Web.ctor: ");
|
---|
[391] | 69 | Log.Exception (e);
|
---|
| 70 | }
|
---|
| 71 | }
|
---|
| 72 |
|
---|
[426] | 73 | private void RegisterDefaultHandlers (string _modInstancePath) {
|
---|
| 74 | // TODO: Read from config
|
---|
| 75 | bool useCacheForStatic = StringParsers.ParseBool ("false");
|
---|
| 76 |
|
---|
| 77 | string webfilesFolder = DetectWebserverFolder (_modInstancePath);
|
---|
| 78 |
|
---|
| 79 | RegisterPathHandler ("/", new RewriteHandler ("/files/"));
|
---|
| 80 |
|
---|
| 81 | // React virtual routing
|
---|
| 82 | RegisterPathHandler ("/app", new RewriteHandler ("/files/index.html", true));
|
---|
| 83 |
|
---|
| 84 | // Do mods relatively early as they should not be requested a lot, unlike the later registrations, especially for API and map tiles
|
---|
| 85 | RegisterWebMods (useCacheForStatic);
|
---|
| 86 |
|
---|
| 87 | RegisterPathHandler ("/session/", new SessionHandler (ConnectionHandler));
|
---|
| 88 | RegisterPathHandler ("/userstatus", new UserStatusHandler ());
|
---|
| 89 | RegisterPathHandler ("/sse/", new SseHandler ());
|
---|
| 90 | RegisterPathHandler ("/files/", new StaticHandler (
|
---|
| 91 | webfilesFolder,
|
---|
| 92 | useCacheForStatic ? new SimpleCache () : new DirectAccess (),
|
---|
| 93 | false)
|
---|
| 94 | );
|
---|
| 95 | RegisterPathHandler ("/itemicons/", new ItemIconHandler (true));
|
---|
| 96 | RegisterPathHandler ("/api/", new ApiHandler ());
|
---|
| 97 | }
|
---|
| 98 |
|
---|
[398] | 99 | private static string DetectWebserverFolder (string _modInstancePath) {
|
---|
[431] | 100 | const string webrootFolderName = "webroot";
|
---|
| 101 |
|
---|
| 102 | string webserverFolder = $"{_modInstancePath}/{webrootFolderName}";
|
---|
[398] | 103 |
|
---|
| 104 | foreach (Mod mod in ModManager.GetLoadedMods ()) {
|
---|
[431] | 105 | string modServerFolder = $"{mod.Path}/{webrootFolderName}";
|
---|
[398] | 106 |
|
---|
| 107 | if (Directory.Exists (modServerFolder)) {
|
---|
| 108 | webserverFolder = modServerFolder;
|
---|
| 109 | }
|
---|
| 110 | }
|
---|
| 111 |
|
---|
| 112 | Log.Out ($"[Web] Serving basic webserver files from {webserverFolder}");
|
---|
| 113 |
|
---|
| 114 | return webserverFolder;
|
---|
| 115 | }
|
---|
| 116 |
|
---|
[391] | 117 | public void RegisterPathHandler (string _urlBasePath, AbsHandler _handler) {
|
---|
| 118 | foreach (AbsHandler handler in handlers) {
|
---|
| 119 | if (handler.UrlBasePath != _urlBasePath) {
|
---|
| 120 | continue;
|
---|
| 121 | }
|
---|
| 122 |
|
---|
[398] | 123 | Log.Error ($"[Web] Handler for relative path {_urlBasePath} already registerd.");
|
---|
[391] | 124 | return;
|
---|
| 125 | }
|
---|
| 126 |
|
---|
| 127 | handlers.Add (_handler);
|
---|
| 128 | _handler.SetBasePathAndParent (this, _urlBasePath);
|
---|
| 129 | }
|
---|
| 130 |
|
---|
| 131 | private void RegisterWebMods (bool _useStaticCache) {
|
---|
| 132 | foreach (Mod mod in ModManager.GetLoadedMods ()) {
|
---|
| 133 | try {
|
---|
| 134 | try {
|
---|
| 135 | WebMod webMod = new WebMod (this, mod, _useStaticCache);
|
---|
[434] | 136 | WebMods.Add (webMod);
|
---|
[391] | 137 | } catch (InvalidDataException e) {
|
---|
[402] | 138 | Log.Error ($"[Web] Could not load webmod from mod {mod.Name}: {e.Message}");
|
---|
[391] | 139 | }
|
---|
| 140 | } catch (Exception e) {
|
---|
[402] | 141 | Log.Error ($"[Web] Failed loading web mods from mod {mod.Name}");
|
---|
[391] | 142 | Log.Exception (e);
|
---|
| 143 | }
|
---|
| 144 | }
|
---|
| 145 | }
|
---|
| 146 |
|
---|
| 147 | public void Disconnect () {
|
---|
| 148 | try {
|
---|
| 149 | listener.Stop ();
|
---|
| 150 | listener.Close ();
|
---|
| 151 | } catch (Exception e) {
|
---|
[402] | 152 | Log.Out ($"[Web] Error in Web.Disconnect: {e}");
|
---|
[391] | 153 | }
|
---|
| 154 | }
|
---|
| 155 |
|
---|
| 156 | public void Shutdown () {
|
---|
| 157 | foreach (AbsHandler handler in handlers) {
|
---|
| 158 | handler.Shutdown ();
|
---|
| 159 | }
|
---|
| 160 | }
|
---|
| 161 |
|
---|
| 162 | public void SendLine (string _line) {
|
---|
[412] | 163 | ConnectionHandler.SendLine (_line);
|
---|
[391] | 164 | }
|
---|
| 165 |
|
---|
| 166 | public void SendLog (string _formattedMessage, string _plainMessage, string _trace, LogType _type, DateTime _timestamp, long _uptime) {
|
---|
| 167 | // Do nothing, handled by LogBuffer internally
|
---|
| 168 | }
|
---|
| 169 |
|
---|
[394] | 170 | private readonly UnityEngine.Profiling.CustomSampler getContextSampler = UnityEngine.Profiling.CustomSampler.Create ("GetCtx");
|
---|
[391] | 171 | private readonly UnityEngine.Profiling.CustomSampler authSampler = UnityEngine.Profiling.CustomSampler.Create ("Auth");
|
---|
[394] | 172 | private readonly UnityEngine.Profiling.CustomSampler cookieSampler = UnityEngine.Profiling.CustomSampler.Create ("ConCookie");
|
---|
[391] | 173 | private readonly UnityEngine.Profiling.CustomSampler handlerSampler = UnityEngine.Profiling.CustomSampler.Create ("Handler");
|
---|
| 174 |
|
---|
| 175 | private void HandleRequest (IAsyncResult _result) {
|
---|
| 176 | HttpListener listenerInstance = (HttpListener)_result.AsyncState;
|
---|
| 177 | if (!listenerInstance.IsListening) {
|
---|
| 178 | return;
|
---|
| 179 | }
|
---|
| 180 |
|
---|
| 181 | #if ENABLE_PROFILER
|
---|
| 182 | UnityEngine.Profiling.Profiler.BeginThreadProfiling ("AllocsMods", "WebRequest");
|
---|
[394] | 183 | getContextSampler.Begin ();
|
---|
[391] | 184 | HttpListenerContext ctx = listenerInstance.EndGetContext (_result);
|
---|
[394] | 185 | getContextSampler.End ();
|
---|
[391] | 186 | try {
|
---|
| 187 | #else
|
---|
| 188 | HttpListenerContext ctx = listenerInstance.EndGetContext (_result);
|
---|
| 189 | listenerInstance.BeginGetContext (HandleRequest, listenerInstance);
|
---|
| 190 | #endif
|
---|
| 191 | try {
|
---|
| 192 | HttpListenerRequest request = ctx.Request;
|
---|
| 193 | HttpListenerResponse response = ctx.Response;
|
---|
| 194 | response.SendChunked = false;
|
---|
| 195 |
|
---|
| 196 | response.ProtocolVersion = httpProtocolVersion;
|
---|
| 197 |
|
---|
| 198 | // No game yet -> fail request
|
---|
| 199 | if (GameManager.Instance.World == null) {
|
---|
| 200 | response.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
|
---|
| 201 | return;
|
---|
| 202 | }
|
---|
| 203 |
|
---|
| 204 | if (request.Url == null) {
|
---|
| 205 | response.StatusCode = (int) HttpStatusCode.BadRequest;
|
---|
| 206 | return;
|
---|
| 207 | }
|
---|
| 208 |
|
---|
| 209 | authSampler.Begin ();
|
---|
| 210 | int permissionLevel = DoAuthentication (request, out WebConnection conn);
|
---|
| 211 | authSampler.End ();
|
---|
| 212 |
|
---|
| 213 | //Log.Out ("Login status: conn!=null: {0}, permissionlevel: {1}", conn != null, permissionLevel);
|
---|
| 214 |
|
---|
[394] | 215 | cookieSampler.Begin ();
|
---|
[391] | 216 | if (conn != null) {
|
---|
| 217 | Cookie cookie = new Cookie ("sid", conn.SessionID, "/") {
|
---|
| 218 | Expired = false,
|
---|
| 219 | Expires = DateTime.MinValue,
|
---|
| 220 | HttpOnly = true,
|
---|
| 221 | Secure = false
|
---|
| 222 | };
|
---|
| 223 | response.AppendCookie (cookie);
|
---|
| 224 | }
|
---|
[394] | 225 | cookieSampler.End ();
|
---|
[391] | 226 |
|
---|
| 227 | string requestPath = request.Url.AbsolutePath;
|
---|
| 228 |
|
---|
| 229 | if (requestPath.Length < 2) {
|
---|
| 230 | response.Redirect (indexPageUrl);
|
---|
| 231 | return;
|
---|
| 232 | }
|
---|
| 233 |
|
---|
| 234 | RequestContext context = new RequestContext (requestPath, request, response, conn, permissionLevel);
|
---|
[415] | 235 |
|
---|
| 236 | if (context.Method == ERequestMethod.Other) {
|
---|
| 237 | context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
|
---|
| 238 | return;
|
---|
| 239 | }
|
---|
[391] | 240 |
|
---|
| 241 | ApplyPathHandler (context);
|
---|
| 242 |
|
---|
| 243 | } catch (IOException e) {
|
---|
| 244 | if (e.InnerException is SocketException) {
|
---|
[402] | 245 | Log.Out ($"[Web] Error in Web.HandleRequest(): Remote host closed connection: {e.InnerException.Message}");
|
---|
[391] | 246 | } else {
|
---|
[402] | 247 | Log.Out ($"[Web] Error (IO) in Web.HandleRequest(): {e}");
|
---|
[391] | 248 | }
|
---|
| 249 | } catch (Exception e) {
|
---|
[398] | 250 | Log.Error ("[Web] Error in Web.HandleRequest(): ");
|
---|
[391] | 251 | Log.Exception (e);
|
---|
| 252 | } finally {
|
---|
| 253 | if (!ctx.Response.SendChunked) {
|
---|
| 254 | ctx.Response.Close ();
|
---|
| 255 | }
|
---|
| 256 | }
|
---|
| 257 | #if ENABLE_PROFILER
|
---|
| 258 | } finally {
|
---|
[404] | 259 | listenerInstance.BeginGetContext (handleRequestDelegate, listenerInstance);
|
---|
[391] | 260 | UnityEngine.Profiling.Profiler.EndThreadProfiling ();
|
---|
| 261 | }
|
---|
| 262 | #endif
|
---|
| 263 | }
|
---|
| 264 |
|
---|
| 265 | public void ApplyPathHandler (RequestContext _context) {
|
---|
| 266 | for (int i = handlers.Count - 1; i >= 0; i--) {
|
---|
| 267 | AbsHandler handler = handlers [i];
|
---|
| 268 |
|
---|
| 269 | if (!_context.RequestPath.StartsWith (handler.UrlBasePath)) {
|
---|
| 270 | continue;
|
---|
| 271 | }
|
---|
| 272 |
|
---|
| 273 | if (!handler.IsAuthorizedForHandler (_context.Connection, _context.PermissionLevel)) {
|
---|
| 274 | _context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
|
---|
| 275 | if (_context.Connection != null) {
|
---|
| 276 | //Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", _con.SteamID, handler.ModuleName);
|
---|
| 277 | }
|
---|
| 278 | } else {
|
---|
| 279 | handlerSampler.Begin ();
|
---|
| 280 | handler.HandleRequest (_context);
|
---|
| 281 | handlerSampler.End ();
|
---|
| 282 | }
|
---|
| 283 |
|
---|
| 284 | return;
|
---|
| 285 | }
|
---|
| 286 |
|
---|
| 287 | // Not really relevant for non-debugging purposes:
|
---|
| 288 | //Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + _requestPath + "\"");
|
---|
| 289 | _context.Response.StatusCode = (int) HttpStatusCode.NotFound;
|
---|
| 290 | }
|
---|
| 291 |
|
---|
| 292 | private int DoAuthentication (HttpListenerRequest _req, out WebConnection _con) {
|
---|
| 293 | _con = null;
|
---|
| 294 |
|
---|
| 295 | string sessionId = _req.Cookies ["sid"]?.Value;
|
---|
| 296 |
|
---|
| 297 | IPEndPoint reqRemoteEndPoint = _req.RemoteEndPoint;
|
---|
| 298 | if (reqRemoteEndPoint == null) {
|
---|
[398] | 299 | Log.Warning ("[Web] No RemoteEndPoint on web request");
|
---|
[426] | 300 | return AdminWebModules.PermissionLevelGuest;
|
---|
[391] | 301 | }
|
---|
| 302 |
|
---|
| 303 | if (!string.IsNullOrEmpty (sessionId)) {
|
---|
[412] | 304 | _con = ConnectionHandler.IsLoggedIn (sessionId, reqRemoteEndPoint.Address);
|
---|
[391] | 305 | if (_con != null) {
|
---|
[404] | 306 | int level1 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_con.UserId);
|
---|
| 307 | int level2 = int.MaxValue;
|
---|
| 308 | if (_con.CrossplatformUserId != null) {
|
---|
| 309 | level2 = GameManager.Instance.adminTools.Users.GetUserPermissionLevel (_con.CrossplatformUserId);
|
---|
| 310 | }
|
---|
| 311 |
|
---|
| 312 | return Math.Min (level1, level2);
|
---|
[391] | 313 | }
|
---|
| 314 | }
|
---|
| 315 |
|
---|
[404] | 316 | if (!_req.Headers.TryGetValue ("X-SDTD-API-TOKENNAME", out string apiTokenName) ||
|
---|
| 317 | !_req.Headers.TryGetValue ("X-SDTD-API-SECRET", out string apiTokenSecret)) {
|
---|
[426] | 318 | return AdminWebModules.PermissionLevelGuest;
|
---|
[391] | 319 | }
|
---|
| 320 |
|
---|
[404] | 321 | int adminLevel = AdminApiTokens.Instance.GetPermissionLevel (apiTokenName, apiTokenSecret);
|
---|
| 322 | if (adminLevel < int.MaxValue) {
|
---|
| 323 | return adminLevel;
|
---|
[391] | 324 | }
|
---|
| 325 |
|
---|
[402] | 326 | Log.Warning ($"[Web] Invalid Admintoken used from {reqRemoteEndPoint}");
|
---|
[391] | 327 |
|
---|
[426] | 328 | return AdminWebModules.PermissionLevelGuest;
|
---|
[391] | 329 | }
|
---|
| 330 | }
|
---|
| 331 | }
|
---|