-
Notifications
You must be signed in to change notification settings - Fork 0
/
Startup.cs
638 lines (599 loc) · 24.2 KB
/
Startup.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
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using FreneticMediaServer.MediaTypes;
using Microsoft.Extensions.Primitives;
using Microsoft.Extensions.Hosting;
using System.Threading;
using Microsoft.AspNetCore.StaticFiles.Infrastructure;
namespace FreneticMediaServer
{
public class Startup
{
public static readonly UTF8Encoding EncodingUTF8 = GeneralHelpers.EncodingUTF8;
public static byte[] Page_Error = EncodingUTF8.GetBytes("<!doctype HTML><html><head><title>Error!</title></head><body>An error occurred.</body></html>");
public static string Page_Ref_FileView = File.ReadAllText("./page_ref.html", EncodingUTF8);
public static void LogWarning(string message)
{
Console.WriteLine(DateTime.Now.ToString() + " [Warning] " + message);
}
public long GlobalMaxFileSize = 0;
public string RawWebUrl = null;
public string MetaFilePath = null;
public string RawFilePath = null;
public bool RebuildImages = true;
public string ContactEmail = null;
public void ConfigureServices(IServiceCollection services)
{
}
public static readonly Object[] FileLockers = new Object[256];
public static readonly Object[] UserLockers = new Object[256];
static Startup()
{
for (int i = 0; i < FileLockers.Length; i++)
{
FileLockers[i] = new Object();
}
for (int i = 0; i < UserLockers.Length; i++)
{
UserLockers[i] = new Object();
}
}
public static Object PickFileLockFor(string text)
{
return FileLockers[text.GetHashCode() & 255];
}
public static Object PickUserLockFor(string name)
{
return UserLockers[name.GetHashCode() & 255];
}
public ConcurrentDictionary<string, User> KnownUsers = new ConcurrentDictionary<string, User>();
public bool ValidateCleanTextInputLine(string input)
{
if (input.Length == 0)
{
return false;
}
for (int i = 0; i < input.Length; i++)
{
if (!(
(input[i] >= 'A' && input[i] <= 'Z')
|| (input[i] >= 'a' && input[i] <= 'z')
|| (input[i] >= '0' && input[i] <= '9')
|| (input[i] == '_')
))
{
return false;
}
}
return true;
}
public User ReadUserFile(string name)
{
name = name.ToLowerInvariant();
if (!ValidateCleanTextInputLine(name))
{
return null;
}
lock (PickUserLockFor(name))
{
if (KnownUsers.TryGetValue(name, out User usr))
{
return usr;
}
string fpath = "./config/users/" + name + ".cfg";
if (!File.Exists(fpath))
{
return null;
}
string file = File.ReadAllText(fpath);
usr = new User(name, file);
return usr;
}
}
public User GetUser(string name)
{
name = name.ToLowerInvariant();
if (!ValidateCleanTextInputLine(name))
{
return null;
}
return KnownUsers.GetOrAdd(name, ReadUserFile);
}
public void ApplyConfigSetting(string setting, string value)
{
switch (setting)
{
case "raw_web_url":
RawWebUrl = value;
break;
case "meta_file_path":
MetaFilePath = value;
break;
case "rebuild_images":
RebuildImages = value.ToLowerInvariant() == "true";
break;
case "raw_file_path":
RawFilePath = value;
break;
case "support_email":
ContactEmail = value;
break;
case "global_max_file_size":
long? parsedFileSize = GeneralHelpers.ParseFileSizeLimit(value);
if (!parsedFileSize.HasValue)
{
throw new FormatException("Invalid file size limit value '" + value + "' ... must be an integer number followed by B, KB, MB, or GB");
}
GlobalMaxFileSize = parsedFileSize.Value;
break;
default:
LogWarning("Unknown config setting '" + setting + "'");
break;
}
}
public void LoadConfig()
{
if (!File.Exists("./config/main.cfg"))
{
throw new Exception("Config file not available. Please create a file at './config/main.cfg' based on the sample config.");
}
string config_data = File.ReadAllText("./config/main.cfg");
foreach (KeyValuePair<string, string> option in GeneralHelpers.ReadConfigData(config_data, (line) => LogWarning("Invalid configuration line '" + line + "'")))
{
ApplyConfigSetting(option.Key, option.Value);
}
if (GlobalMaxFileSize <= 0)
{
throw new Exception("Config MUST specify a global max file size!");
}
if (RawWebUrl == null)
{
throw new Exception("Config MUST specify a raw web URL!");
}
if (MetaFilePath == null)
{
throw new Exception("Config MUST specify a meta file path!");
}
if (RawFilePath == null)
{
throw new Exception("Config MUST specify a raw file path!");
}
}
public Dictionary<string, MediaType> KnownMediaTypes = new Dictionary<string, MediaType>(128);
public void RegisterMediaType(MediaType type)
{
foreach (string ext in type.GetValidExtensions())
{
KnownMediaTypes.Add(ext, type);
}
}
public void EstablishMediaHandlers()
{
RegisterMediaType(new ImageMediaType() { Server = this });
RegisterMediaType(new AnimationMediaType() { Server = this });
// TODO: video (mp4, webm, mpeg, avi)
// TODO: audio (mp3, wav, ogg)
// TODO: text (txt)
// TODO: Possibly, code text files? (Pastebin with highlighting)
}
public void SetupHttpHeaders(HttpContext context, int code)
{
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.StatusCode = code;
}
public async Task Write(HttpContext context, string text)
{
await context.Response.WriteAsync(text, EncodingUTF8);
}
public async Task<bool> HandlePage_Get_FileView(HttpContext context, string subPath)
{
subPath = subPath.ToLowerInvariant();
int slash_index = subPath.IndexOf('/');
if (slash_index < 1)
{
return false;
}
string category = subPath.Substring(0, slash_index);
string file_with_ext = subPath[(slash_index + 1)..];
if (file_with_ext.Contains('/'))
{
return false;
}
int ext_index = file_with_ext.LastIndexOf('.');
if (ext_index < 1)
{
return false;
}
string file = file_with_ext.Substring(0, ext_index);
string ext = file_with_ext[(ext_index + 1)..];
if (!KnownMediaTypes.TryGetValue(ext, out MediaType type))
{
return false;
}
if (!ValidateCleanTextInputLine(category))
{
return false;
}
if (!ValidateCleanTextInputLine(file))
{
return false;
}
if (!ValidateCleanTextInputLine(ext.Replace('.', '_')))
{
return false;
}
MetaFile meta = GetMetaFor(category, file);
if (meta == null)
{
return false;
}
SetupHttpHeaders(context, 200);
await Write(context, type.GenerateHtmlPageFor(category, file, ext, meta));
return true;
}
public MetaFile GetMetaFor(string category, string file)
{
string metaFile = MetaFilePath + category + "/" + file + ".meta";
if (File.Exists(metaFile))
{
return new MetaFile(File.ReadAllText(metaFile, EncodingUTF8));
}
return null;
}
public async Task<bool> HandlePage_Any_Delete(HttpContext context, string subPath, string code)
{
subPath = subPath.ToLowerInvariant();
int slash_index = subPath.IndexOf('/');
if (slash_index < 1)
{
return false;
}
string category = subPath.Substring(0, slash_index);
string file_with_ext = subPath[(slash_index + 1)..];
if (file_with_ext.Contains('/'))
{
return false;
}
int ext_index = file_with_ext.LastIndexOf('.');
if (ext_index < 1)
{
return false;
}
string file = file_with_ext.Substring(0, ext_index);
string ext = file_with_ext[(ext_index + 1)..];
if (!KnownMediaTypes.TryGetValue(ext, out MediaType type))
{
return false;
}
if (!ValidateCleanTextInputLine(category))
{
return false;
}
if (!ValidateCleanTextInputLine(file))
{
return false;
}
if (!ValidateCleanTextInputLine(ext.Replace('.', '_')))
{
return false;
}
MetaFile meta = GetMetaFor(category, file);
if (meta == null)
{
return false;
}
if (context.Request.Method == "POST")
{
if (SecurityHelper.CheckHashValidity(meta.DeleteCode, code))
{
string deletedCategoryPath = MetaFilePath + ".deleted/" + category + "/" + file + "/";
ClaimMetaFilePath(deletedCategoryPath, (path, fid) =>
{
meta.DeleteTime = DateTimeOffset.Now;
File.WriteAllText(path, meta.FileOutputString(), EncodingUTF8);
File.Move(RawFilePath + category + "/" + file + "." + ext, deletedCategoryPath + fid + "." + ext);
File.Delete(MetaFilePath + category + "/" + file + ".meta");
});
SetupHttpHeaders(context, 200);
await Write(context, HtmlHelper.BasicHeaderWithTitle("Delete File"));
await Write(context, "<h1>Deleted.</h1>");
await Write(context, HtmlHelper.BasicFooter());
}
else
{
SetupHttpHeaders(context, 200);
await Write(context, HtmlHelper.BasicHeaderWithTitle("Delete File"));
await Write(context, "<h1>Refused. (Invalid code?)</h1>");
await Write(context, HtmlHelper.BasicFooter());
}
}
else
{
SetupHttpHeaders(context, 200);
await Write(context, HtmlHelper.BasicHeaderWithTitle("Delete File"));
await Write(context, HtmlHelper.OneButtonForm("/d/" + category + "/" + file_with_ext, "code", code, "Confirm File Delete"));
await Write(context, HtmlHelper.BasicFooter());
}
return true;
}
public async Task HandlePage_Get_GenerateCode(HttpContext context, string code)
{
SetupHttpHeaders(context, 200);
await Write(context, HtmlHelper.BasicHeaderWithTitle("Generated Code"));
await Write(context, "Code generated:\n<br>\n<br>" + SecurityHelper.HashCurrent(code) + "\n<br>\n");
await Write(context, HtmlHelper.BasicFooter());
}
public async Task HandlePage_404(HttpContext context)
{
SetupHttpHeaders(context, 404);
await Write(context, HtmlHelper.BasicHeaderWithTitle("404 File Not Found"));
await Write(context, "<h1>404</h1>\n<br><h2>File Not Found</h2>\n");
await Write(context, HtmlHelper.BasicFooter());
}
public string RandomHexID(int length = 3)
{
return GeneralHelpers.BytesToHex(SecurityHelper.GetRandomBytes(length)).ToLowerInvariant();
}
public async Task HandlePage_Error(HttpContext context, int code, string error)
{
context.Response.ContentType = "text/plain; charset=utf-8";
context.Response.StatusCode = code;
await Write(context, "fail=" + error);
}
public void ClaimMetaFilePath(string directoryPath, Action<string, string> writeMetaFile)
{
Directory.CreateDirectory(directoryPath);
int current_length = 3;
string fileID = RandomHexID(current_length);
int attempts = 0;
string metaPathPrefix = directoryPath + "/";
while (true)
{
string path = metaPathPrefix + fileID + ".meta";
Object lockObject = PickFileLockFor(fileID);
lock (lockObject)
{
if (!File.Exists(path))
{
writeMetaFile(path, fileID);
break;
}
}
attempts++;
if (attempts > 2)
{
attempts = 0;
current_length++;
if (current_length > 8)
{
throw new Exception("File handling error, or code generator broke? Could not generate valid save ID.");
}
}
fileID = RandomHexID(current_length);
}
}
public string SaveUploadFile(MetaFile metaFile, string category, string extension, MediaType type, byte[] data)
{
data = type.Recrunch(extension, data);
string fileID = null;
ClaimMetaFilePath(MetaFilePath + category, (path, fid) =>
{
fileID = fid;
metaFile.GenerateDeleteCode();
File.WriteAllText(path, metaFile.FileOutputString(), EncodingUTF8);
});
string rawPath = RawFilePath + category + "/" + fileID + "." + extension;
Directory.CreateDirectory(RawFilePath + category);
File.WriteAllBytes(rawPath, data);
return fileID;
}
public async Task HandlePage_Post_Upload(HttpContext context)
{
try
{
if (context.Request.Form.Files.Count == 0)
{
await HandlePage_Error(context, 400, "data");
return;
}
IFormFile file = context.Request.Form.Files[0];
if (file.Length > GlobalMaxFileSize)
{
await HandlePage_Error(context, 400, "file_size");
return;
}
string filename = file.FileName;
int indexDot = filename.LastIndexOf('.');
if (indexDot < 1)
{
await HandlePage_Error(context, 400, "file_type");
return;
}
string extension = filename[(indexDot + 1)..];
if (!ValidateCleanTextInputLine(extension.Replace('.', '_')))
{
await HandlePage_Error(context, 400, "data");
return;
}
if (!context.Request.Form.TryGetValue("uploader_id", out StringValues uploader_id_val)
|| !context.Request.Form.TryGetValue("uploader_verification", out StringValues uploader_verification_val)
|| !context.Request.Form.TryGetValue("file_category", out StringValues file_category_val)
|| !context.Request.Form.TryGetValue("description", out StringValues description_val))
{
await HandlePage_Error(context, 400, "data");
return;
}
string uploaderID = uploader_id_val[0].ToLowerInvariant();
string category = file_category_val[0].ToLowerInvariant();
string description = description_val[0];
if (!ValidateCleanTextInputLine(uploaderID))
{
await HandlePage_Error(context, 400, "data");
return;
}
if (!ValidateCleanTextInputLine(category))
{
await HandlePage_Error(context, 400, "data");
return;
}
User user = GetUser(uploaderID);
if (user == null)
{
await HandlePage_Error(context, 400, "user_verification");
return;
}
if (!SecurityHelper.CheckHashValidity(user.VerificationCode, uploader_verification_val[0]))
{
await HandlePage_Error(context, 400, "user_verification");
return;
}
if (!KnownMediaTypes.TryGetValue(extension, out MediaType type))
{
await HandlePage_Error(context, 400, "file_type");
return;
}
if (!user.CanUploadType(type))
{
await HandlePage_Error(context, 400, "file_type");
return;
}
if (file.Length > user.MaxFileSize)
{
await HandlePage_Error(context, 400, "file_size");
return;
}
if (!user.CategoryVerifier.IsMatch(category))
{
await HandlePage_Error(context, 400, "category");
return;
}
byte[] uploadedData;
using (MemoryStream file_stream = new MemoryStream((int)file.Length))
{
file.CopyTo(file_stream);
uploadedData = file_stream.ToArray();
}
MetaFile metaFile = new MetaFile(uploaderID, description, filename,
context.Request.HttpContext.Connection.RemoteIpAddress
+ " OR " + context.Request.Headers["REMOTE_ADDR"]
+ " OR " + context.Request.Headers["X-Forwarded-For"]);
string fileID = SaveUploadFile(metaFile, category, extension, type, uploadedData);
await Write(context, "success=" + category + "/" + fileID + "." + extension + ";" + metaFile.DeleteCode_Clean);
return;
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
{
throw;
}
await HandlePage_Error(context, 500, "internal");
LogWarning("File upload handler: " + ex.ToString());
return;
}
}
public byte[] GetBytesFor(string rootFile)
{
return File.Exists("./wwwroot/" + rootFile) ? File.ReadAllBytes("./wwwroot/" + rootFile) : null;
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
LoadConfig();
EstablishMediaHandlers();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
byte[] dat_robots = GetBytesFor("robots.txt");
byte[] dat_favicon = GetBytesFor("favicon.ico");
byte[] dat_bootstrap_css = GetBytesFor("css/bootstrap.min.css");
app.Run(async (context) =>
{
if (context.Request.Path.HasValue)
{
if (context.Request.Path.Value.StartsWith("/i/"))
{
if (await HandlePage_Get_FileView(context, context.Request.Path.Value["/i/".Length..]))
{
return;
}
}
else if (context.Request.Path.Value.StartsWith("/d/"))
{
if (context.Request.Method == "POST")
{
if (context.Request.HasFormContentType && context.Request.Form.TryGetValue("code", out StringValues code_val))
{
if (await HandlePage_Any_Delete(context, context.Request.Path.Value["/d/".Length..], code_val[0]))
{
return;
}
}
}
else if (context.Request.Query.TryGetValue("delete_code", out StringValues code))
{
if (await HandlePage_Any_Delete(context, context.Request.Path.Value["/d/".Length..], code))
{
return;
}
}
}
else if (context.Request.Path.Value.StartsWith("/generate_code"))
{
if (context.Request.Query.TryGetValue("pass", out StringValues code))
{
await HandlePage_Get_GenerateCode(context, code[0]);
return;
}
}
else if (context.Request.Path.Value.StartsWith("/upload"))
{
if (context.Request.Method == "POST" && context.Request.HasFormContentType)
{
await HandlePage_Post_Upload(context);
return;
}
}
else if (context.Request.Path.Value.StartsWith("/error"))
{
context.Response.ContentType = "text/html";
await context.Response.Body.WriteAsync(Page_Error);
return;
}
else if (context.Request.Path.Value.StartsWith("/robots.txt"))
{
context.Response.ContentType = "text/plain";
await context.Response.Body.WriteAsync(dat_robots);
return;
}
else if (context.Request.Path.Value.StartsWith("/favicon.ico"))
{
context.Response.ContentType = "image/x-icon";
await context.Response.Body.WriteAsync(dat_favicon);
return;
}
else if (context.Request.Path.Value.StartsWith("/css/bootstrap.min.css"))
{
context.Response.ContentType = "text/css";
await context.Response.Body.WriteAsync(dat_bootstrap_css);
return;
}
}
await HandlePage_404(context);
});
}
}
}