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