-
Notifications
You must be signed in to change notification settings - Fork 3
/
LocalServerProcessor.cs
705 lines (548 loc) · 25.7 KB
/
LocalServerProcessor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// Copyright (c) 2023 Fox Council - VintageHive - https://github.com/FoxCouncil/VintageHive
using Fluid;
using Fluid.Ast;
using Fluid.Values;
using HeyRed.Mime;
using Humanizer;
using System.Web;
using VintageHive.Processors.LocalServer;
using VintageHive.Proxy.Ftp;
using VintageHive.Proxy.Http;
using HttpStatusCode = VintageHive.Proxy.Http.HttpStatusCode;
namespace VintageHive.Processors;
internal static class LocalServerProcessor
{
static readonly FluidParser fluidParser = new();
static LocalServerProcessor()
{
TemplateOptions.Default.MemberAccessStrategy = new UnsafeMemberAccessStrategy();
TemplateOptions.Default.Filters.AddFilter("bytes", (input, arguments, context) =>
{
return StringValue.Create(((long)input.ToNumberValue()).Bytes().Humanize());
});
TemplateOptions.Default.Filters.AddFilter("urlencode", (input, arguments, context) =>
{
return StringValue.Create(HttpUtility.UrlEncode(input.ToStringValue()));
});
TemplateOptions.Default.Filters.AddFilter("wmotostring", (input, arguments, context) =>
{
return StringValue.Create(WeatherUtils.ConvertWmoCodeToString((int)input.ToNumberValue()));
});
TemplateOptions.Default.Filters.AddFilter("pathlinksplit", (input, arguments, context) =>
{
var path = input.ToStringValue();
if (path == "/")
{
return input;
}
dynamic model = context.Model.ToObjectValue();
var repo = model.Request.QueryParams["repo"];
var pathParts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (pathParts.Length > 1)
{
for (int i = 0; i < pathParts.Length - 1; i++)
{
pathParts[i] = $"<a href=\"download.html?repo={HttpUtility.UrlEncode(repo)}&path={HttpUtility.UrlEncode(path[..(path.IndexOf(pathParts[i]) + pathParts[i].Length)] + "/")}\">{pathParts[i]}</a>";
}
}
return StringValue.Create("/" + string.Join('/', pathParts) + "/");
});
TemplateOptions.Default.Filters.AddFilter("tag_parse", (input, arguments, context) =>
{
var tags = input.ToStringValue().Split(',', StringSplitOptions.RemoveEmptyEntries);
if (!tags.Any())
{
return StringValue.Empty;
}
var sb = new StringBuilder();
foreach (var tag in tags)
{
sb.Append($"| <a href=\"/browser.html?tag={HttpUtility.UrlEncode(tag)}\">{tag.ApplyCase(LetterCasing.Sentence)}</a> ");
}
return StringValue.Create(sb.ToString().Trim()[2..]);
});
fluidParser.RegisterEmptyTag("displayMessageHtml", static async (writer, encoder, context) =>
{
var response = (await context.Model.GetValueAsync("Response", context)).ToObjectValue() as HttpResponse;
if (response.HasSession("error"))
{
writer.Write($"<div class=\"alert alert-danger alert-dismissible fade show\" role=\"alert\">");
writer.Write($"{response.Session.error}");
writer.Write($"<button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"alert\" aria-label=\"Close\"></button>");
writer.Write($"</div>");
response.RemoveSession("error");
}
return Completion.Normal;
});
fluidParser.RegisterEmptyTag("displayMessageText", static async (writer, encoder, context) =>
{
var response = (await context.Model.GetValueAsync("Response", context)).ToObjectValue() as HttpResponse;
if (response.HasSession("error"))
{
writer.Write($"{response.Session.error}");
response.RemoveSession("error");
}
return Completion.Normal;
});
}
public static async Task<bool> ProcessFtpRequest(FtpRequest req)
{
if (req.Uri.Host.StartsWith("ftp."))
{
// let's play ISP
var hostDomain = req.Uri.Host.Replace("ftp.", string.Empty).ToLower();
if (string.IsNullOrWhiteSpace(hostDomain))
{
return false;
}
var hostPath = Path.Combine("hosting", hostDomain);
if (!VFS.DirectoryExists(hostPath))
{
VFS.DirectoryCreate(hostPath);
}
// Todo; authentication
await req.SendUserLoggedIn();
var isActive = true;
var transferType = FtpTransferType.ASCII;
var dataListener = new TcpListener(IPAddress.Parse(req.ListenerSocket.LocalIP), 0);
TcpClient dataClient = null;
var basePath = hostPath;
var currentPath = "/";
var resumeOffset = long.MinValue;
var renamePath = "";
while (isActive)
{
var payload = await req.FetchCommand();
if (payload == null)
{
break;
}
var command = payload.Item1.ToUpper();
var args = payload.Item2;
switch (command)
{
case FtpCommand.SystemType:
{
await req.SendResponse(FtpResponseCode.NameSystemType, "UNIX");
}
break;
case FtpCommand.FeatureList:
{
await req.SendFeatureListResponse(FtpResponseCode.SystemStatus, new[] { "SIZE" });
}
break;
case FtpCommand.PrintWorkingDirectory:
{
await req.SendResponse(FtpResponseCode.PathnameCreated, $"\"{currentPath}\" is the current directory");
}
break;
case FtpCommand.ChangeWorkingDirectory:
{
var relPath = args.StartsWith("/") ? args : Path.Combine(currentPath, args);
if (string.IsNullOrWhiteSpace(relPath))
{
relPath = "/";
}
var path = Path.Combine(basePath, PathGetReal(relPath));
if (VFS.DirectoryExists(path))
{
currentPath = relPath;
await req.SendResponse(FtpResponseCode.RequestedFileActionOkay, "CWD command successful");
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, "Directory not found");
}
}
break;
case FtpCommand.MakeDirectory:
{
var path = Path.Combine(basePath, PathGetReal(currentPath), PathGetReal(args));
if (!VFS.DirectoryExists(path))
{
VFS.DirectoryCreate(path);
await req.SendResponse(FtpResponseCode.PathnameCreated, $"\"{args}\" directory created");
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, "Failed to create directory: already exists");
}
}
break;
case FtpCommand.DeleteDirectory:
{
var path = Path.Combine(basePath, PathGetReal(args));
if (VFS.DirectoryExists(path))
{
try
{
VFS.DirectoryDelete(path);
await req.SendResponse(FtpResponseCode.RequestedFileActionOkay, $"\"{args}\" directory deleted");
}
catch (Exception e)
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to deleted directory: {e.Message}");
Log.WriteLine(Log.LEVEL_ERROR, nameof(LocalServerProcessor), e.Message, req.ListenerSocket.TraceId.ToString());
}
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to deleted directory: \"{args}\" doesn't exists");
}
}
break;
case FtpCommand.DeleteFile:
{
var path = Path.Combine(basePath, PathGetReal(args));
if (VFS.FileExists(path))
{
try
{
VFS.FileDelete(path);
await req.SendResponse(FtpResponseCode.RequestedFileActionOkay, $"{args} file deleted");
}
catch (Exception ex)
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to retrieve file: {ex.Message}");
}
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, "File Not Found");
}
}
break;
case FtpCommand.RenameFrom:
{
var path = Path.Combine(basePath, PathGetReal(args));
if (VFS.FileExists(path) || VFS.DirectoryExists(path))
{
renamePath = path;
await req.SendResponse(FtpResponseCode.RequestedFileActionPendingMore, "File exists, ready for destination name");
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, "File does not exist");
}
}
break;
case FtpCommand.RenameTo:
{
if (string.IsNullOrEmpty(renamePath))
{
await req.SendResponse(FtpResponseCode.BadSequenceOfCommands, "Bad sequence of commands: RNFR must be issued first");
break;
}
var path = Path.Combine(basePath, PathGetReal(args));
try
{
if (VFS.FileExists(renamePath))
{
VFS.FileMove(renamePath, path);
await req.SendResponse(FtpResponseCode.RequestedFileActionOkay, $"File renamed from {renamePath.Replace(basePath, string.Empty)} to {path.Replace(basePath, string.Empty)}");
}
else if (VFS.DirectoryExists(renamePath))
{
VFS.DirectoryMove(renamePath, path);
await req.SendResponse(FtpResponseCode.RequestedFileActionOkay, $"Directory renamed from {renamePath.Replace(basePath, string.Empty)} to {path.Replace(basePath, string.Empty)}");
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"File or directory does not exist");
}
}
catch (Exception ex)
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to rename file or directory: {ex.Message}");
}
finally
{
renamePath = string.Empty;
}
}
break;
case FtpCommand.TransferMode:
{
transferType = args;
await req.SendResponse(FtpResponseCode.CommandSuccess, $"Type set to {FtpTransferType.NameFromType(args)}");
}
break;
case FtpCommand.PassiveMode:
{
dataListener.Start();
IPEndPoint endpoint = (IPEndPoint)dataListener.LocalEndpoint;
var address = endpoint.Address.GetAddressBytes();
var port = endpoint.Port;
resumeOffset = 0;
await req.SendResponse(FtpResponseCode.EnteringPassiveMode, $"Entering Passive Mode ({address[0]},{address[1]},{address[2]},{address[3]},{port >> 8},{port & 0xff})");
}
break;
case FtpCommand.ListInfo:
{
await req.SendResponse(FtpResponseCode.FileStatusOkay, $"Opening {FtpTransferType.NameFromType(transferType)} mode data connection for file list");
dataClient = dataListener.AcceptTcpClient();
using var dataStream = dataClient.GetStream();
using var dataWriter = new StreamWriter(dataStream);
var path = Path.Combine(basePath, PathGetReal(currentPath));
var directoryList = VFS.DirectoryList(path);
foreach (var directoryItem in directoryList)
{
if (Directory.Exists(directoryItem))
{
var info = new DirectoryInfo(directoryItem);
string permissions = "drwxrwxrwx";
string owner = "100";
string group = "100";
string size = "0";
string date = info.LastWriteTime.ToString("MMM dd HH:mm");
string name = info.Name;
string line = string.Format("{0} {1} {2,8} {3,9} {4,12} {5} {6}", permissions, 1, owner, group, size, date, name);
dataWriter.WriteLine(line);
}
else if (File.Exists(directoryItem))
{
var info = new FileInfo(directoryItem);
string permissions = "-rw-rw-rw-";
string owner = "100";
string group = "100";
string size = info.Length.ToString();
string date = info.LastWriteTime.ToString("MMM dd HH:mm");
string name = info.Name;
string line = string.Format("{0} {1} {2,8} {3,9} {4,12} {5} {6}", permissions, 1, owner, group, size, date, name);
dataWriter.WriteLine(line);
}
else
{
throw new ApplicationException("What?");
}
}
dataWriter.Close();
dataClient.Close();
dataListener.Stop();
await req.SendResponse(FtpResponseCode.DataConnectionClosing, "Transfer complete");
}
break;
case FtpCommand.RestartTransfer:
{
if (long.TryParse(args, out var result))
{
if (result == 0)
{
await req.SendResponse(FtpResponseCode.RequestedFileActionPendingMore, "Clearing transfer restart offset");
}
else
{
resumeOffset = result;
await req.SendResponse(FtpResponseCode.RequestedFileActionPendingMore, $"Restarting transfer at {resumeOffset}");
}
}
else
{
await req.SendResponse(FtpResponseCode.SyntaxError, $"Syntax error in parameters or arguments for REST");
}
}
break;
case FtpCommand.RetrieveFile:
{
await req.SendResponse(FtpResponseCode.FileStatusOkay, $"Opening {FtpTransferType.NameFromType(transferType)} mode data connection for file transfer");
dataClient = dataListener.AcceptTcpClient();
using var dataStream = dataClient.GetStream();
var path = Path.Combine(basePath, PathGetReal(currentPath), args);
if (VFS.FileExists(path))
{
using var fileStream = VFS.FileReadStream(path);
fileStream.Position = resumeOffset;
try
{
await fileStream.CopyToAsync(dataStream);
}
catch (Exception ex)
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to retrieve file: {ex.Message}");
dataClient.Close();
dataListener.Stop();
break;
}
}
else
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to retrieve file: File Does Not Exist");
dataClient.Close();
dataListener.Stop();
break;
}
dataClient.Close();
dataListener.Stop();
await req.SendResponse(FtpResponseCode.DataConnectionClosing, "Transfer complete");
}
break;
case FtpCommand.StoreFile:
{
await req.SendResponse(FtpResponseCode.FileStatusOkay, $"Opening {FtpTransferType.NameFromType(transferType)} mode data connection for file storage");
dataClient = dataListener.AcceptTcpClient();
using var dataStream = dataClient.GetStream();
var path = Path.Combine(basePath, PathGetReal(currentPath), args);
try
{
using var fileStream = VFS.FileWrite(path);
await dataStream.CopyToAsync(fileStream);
}
catch (Exception ex)
{
await req.SendResponse(FtpResponseCode.RequestedActionNotTaken, $"Failed to retrieve file: {ex.Message}");
dataClient.Close();
dataListener.Stop();
break;
}
dataClient.Close();
dataListener.Stop();
await req.SendResponse(FtpResponseCode.DataConnectionClosing, "Transfer complete");
}
break;
case FtpCommand.Quit:
{
await req.SendResponse(FtpResponseCode.ServerClosingControlConnection, "Goodbye");
isActive = false;
}
break;
case FtpCommand.Bark:
{
await req.SendResponse(FtpResponseCode.CommandSuccess, "Bark! Bark!");
}
break;
default:
{
await req.SendResponse(FtpResponseCode.CommandNotImplemented, "Command not implemented");
}
break;
}
}
if (dataClient != null && dataClient.Connected)
{
dataClient.Close();
}
dataListener?.Stop();
return true;
}
return false;
}
public static async Task<bool> ProcessHttpsRequest(HttpRequest req, HttpResponse res)
{
await Task.Delay(0);
return RunLocalHostedSites(req, res);
}
public static async Task<bool> ProcessHttpRequest(HttpRequest req, HttpResponse res)
{
if (req.Uri.IsLoopback)
{
var newRedirectedUri = new UriBuilder(req.Uri)
{
Host = "admin.hive.com"
};
req.Uri = newRedirectedUri.Uri;
}
else if (req.Uri.Host == "admin.hive.com")
{
return false;
}
var site = ControllerManager.Fetch(req, res);
if (site != null)
{
return await ProcessController(req, res, site);
}
return RunLocalHostedSites(req, res);
}
private static bool RunLocalHostedSites(HttpRequest req, HttpResponse res)
{
var host = req.Uri.Host;
if (host.StartsWith("www"))
{
var vfsFolder = host.Replace("www.", string.Empty);
var wwwFolder = Path.Combine("hosting", vfsFolder, "www");
if (VFS.DirectoryExists(wwwFolder))
{
var file = req.Uri.AbsolutePath;
if (file == "/")
{
file = "/index.html";
}
var vfsFile = Path.Combine(wwwFolder, PathGetReal(file));
if (VFS.FileExists(vfsFile))
{
var mimetype = MimeTypesMap.GetMimeType(file);
var fileStream = VFS.FileReadStream(vfsFile);
res.SetStreamForDownload(fileStream, mimetype);
return true;
}
}
}
return false;
}
private static async Task<bool> ProcessController(HttpRequest req, HttpResponse res, Controller site)
{
res.Cache = false;
var fileRequestPath = req.Uri.AbsolutePath;
if (fileRequestPath == "/")
{
fileRequestPath = "/index.html";
}
await site.CallMethod(fileRequestPath);
if (res.Handled)
{
return true;
}
var requestFilePath = Path.Combine("controllers/", req.Uri.Host+"/", Path.IsPathRooted(fileRequestPath) ? fileRequestPath[1..] : fileRequestPath);
Log.WriteLine(Log.LEVEL_DEBUG, nameof(LocalServerProcessor), $"RequestedPath: {requestFilePath}", req.ListenerSocket.TraceId.ToString());
Log.WriteLine(Log.LEVEL_DEBUG, nameof(LocalServerProcessor), $"StaticsPath: {VFS.StaticsPath}", req.ListenerSocket.TraceId.ToString());
var virtualPath = VFS.GetVirtualPath(VFS.StaticsPath, requestFilePath);
Log.WriteLine(Log.LEVEL_DEBUG, nameof(LocalServerProcessor), $"VirtualPath: {virtualPath}", req.ListenerSocket.TraceId.ToString());
var isReplacedFile = VFS.FileExists(virtualPath);
var resourceFile = "";
if (!isReplacedFile)
{
resourceFile = requestFilePath.Replace(Path.DirectorySeparatorChar, '.').Replace(Path.AltDirectorySeparatorChar, '.');
if (!Resources.Statics.ContainsKey(resourceFile))
{
res.SetNotFound();
return true;
}
}
var vfsPath = VFS.GetVirtualPath(VFS.StaticsPath, requestFilePath);
var mimetype = MimeTypesMap.GetMimeType(requestFilePath);
switch (mimetype)
{
case "text/html":
{
var source = isReplacedFile ? await VFS.FileReadStringAsync(vfsPath) : Resources.GetStaticsResourceString(resourceFile);
if (fluidParser.TryParse(source, out var template, out var error))
{
res.SetBodyString(await template.RenderAsync(res.Context), "text/html; charset=utf-8");
}
else
{
res.SetStatusCode(HttpStatusCode.InternalServerError).SetBodyString(error);
}
}
break;
default:
{
res.SetBodyData(isReplacedFile ? await VFS.FileReadDataAsync(vfsPath) : Resources.GetStaticsResourceData(resourceFile), mimetype);
}
break;
}
return true;
}
static string PathCombine(string path1, string path2)
{
if (Path.IsPathRooted(path2))
{
path2 = path2.TrimStart(Path.DirectorySeparatorChar);
path2 = path2.TrimStart(Path.AltDirectorySeparatorChar);
}
return Path.Combine(path1, path2);
}
static string PathGetReal(string virtualPath)
{
return virtualPath.TrimStart('/').Replace('/', '\\');
}
}