1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.IO;
|
---|
4 | using System.Net;
|
---|
5 | using System.Net.Sockets;
|
---|
6 | using System.Reflection;
|
---|
7 | using System.Text;
|
---|
8 | using System.Threading;
|
---|
9 | using AllocsFixes.FileCache;
|
---|
10 | using AllocsFixes.NetConnections.Servers.Web.Handlers;
|
---|
11 | using UnityEngine;
|
---|
12 |
|
---|
13 | namespace AllocsFixes.NetConnections.Servers.Web {
|
---|
14 | public class Web : IConsoleServer {
|
---|
15 | private const int GUEST_PERMISSION_LEVEL = 2000;
|
---|
16 | public static int handlingCount;
|
---|
17 | public static int currentHandlers;
|
---|
18 | public static long totalHandlingTime = 0;
|
---|
19 | private readonly HttpListener _listener = new HttpListener ();
|
---|
20 | private readonly string dataFolder;
|
---|
21 | private readonly Dictionary<string, PathHandler> handlers = new Dictionary<string, PathHandler> ();
|
---|
22 | private readonly bool useStaticCache;
|
---|
23 |
|
---|
24 | public ConnectionHandler connectionHandler;
|
---|
25 |
|
---|
26 | public Web () {
|
---|
27 | try {
|
---|
28 | int webPort = GamePrefs.GetInt (EnumGamePrefs.ControlPanelPort);
|
---|
29 | if (webPort < 1 || webPort > 65533) {
|
---|
30 | Log.Out ("Webserver not started (ControlPanelPort not within 1-65533)");
|
---|
31 | return;
|
---|
32 | }
|
---|
33 |
|
---|
34 | if (!Directory.Exists (Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) +
|
---|
35 | "/webserver")) {
|
---|
36 | Log.Out ("Webserver not started (folder \"webserver\" not found in WebInterface mod folder)");
|
---|
37 | return;
|
---|
38 | }
|
---|
39 |
|
---|
40 | // TODO: Read from config
|
---|
41 | useStaticCache = false;
|
---|
42 |
|
---|
43 | dataFolder = Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location) + "/webserver";
|
---|
44 |
|
---|
45 | if (!HttpListener.IsSupported) {
|
---|
46 | Log.Out ("Webserver not started (needs Windows XP SP2, Server 2003 or later or Mono)");
|
---|
47 | return;
|
---|
48 | }
|
---|
49 |
|
---|
50 | handlers.Add (
|
---|
51 | "/index.htm",
|
---|
52 | new SimpleRedirectHandler ("/static/index.html"));
|
---|
53 | handlers.Add (
|
---|
54 | "/favicon.ico",
|
---|
55 | new SimpleRedirectHandler ("/static/favicon.ico"));
|
---|
56 | handlers.Add (
|
---|
57 | "/session/",
|
---|
58 | new SessionHandler (
|
---|
59 | "/session/",
|
---|
60 | dataFolder,
|
---|
61 | this)
|
---|
62 | );
|
---|
63 | handlers.Add (
|
---|
64 | "/userstatus",
|
---|
65 | new UserStatusHandler ()
|
---|
66 | );
|
---|
67 | if (useStaticCache) {
|
---|
68 | handlers.Add (
|
---|
69 | "/static/",
|
---|
70 | new StaticHandler (
|
---|
71 | "/static/",
|
---|
72 | dataFolder,
|
---|
73 | new SimpleCache (),
|
---|
74 | false)
|
---|
75 | );
|
---|
76 | } else {
|
---|
77 | handlers.Add (
|
---|
78 | "/static/",
|
---|
79 | new StaticHandler (
|
---|
80 | "/static/",
|
---|
81 | dataFolder,
|
---|
82 | new DirectAccess (),
|
---|
83 | false)
|
---|
84 | );
|
---|
85 | }
|
---|
86 |
|
---|
87 | handlers.Add (
|
---|
88 | "/itemicons/",
|
---|
89 | new ItemIconHandler (
|
---|
90 | "/itemicons/",
|
---|
91 | true)
|
---|
92 | );
|
---|
93 |
|
---|
94 | handlers.Add (
|
---|
95 | "/map/",
|
---|
96 | new StaticHandler (
|
---|
97 | "/map/",
|
---|
98 | GameUtils.GetSaveGameDir () + "/map",
|
---|
99 | MapRendering.MapRendering.GetTileCache (),
|
---|
100 | false,
|
---|
101 | "web.map")
|
---|
102 | );
|
---|
103 |
|
---|
104 | handlers.Add (
|
---|
105 | "/api/",
|
---|
106 | new ApiHandler ("/api/")
|
---|
107 | );
|
---|
108 |
|
---|
109 | connectionHandler = new ConnectionHandler (this);
|
---|
110 |
|
---|
111 | _listener.Prefixes.Add (string.Format ("http://*:{0}/", webPort + 2));
|
---|
112 | _listener.Start ();
|
---|
113 |
|
---|
114 | SdtdConsole.Instance.RegisterServer (this);
|
---|
115 |
|
---|
116 | _listener.BeginGetContext (HandleRequest, _listener);
|
---|
117 |
|
---|
118 | Log.Out ("Started Webserver on " + (webPort + 2));
|
---|
119 | } catch (Exception e) {
|
---|
120 | Log.Out ("Error in Web.ctor: " + e);
|
---|
121 | }
|
---|
122 | }
|
---|
123 |
|
---|
124 | public void Disconnect () {
|
---|
125 | try {
|
---|
126 | _listener.Stop ();
|
---|
127 | _listener.Close ();
|
---|
128 | } catch (Exception e) {
|
---|
129 | Log.Out ("Error in Web.Disconnect: " + e);
|
---|
130 | }
|
---|
131 | }
|
---|
132 |
|
---|
133 | public void SendLine (string line) {
|
---|
134 | connectionHandler.SendLine (line);
|
---|
135 | }
|
---|
136 |
|
---|
137 | public void SendLog (string text, string trace, LogType type) {
|
---|
138 | // Do nothing, handled by LogBuffer internally
|
---|
139 | }
|
---|
140 |
|
---|
141 | public static bool isSslRedirected (HttpListenerRequest req) {
|
---|
142 | string proto = req.Headers ["X-Forwarded-Proto"];
|
---|
143 | if (!string.IsNullOrEmpty (proto)) {
|
---|
144 | return proto.Equals ("https", StringComparison.OrdinalIgnoreCase);
|
---|
145 | }
|
---|
146 |
|
---|
147 | return false;
|
---|
148 | }
|
---|
149 |
|
---|
150 | private void HandleRequest (IAsyncResult result) {
|
---|
151 | if (_listener.IsListening) {
|
---|
152 | Interlocked.Increment (ref handlingCount);
|
---|
153 | Interlocked.Increment (ref currentHandlers);
|
---|
154 |
|
---|
155 | // MicroStopwatch msw = new MicroStopwatch ();
|
---|
156 | HttpListenerContext ctx = _listener.EndGetContext (result);
|
---|
157 | _listener.BeginGetContext (HandleRequest, _listener);
|
---|
158 | try {
|
---|
159 | HttpListenerRequest request = ctx.Request;
|
---|
160 | HttpListenerResponse response = ctx.Response;
|
---|
161 | response.SendChunked = false;
|
---|
162 |
|
---|
163 | response.ProtocolVersion = new Version ("1.1");
|
---|
164 |
|
---|
165 | WebConnection conn;
|
---|
166 | int permissionLevel = DoAuthentication (request, out conn);
|
---|
167 |
|
---|
168 |
|
---|
169 | //Log.Out ("Login status: conn!=null: {0}, permissionlevel: {1}", conn != null, permissionLevel);
|
---|
170 |
|
---|
171 |
|
---|
172 | if (conn != null) {
|
---|
173 | Cookie cookie = new Cookie ("sid", conn.SessionID, "/");
|
---|
174 | cookie.Expired = false;
|
---|
175 | cookie.Expires = new DateTime (2020, 1, 1);
|
---|
176 | cookie.HttpOnly = true;
|
---|
177 | cookie.Secure = false;
|
---|
178 | response.AppendCookie (cookie);
|
---|
179 | }
|
---|
180 |
|
---|
181 | // No game yet -> fail request
|
---|
182 | if (GameManager.Instance.World == null) {
|
---|
183 | response.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
|
---|
184 | return;
|
---|
185 | }
|
---|
186 |
|
---|
187 | if (request.Url.AbsolutePath.Length < 2) {
|
---|
188 | handlers ["/index.htm"].HandleRequest (request, response, conn, permissionLevel);
|
---|
189 | return;
|
---|
190 | } else {
|
---|
191 | foreach (KeyValuePair<string, PathHandler> kvp in handlers) {
|
---|
192 | if (request.Url.AbsolutePath.StartsWith (kvp.Key)) {
|
---|
193 | if (!kvp.Value.IsAuthorizedForHandler (conn, permissionLevel)) {
|
---|
194 | response.StatusCode = (int) HttpStatusCode.Forbidden;
|
---|
195 | if (conn != null) {
|
---|
196 | //Log.Out ("Web.HandleRequest: user '{0}' not allowed to access '{1}'", conn.SteamID, kvp.Value.ModuleName);
|
---|
197 | }
|
---|
198 | } else {
|
---|
199 | kvp.Value.HandleRequest (request, response, conn, permissionLevel);
|
---|
200 | }
|
---|
201 |
|
---|
202 | return;
|
---|
203 | }
|
---|
204 | }
|
---|
205 | }
|
---|
206 |
|
---|
207 | // Not really relevant for non-debugging purposes:
|
---|
208 | //Log.Out ("Error in Web.HandleRequest(): No handler found for path \"" + request.Url.AbsolutePath + "\"");
|
---|
209 | response.StatusCode = (int) HttpStatusCode.NotFound;
|
---|
210 | } catch (IOException e) {
|
---|
211 | if (e.InnerException is SocketException) {
|
---|
212 | Log.Out ("Error in Web.HandleRequest(): Remote host closed connection: " +
|
---|
213 | e.InnerException.Message);
|
---|
214 | } else {
|
---|
215 | Log.Out ("Error (IO) in Web.HandleRequest(): " + e);
|
---|
216 | }
|
---|
217 | } catch (Exception e) {
|
---|
218 | Log.Out ("Error in Web.HandleRequest(): " + e);
|
---|
219 | } finally {
|
---|
220 | if (ctx != null && !ctx.Response.SendChunked) {
|
---|
221 | ctx.Response.Close ();
|
---|
222 | }
|
---|
223 |
|
---|
224 | // msw.Stop ();
|
---|
225 | // totalHandlingTime += msw.ElapsedMicroseconds;
|
---|
226 | // Log.Out ("Web.HandleRequest(): Took {0} µs", msw.ElapsedMicroseconds);
|
---|
227 | Interlocked.Decrement (ref currentHandlers);
|
---|
228 | }
|
---|
229 | }
|
---|
230 | }
|
---|
231 |
|
---|
232 | private int DoAuthentication (HttpListenerRequest _req, out WebConnection _con) {
|
---|
233 | _con = null;
|
---|
234 |
|
---|
235 | string sessionId = null;
|
---|
236 | if (_req.Cookies ["sid"] != null) {
|
---|
237 | sessionId = _req.Cookies ["sid"].Value;
|
---|
238 | }
|
---|
239 |
|
---|
240 | if (!string.IsNullOrEmpty (sessionId)) {
|
---|
241 | WebConnection con = connectionHandler.IsLoggedIn (sessionId, _req.RemoteEndPoint.Address.ToString ());
|
---|
242 | if (con != null) {
|
---|
243 | _con = con;
|
---|
244 | return GameManager.Instance.adminTools.GetAdminToolsClientInfo (_con.SteamID.ToString ())
|
---|
245 | .PermissionLevel;
|
---|
246 | }
|
---|
247 | }
|
---|
248 |
|
---|
249 | if (_req.QueryString ["adminuser"] != null && _req.QueryString ["admintoken"] != null) {
|
---|
250 | WebPermissions.AdminToken admin = WebPermissions.Instance.GetWebAdmin (_req.QueryString ["adminuser"],
|
---|
251 | _req.QueryString ["admintoken"]);
|
---|
252 | if (admin != null) {
|
---|
253 | return admin.permissionLevel;
|
---|
254 | }
|
---|
255 |
|
---|
256 | Log.Warning ("Invalid Admintoken used from " + _req.RemoteEndPoint);
|
---|
257 | }
|
---|
258 |
|
---|
259 | if (_req.Url.AbsolutePath.StartsWith ("/session/verify")) {
|
---|
260 | try {
|
---|
261 | ulong id = OpenID.Validate (_req);
|
---|
262 | if (id > 0) {
|
---|
263 | WebConnection con = connectionHandler.LogIn (id, _req.RemoteEndPoint.Address.ToString ());
|
---|
264 | _con = con;
|
---|
265 | int level = GameManager.Instance.adminTools.GetAdminToolsClientInfo (id.ToString ())
|
---|
266 | .PermissionLevel;
|
---|
267 | Log.Out ("Steam OpenID login from {0} with ID {1}, permission level {2}",
|
---|
268 | _req.RemoteEndPoint.ToString (), con.SteamID, level);
|
---|
269 | return level;
|
---|
270 | }
|
---|
271 |
|
---|
272 | Log.Out ("Steam OpenID login failed from {0}", _req.RemoteEndPoint.ToString ());
|
---|
273 | } catch (Exception e) {
|
---|
274 | Log.Error ("Error validating login:");
|
---|
275 | Log.Exception (e);
|
---|
276 | }
|
---|
277 | }
|
---|
278 |
|
---|
279 | return GUEST_PERMISSION_LEVEL;
|
---|
280 | }
|
---|
281 |
|
---|
282 | public static void SetResponseTextContent (HttpListenerResponse resp, string text) {
|
---|
283 | byte[] buf = Encoding.UTF8.GetBytes (text);
|
---|
284 | resp.ContentLength64 = buf.Length;
|
---|
285 | resp.ContentType = "text/html";
|
---|
286 | resp.ContentEncoding = Encoding.UTF8;
|
---|
287 | resp.OutputStream.Write (buf, 0, buf.Length);
|
---|
288 | }
|
---|
289 | }
|
---|
290 | }
|
---|