| 20 | } |
| 21 | |
| 22 | public IDisposable Start() |
| 23 | { |
| 24 | if (inner != null) { |
| 25 | throw new InvalidOperationException("Already started!"); |
| 26 | } |
| 27 | |
| 28 | var server = new HttpListener(); |
| 29 | server.Prefixes.Add(String.Format("http://+:{0}/", Port)); |
| 30 | server.Start(); |
| 31 | |
| 32 | bool shouldStop = false; |
| 33 | var listener = Task.Run(async () => { |
| 34 | while (!shouldStop) { |
| 35 | var ctx = await server.GetContextAsync(); |
| 36 | |
| 37 | if (ctx.Request.HttpMethod != "GET") { |
| 38 | closeResponseWith(ctx, 400, "GETs only"); |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | var target = Path.Combine(RootPath, ctx.Request.Url.AbsolutePath.Replace('/', Path.DirectorySeparatorChar).Substring(1)); |
| 43 | var fi = new FileInfo(target); |
| 44 | |
| 45 | if (!fi.FullName.StartsWith(RootPath)) { |
| 46 | closeResponseWith(ctx, 401, "Not authorized"); |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | if (!fi.Exists) { |
| 51 | closeResponseWith(ctx, 404, "Not found"); |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | try { |
| 56 | using (var input = File.OpenRead(target)) { |
| 57 | ctx.Response.StatusCode = 200; |
| 58 | input.CopyTo(ctx.Response.OutputStream); |
| 59 | ctx.Response.Close(); |
| 60 | } |
| 61 | } catch (Exception ex) { |
| 62 | closeResponseWith(ctx, 500, ex.ToString()); |
| 63 | } |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | var ret = Disposable.Create(() => { |
| 68 | shouldStop = true; |
| 69 | server.Stop(); |
| 70 | listener.Wait(2000); |
| 71 | |
| 72 | inner = null; |
| 73 | }); |
| 74 | |
| 75 | inner = ret; |
| 76 | return ret; |
| 77 | } |
| 78 | |
| 79 | static void closeResponseWith(HttpListenerContext ctx, int statusCode, string message) |