source: binary-improvements2/WebServer/src/Web.cs@ 402

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