The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UploadController.cs 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using nClam;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using Teknik.Areas.Upload.ViewModels;
  7. using Teknik.Areas.Users.Utility;
  8. using Teknik.Controllers;
  9. using Teknik.Filters;
  10. using Teknik.Utilities;
  11. using Teknik.Models;
  12. using Teknik.Attributes;
  13. using System.Text;
  14. using Teknik.Utilities.Cryptography;
  15. using Teknik.Data;
  16. using Teknik.Configuration;
  17. using Microsoft.Extensions.Logging;
  18. using Microsoft.AspNetCore.Mvc;
  19. using Microsoft.AspNetCore.Authorization;
  20. using System.Threading.Tasks;
  21. using Microsoft.EntityFrameworkCore;
  22. using Microsoft.AspNetCore.Http;
  23. using Teknik.Logging;
  24. using Teknik.Areas.Users.Models;
  25. namespace Teknik.Areas.Upload.Controllers
  26. {
  27. [Authorize]
  28. [Area("Upload")]
  29. public class UploadController : DefaultController
  30. {
  31. public UploadController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
  32. [HttpGet]
  33. [AllowAnonymous]
  34. public IActionResult Index()
  35. {
  36. ViewBag.Title = "Upload Files";
  37. UploadViewModel model = new UploadViewModel();
  38. model.CurrentSub = Subdomain;
  39. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  40. if (user != null)
  41. {
  42. model.Encrypt = user.UploadSettings.Encrypt;
  43. model.ExpirationLength = user.UploadSettings.ExpirationLength;
  44. model.ExpirationUnit = user.UploadSettings.ExpirationUnit;
  45. model.Vaults = user.Vaults.ToList();
  46. }
  47. else
  48. {
  49. model.Encrypt = false;
  50. }
  51. return View(model);
  52. }
  53. [HttpPost]
  54. [AllowAnonymous]
  55. [DisableRequestSizeLimit]
  56. public async Task<IActionResult> Upload([FromForm] UploadFileViewModel uploadFile)
  57. {
  58. try
  59. {
  60. if (_config.UploadConfig.UploadEnabled)
  61. {
  62. long maxUploadSize = _config.UploadConfig.MaxUploadSize;
  63. if (User.Identity.IsAuthenticated)
  64. {
  65. maxUploadSize = _config.UploadConfig.MaxUploadSizeBasic;
  66. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  67. if (userInfo.AccountType == AccountType.Premium)
  68. {
  69. maxUploadSize = _config.UploadConfig.MaxUploadSizePremium;
  70. }
  71. }
  72. else
  73. {
  74. // Non-logged in users are defaulted to 1 day expiration
  75. uploadFile.options.ExpirationUnit = ExpirationUnit.Days;
  76. uploadFile.options.ExpirationLength = 1;
  77. }
  78. if (uploadFile.file.Length <= maxUploadSize)
  79. {
  80. // convert file to bytes
  81. long contentLength = uploadFile.file.Length;
  82. // Scan the file to detect a virus
  83. if (_config.UploadConfig.VirusScanEnable)
  84. {
  85. using (Stream fs = uploadFile.file.OpenReadStream())
  86. {
  87. ClamClient clam = new ClamClient(_config.UploadConfig.ClamServer, _config.UploadConfig.ClamPort);
  88. clam.MaxStreamSize = maxUploadSize;
  89. ClamScanResult scanResult = await clam.SendAndScanFileAsync(fs);
  90. switch (scanResult.Result)
  91. {
  92. case ClamScanResults.Clean:
  93. break;
  94. case ClamScanResults.VirusDetected:
  95. return Json(new { error = new { message = string.Format("Virus Detected: {0}. As per our <a href=\"{1}\">Terms of Service</a>, Viruses are not permited.", scanResult.InfectedFiles.First().VirusName, Url.SubRouteUrl("tos", "TOS.Index")) } });
  96. case ClamScanResults.Error:
  97. return Json(new { error = new { message = string.Format("Error scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  98. case ClamScanResults.Unknown:
  99. return Json(new { error = new { message = string.Format("Unknown result while scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  100. }
  101. }
  102. }
  103. // Check content type restrictions (Only for encrypting server side
  104. if (!uploadFile.options.Encrypt)
  105. {
  106. if (_config.UploadConfig.RestrictedContentTypes.Contains(uploadFile.fileType) || _config.UploadConfig.RestrictedExtensions.Contains(uploadFile.fileExt))
  107. {
  108. return Json(new { error = new { message = "File Type Not Allowed" } });
  109. }
  110. }
  111. using (Stream fs = uploadFile.file.OpenReadStream())
  112. {
  113. Models.Upload upload = UploadHelper.SaveFile(_dbContext,
  114. _config,
  115. fs,
  116. uploadFile.fileType,
  117. contentLength,
  118. !uploadFile.options.Encrypt,
  119. uploadFile.options.ExpirationUnit,
  120. uploadFile.options.ExpirationLength,
  121. uploadFile.fileExt,
  122. uploadFile.iv, null,
  123. uploadFile.keySize,
  124. uploadFile.blockSize);
  125. if (upload != null)
  126. {
  127. if (User.Identity.IsAuthenticated)
  128. {
  129. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  130. if (user != null)
  131. {
  132. upload.UserId = user.UserId;
  133. _dbContext.Entry(upload).State = EntityState.Modified;
  134. _dbContext.SaveChanges();
  135. }
  136. }
  137. return Json(new { result = new
  138. {
  139. name = upload.Url,
  140. url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }),
  141. contentType = upload.ContentType,
  142. contentLength = StringHelper.GetBytesReadable(upload.ContentLength),
  143. deleteUrl = Url.SubRouteUrl("u", "Upload.DeleteByKey", new { file = upload.Url, key = upload.DeleteKey }),
  144. expirationUnit = uploadFile.options.ExpirationUnit.ToString(),
  145. expirationLength = uploadFile.options.ExpirationLength
  146. } });
  147. }
  148. }
  149. return Json(new { error = new { message = "Unable to upload file" } });
  150. }
  151. else
  152. {
  153. return Json(new { error = new { message = "File Too Large" } });
  154. }
  155. }
  156. return Json(new { error = new { message = "Uploads are disabled" } });
  157. }
  158. catch (Exception ex)
  159. {
  160. return Json(new { error = new { message = "Exception while uploading file: " + ex.GetFullMessage(true) } });
  161. }
  162. }
  163. [HttpGet]
  164. [AllowAnonymous]
  165. [ResponseCache(Duration = 31536000, Location = ResponseCacheLocation.Any)]
  166. public async Task<IActionResult> Download(string file)
  167. {
  168. if (_config.UploadConfig.DownloadEnabled)
  169. {
  170. ViewBag.Title = "Download " + file;
  171. string fileName = string.Empty;
  172. string url = string.Empty;
  173. string key = string.Empty;
  174. string iv = string.Empty;
  175. string contentType = string.Empty;
  176. long contentLength = 0;
  177. bool premiumAccount = false;
  178. DateTime dateUploaded = new DateTime();
  179. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  180. if (upload != null)
  181. {
  182. // Check Expiration
  183. if (UploadHelper.CheckExpiration(upload))
  184. {
  185. _dbContext.Uploads.Remove(upload);
  186. _dbContext.SaveChanges();
  187. return new StatusCodeResult(StatusCodes.Status404NotFound);
  188. }
  189. upload.Downloads += 1;
  190. _dbContext.Entry(upload).State = EntityState.Modified;
  191. _dbContext.SaveChanges();
  192. fileName = upload.FileName;
  193. url = upload.Url;
  194. key = upload.Key;
  195. iv = upload.IV;
  196. contentType = upload.ContentType;
  197. contentLength = upload.ContentLength;
  198. dateUploaded = upload.DateUploaded;
  199. if (User.Identity.IsAuthenticated)
  200. {
  201. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  202. premiumAccount = userInfo.AccountType == AccountType.Premium;
  203. }
  204. if (!premiumAccount && upload.User != null)
  205. {
  206. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, upload.User.Username);
  207. premiumAccount = userInfo.AccountType == AccountType.Premium;
  208. }
  209. }
  210. else
  211. {
  212. return new StatusCodeResult(StatusCodes.Status404NotFound);
  213. }
  214. // We don't have the key, so we need to decrypt it client side
  215. if (string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  216. {
  217. DownloadViewModel model = new DownloadViewModel();
  218. model.CurrentSub = Subdomain;
  219. model.FileName = file;
  220. model.ContentType = contentType;
  221. model.ContentLength = contentLength;
  222. model.IV = iv;
  223. model.Decrypt = true;
  224. return View(model);
  225. }
  226. else if (!premiumAccount && _config.UploadConfig.MaxDownloadSize < contentLength)
  227. {
  228. // We want to force them to the dl page due to them being over the max download size for embedded content
  229. DownloadViewModel model = new DownloadViewModel();
  230. model.CurrentSub = Subdomain;
  231. model.FileName = file;
  232. model.ContentType = contentType;
  233. model.ContentLength = contentLength;
  234. model.Decrypt = false;
  235. return View(model);
  236. }
  237. else // We have the key, so that means server side decryption
  238. {
  239. // Check for the cache
  240. bool isCached = false;
  241. string modifiedSince = Request.Headers["If-Modified-Since"];
  242. if (!string.IsNullOrEmpty(modifiedSince))
  243. {
  244. DateTime modTime = new DateTime();
  245. bool parsed = DateTime.TryParse(modifiedSince, out modTime);
  246. if (parsed)
  247. {
  248. if ((modTime - dateUploaded).TotalSeconds <= 1)
  249. {
  250. isCached = true;
  251. }
  252. }
  253. }
  254. if (isCached)
  255. {
  256. return new StatusCodeResult(StatusCodes.Status304NotModified);
  257. }
  258. else
  259. {
  260. string subDir = fileName[0].ToString();
  261. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, fileName);
  262. long startByte = 0;
  263. long endByte = contentLength - 1;
  264. long length = contentLength;
  265. if (System.IO.File.Exists(filePath))
  266. {
  267. #region Range Calculation
  268. // Are they downloading it by range?
  269. bool byRange = !string.IsNullOrEmpty(Request.Headers["Range"]); // We do not support ranges
  270. // check to see if we need to pass a specified range
  271. if (byRange)
  272. {
  273. long anotherStart = startByte;
  274. long anotherEnd = endByte;
  275. string[] arr_split = Request.Headers["Range"].ToString().Split(new char[] { '=' });
  276. string range = arr_split[1];
  277. // Make sure the client hasn't sent us a multibyte range
  278. if (range.IndexOf(",") > -1)
  279. {
  280. // (?) Shoud this be issued here, or should the first
  281. // range be used? Or should the header be ignored and
  282. // we output the whole content?
  283. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  284. return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
  285. }
  286. // If the range starts with an '-' we start from the beginning
  287. // If not, we forward the file pointer
  288. // And make sure to get the end byte if spesified
  289. if (range.StartsWith("-"))
  290. {
  291. // The n-number of the last bytes is requested
  292. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  293. }
  294. else
  295. {
  296. arr_split = range.Split(new char[] { '-' });
  297. anotherStart = Convert.ToInt64(arr_split[0]);
  298. long temp = 0;
  299. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
  300. }
  301. /* Check the range and make sure it's treated according to the specs.
  302. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  303. */
  304. // End bytes can not be larger than $end.
  305. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  306. // Validate the requested range and return an error if it's not correct.
  307. if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
  308. {
  309. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  310. return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
  311. }
  312. startByte = anotherStart;
  313. endByte = anotherEnd;
  314. length = endByte - startByte + 1; // Calculate new content length
  315. // Ranges are response of 206
  316. Response.StatusCode = 206;
  317. }
  318. #endregion
  319. // Set Last Modified
  320. Response.GetTypedHeaders().LastModified = dateUploaded;
  321. // We accept ranges
  322. Response.Headers.Add("Accept-Ranges", "0-" + contentLength);
  323. // Notify the client the byte range we'll be outputting
  324. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  325. // Notify the client the content length we'll be outputting
  326. Response.Headers.Add("Content-Length", length.ToString());
  327. // Set the content type of this response
  328. Response.Headers.Add("Content-Type", contentType);
  329. // Create content disposition
  330. var cd = new System.Net.Mime.ContentDisposition
  331. {
  332. FileName = url,
  333. Inline = true
  334. };
  335. Response.Headers.Add("Content-Disposition", cd.ToString());
  336. // Read in the file
  337. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  338. // Reset file stream to starting position (or start of range)
  339. fs.Seek(startByte, SeekOrigin.Begin);
  340. try
  341. {
  342. // If the IV is set, and Key is set, then decrypt it while sending
  343. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  344. {
  345. byte[] keyBytes = Encoding.UTF8.GetBytes(key);
  346. byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
  347. return new BufferedFileStreamResult(contentType, async (response) => await ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)length, _config.UploadConfig.ChunkSize), false);
  348. }
  349. else // Otherwise just send it
  350. {
  351. // Send the file
  352. return new BufferedFileStreamResult(contentType, async (response) => await ResponseHelper.StreamToOutput(response, true, fs, (int)length, _config.UploadConfig.ChunkSize), false);
  353. }
  354. }
  355. catch (Exception ex)
  356. {
  357. _logger.LogWarning(ex, "Error in Download: {url}", new { url });
  358. }
  359. }
  360. }
  361. return new StatusCodeResult(StatusCodes.Status404NotFound);
  362. }
  363. }
  364. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  365. }
  366. [HttpPost]
  367. [AllowAnonymous]
  368. public IActionResult DownloadData(string file, bool decrypt)
  369. {
  370. if (_config.UploadConfig.DownloadEnabled)
  371. {
  372. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  373. if (upload != null)
  374. {
  375. // Check Expiration
  376. if (UploadHelper.CheckExpiration(upload))
  377. {
  378. _dbContext.Uploads.Remove(upload);
  379. _dbContext.SaveChanges();
  380. return Json(new { error = new { message = "File Does Not Exist" } });
  381. }
  382. string subDir = upload.FileName[0].ToString();
  383. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  384. if (System.IO.File.Exists(filePath))
  385. {
  386. // Notify the client the content length we'll be outputting
  387. Response.Headers.Add("Content-Length", upload.ContentLength.ToString());
  388. // Create content disposition
  389. var cd = new System.Net.Mime.ContentDisposition
  390. {
  391. FileName = upload.Url,
  392. Inline = true
  393. };
  394. // Set the content type of this response
  395. Response.Headers.Add("Content-Type", upload.ContentType);
  396. Response.Headers.Add("Content-Disposition", cd.ToString());
  397. // Read in the file
  398. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  399. // If the IV is set, and Key is set, then decrypt it while sending
  400. if (decrypt && !string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  401. {
  402. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  403. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  404. return new BufferedFileStreamResult(upload.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)upload.ContentLength, _config.UploadConfig.ChunkSize), false);
  405. }
  406. else // Otherwise just send it
  407. {
  408. // Send the file
  409. return new BufferedFileStreamResult(upload.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, _config.UploadConfig.ChunkSize), false);
  410. }
  411. }
  412. }
  413. return Json(new { error = new { message = "File Does Not Exist" } });
  414. }
  415. return Json(new { error = new { message = "Downloads are disabled" } });
  416. }
  417. [HttpGet]
  418. [AllowAnonymous]
  419. public IActionResult DeleteByKey(string file, string key)
  420. {
  421. ViewBag.Title = "File Delete | " + file ;
  422. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  423. if (upload != null)
  424. {
  425. DeleteViewModel model = new DeleteViewModel();
  426. model.File = file;
  427. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  428. {
  429. string filePath = upload.FileName;
  430. // Delete from the DB
  431. _dbContext.Uploads.Remove(upload);
  432. _dbContext.SaveChanges();
  433. // Delete the File
  434. if (System.IO.File.Exists(filePath))
  435. {
  436. System.IO.File.Delete(filePath);
  437. }
  438. model.Deleted = true;
  439. }
  440. else
  441. {
  442. model.Deleted = false;
  443. }
  444. return View(model);
  445. }
  446. return new StatusCodeResult(StatusCodes.Status404NotFound);
  447. }
  448. [HttpPost]
  449. public IActionResult GenerateDeleteKey(string file)
  450. {
  451. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  452. if (upload != null)
  453. {
  454. if (upload.User.Username == User.Identity.Name)
  455. {
  456. string delKey = StringHelper.RandomString(_config.UploadConfig.DeleteKeyLength);
  457. upload.DeleteKey = delKey;
  458. _dbContext.Entry(upload).State = EntityState.Modified;
  459. _dbContext.SaveChanges();
  460. return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.DeleteByKey", new { file = file, key = delKey }) } });
  461. }
  462. return Json(new { error = new { message = "You do not own this upload" } });
  463. }
  464. return Json(new { error = new { message = "Invalid URL" } });
  465. }
  466. [HttpPost]
  467. public IActionResult Delete(string id)
  468. {
  469. Models.Upload foundUpload = _dbContext.Uploads.Where(u => u.Url == id).FirstOrDefault();
  470. if (foundUpload != null)
  471. {
  472. if (foundUpload.User.Username == User.Identity.Name)
  473. {
  474. string filePath = foundUpload.FileName;
  475. // Delete from the DB
  476. _dbContext.Uploads.Remove(foundUpload);
  477. _dbContext.SaveChanges();
  478. // Delete the File
  479. if (System.IO.File.Exists(filePath))
  480. {
  481. System.IO.File.Delete(filePath);
  482. }
  483. return Json(new { result = true });
  484. }
  485. return Json(new { error = new { message = "You do not have permission to edit this Paste" } });
  486. }
  487. return Json(new { error = new { message = "This Paste does not exist" } });
  488. }
  489. }
  490. }