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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using nClam;
  2. using Piwik.Tracker;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data.Entity;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Web;
  11. using System.Web.Mvc;
  12. using Teknik.Areas.Error.ViewModels;
  13. using Teknik.Areas.Upload.Models;
  14. using Teknik.Areas.Upload.ViewModels;
  15. using Teknik.Areas.Users.Utility;
  16. using Teknik.Controllers;
  17. using Teknik.Filters;
  18. using Teknik.Utilities;
  19. using Teknik.Models;
  20. using Teknik.Attributes;
  21. using System.Text;
  22. using Org.BouncyCastle.Crypto;
  23. namespace Teknik.Areas.Upload.Controllers
  24. {
  25. [TeknikAuthorize]
  26. public class UploadController : DefaultController
  27. {
  28. private TeknikEntities db = new TeknikEntities();
  29. // GET: Upload/Upload
  30. [HttpGet]
  31. [TrackPageView]
  32. [AllowAnonymous]
  33. public ActionResult Index()
  34. {
  35. ViewBag.Title = "Teknik Upload - End to End Encryption";
  36. UploadViewModel model = new UploadViewModel();
  37. model.CurrentSub = Subdomain;
  38. Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
  39. if (user != null)
  40. {
  41. model.Encrypt = user.UploadSettings.Encrypt;
  42. }
  43. else
  44. {
  45. model.Encrypt = false;
  46. }
  47. return View(model);
  48. }
  49. [HttpPost]
  50. [AllowAnonymous]
  51. public ActionResult Upload(string fileType, string fileExt, string iv, int keySize, int blockSize, bool encrypt, HttpPostedFileWrapper data)
  52. {
  53. try
  54. {
  55. if (Config.UploadConfig.UploadEnabled)
  56. {
  57. if (data.ContentLength <= Config.UploadConfig.MaxUploadSize)
  58. {
  59. // convert file to bytes
  60. int contentLength = data.ContentLength;
  61. // Scan the file to detect a virus
  62. if (Config.UploadConfig.VirusScanEnable)
  63. {
  64. ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
  65. clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
  66. ClamScanResult scanResult = clam.SendAndScanFile(data.InputStream);
  67. switch (scanResult.Result)
  68. {
  69. case ClamScanResults.Clean:
  70. break;
  71. case ClamScanResults.VirusDetected:
  72. 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")) } });
  73. case ClamScanResults.Error:
  74. return Json(new { error = new { message = string.Format("Error scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  75. case ClamScanResults.Unknown:
  76. return Json(new { error = new { message = string.Format("Unknown result while scanning the file upload for viruses. {0}", scanResult.RawResult) } });
  77. }
  78. }
  79. Models.Upload upload = Uploader.SaveFile(db, Config, data.InputStream, fileType, contentLength, encrypt, fileExt, iv, null, keySize, blockSize);
  80. if (upload != null)
  81. {
  82. if (User.Identity.IsAuthenticated)
  83. {
  84. Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
  85. if (user != null)
  86. {
  87. upload.UserId = user.UserId;
  88. db.Entry(upload).State = EntityState.Modified;
  89. db.SaveChanges();
  90. }
  91. }
  92. return Json(new { result = new { name = upload.Url, url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }), contentType = upload.ContentType, contentLength = StringHelper.GetBytesReadable(upload.ContentLength) } }, "text/plain");
  93. }
  94. return Json(new { error = new { message = "Unable to upload file" } });
  95. }
  96. else
  97. {
  98. return Json(new { error = new { message = "File Too Large" } });
  99. }
  100. }
  101. return Json(new { error = new { message = "Uploads are disabled" } });
  102. }
  103. catch (Exception ex)
  104. {
  105. return Json(new { error = new { message = "Exception while uploading file: " + ex.GetFullMessage(true) } });
  106. }
  107. }
  108. // User did not supply key
  109. [HttpGet]
  110. [TrackDownload]
  111. [AllowAnonymous]
  112. public ActionResult Download(string file)
  113. {
  114. if (Config.UploadConfig.DownloadEnabled)
  115. {
  116. ViewBag.Title = "Teknik Download - " + file;
  117. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  118. if (upload != null)
  119. {
  120. upload.Downloads += 1;
  121. db.Entry(upload).State = EntityState.Modified;
  122. db.SaveChanges();
  123. // We don't have the key, so we need to decrypt it client side
  124. if (string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  125. {
  126. DownloadViewModel model = new DownloadViewModel();
  127. model.FileName = file;
  128. model.ContentType = upload.ContentType;
  129. model.ContentLength = upload.ContentLength;
  130. model.IV = upload.IV;
  131. return View(model);
  132. }
  133. else // We have the key, so that means server side decryption
  134. {
  135. // Are they downloading it by range?
  136. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]);
  137. // Check to see if they have a cache
  138. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]);
  139. if (isCached)
  140. {
  141. // The file is cached, let's just 304 this
  142. Response.StatusCode = 304;
  143. Response.StatusDescription = "Not Modified";
  144. Response.AddHeader("Content-Length", "0");
  145. return Content(string.Empty);
  146. }
  147. else
  148. {
  149. string subDir = upload.FileName[0].ToString();
  150. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  151. long startByte = 0;
  152. long endByte = upload.ContentLength - 1;
  153. long length = upload.ContentLength;
  154. if (System.IO.File.Exists(filePath))
  155. {
  156. // Read in the file
  157. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  158. // We accept ranges
  159. Response.AddHeader("Accept-Ranges", "0-" + length);
  160. // check to see if we need to pass a specified range
  161. if (byRange)
  162. {
  163. long anotherStart = startByte;
  164. long anotherEnd = endByte;
  165. string[] arr_split = Request.ServerVariables["HTTP_RANGE"].Split(new char[] { '=' });
  166. string range = arr_split[1];
  167. // Make sure the client hasn't sent us a multibyte range
  168. if (range.IndexOf(",") > -1)
  169. {
  170. // (?) Shoud this be issued here, or should the first
  171. // range be used? Or should the header be ignored and
  172. // we output the whole content?
  173. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  174. throw new HttpException(416, "Requested Range Not Satisfiable");
  175. }
  176. // If the range starts with an '-' we start from the beginning
  177. // If not, we forward the file pointer
  178. // And make sure to get the end byte if spesified
  179. if (range.StartsWith("-"))
  180. {
  181. // The n-number of the last bytes is requested
  182. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  183. }
  184. else
  185. {
  186. arr_split = range.Split(new char[] { '-' });
  187. anotherStart = Convert.ToInt64(arr_split[0]);
  188. long temp = 0;
  189. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : upload.ContentLength;
  190. }
  191. /* Check the range and make sure it's treated according to the specs.
  192. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  193. */
  194. // End bytes can not be larger than $end.
  195. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  196. // Validate the requested range and return an error if it's not correct.
  197. if (anotherStart > anotherEnd || anotherStart > upload.ContentLength - 1 || anotherEnd >= upload.ContentLength)
  198. {
  199. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  200. throw new HttpException(416, "Requested Range Not Satisfiable");
  201. }
  202. startByte = anotherStart;
  203. endByte = anotherEnd;
  204. length = endByte - startByte + 1; // Calculate new content length
  205. // Ranges are response of 206
  206. Response.StatusCode = 206;
  207. }
  208. // Add cache parameters
  209. Response.Cache.SetCacheability(HttpCacheability.Public);
  210. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  211. Response.Cache.SetLastModified(upload.DateUploaded);
  212. // Notify the client the byte range we'll be outputting
  213. Response.AddHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + upload.ContentLength);
  214. Response.AddHeader("Content-Length", length.ToString());
  215. // Create content disposition
  216. var cd = new System.Net.Mime.ContentDisposition
  217. {
  218. FileName = upload.Url,
  219. Inline = true
  220. };
  221. Response.AddHeader("Content-Disposition", cd.ToString());
  222. string contentType = upload.ContentType;
  223. // We need to prevent html (make cleaner later)
  224. if (contentType == "text/html")
  225. {
  226. contentType = "text/plain";
  227. }
  228. // Reset file stream to starting position (or start of range)
  229. fs.Seek(startByte, SeekOrigin.Begin);
  230. // If the IV is set, and Key is set, then decrypt it while sending
  231. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  232. {
  233. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  234. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  235. return new FileGenerateResult(upload.Url,
  236. contentType,
  237. (response) => ResponseHelper.DecryptStreamToOutput(response, fs, (int)length, keyBytes, ivBytes, "CTR", "NoPadding", Config.UploadConfig.ChunkSize),
  238. false);
  239. }
  240. else // Otherwise just send it
  241. {
  242. // Don't buffer the response
  243. Response.Buffer = false;
  244. // Send the file
  245. return new FileGenerateResult(upload.Url,
  246. contentType,
  247. (response) => ResponseHelper.StreamToOutput(response, fs, (int)length, Config.UploadConfig.ChunkSize),
  248. false);
  249. }
  250. }
  251. }
  252. }
  253. }
  254. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  255. }
  256. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  257. }
  258. [HttpPost]
  259. [AllowAnonymous]
  260. public FileResult DownloadData(string file)
  261. {
  262. if (Config.UploadConfig.DownloadEnabled)
  263. {
  264. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  265. if (upload != null)
  266. {
  267. string subDir = upload.FileName[0].ToString();
  268. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  269. if (System.IO.File.Exists(filePath))
  270. {
  271. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  272. return File(fileStream, System.Net.Mime.MediaTypeNames.Application.Octet, file);
  273. }
  274. }
  275. Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  276. return null;
  277. }
  278. Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  279. return null;
  280. }
  281. [HttpGet]
  282. [AllowAnonymous]
  283. public ActionResult Delete(string file, string key)
  284. {
  285. ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
  286. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  287. if (upload != null)
  288. {
  289. DeleteViewModel model = new DeleteViewModel();
  290. model.File = file;
  291. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  292. {
  293. string filePath = upload.FileName;
  294. // Delete from the DB
  295. db.Uploads.Remove(upload);
  296. db.SaveChanges();
  297. // Delete the File
  298. if (System.IO.File.Exists(filePath))
  299. {
  300. System.IO.File.Delete(filePath);
  301. }
  302. model.Deleted = true;
  303. }
  304. else
  305. {
  306. model.Deleted = false;
  307. }
  308. return View(model);
  309. }
  310. return RedirectToRoute("Error.Http404");
  311. }
  312. [HttpPost]
  313. [AllowAnonymous]
  314. public ActionResult GenerateDeleteKey(string file)
  315. {
  316. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  317. if (upload != null)
  318. {
  319. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  320. upload.DeleteKey = delKey;
  321. db.Entry(upload).State = EntityState.Modified;
  322. db.SaveChanges();
  323. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Delete", new { file = file, key = delKey }) });
  324. }
  325. return Json(new { error = "Invalid URL" });
  326. }
  327. [HttpPost]
  328. [AllowAnonymous]
  329. public ActionResult SaveFileKey(string file, string key)
  330. {
  331. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  332. if (upload != null)
  333. {
  334. upload.Key = key;
  335. db.Entry(upload).State = EntityState.Modified;
  336. db.SaveChanges();
  337. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Download", new { file = file }) });
  338. }
  339. return Json(new { error = "Invalid URL" });
  340. }
  341. [HttpPost]
  342. [AllowAnonymous]
  343. public ActionResult RemoveFileKey(string file, string key)
  344. {
  345. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  346. if (upload != null)
  347. {
  348. if (upload.Key == key)
  349. {
  350. upload.Key = null;
  351. db.Entry(upload).State = EntityState.Modified;
  352. db.SaveChanges();
  353. return Json(new { result = Url.SubRouteUrl("upload", "Upload.Download", new { file = file }) });
  354. }
  355. return Json(new { error = "Non-Matching Key" });
  356. }
  357. return Json(new { error = "Invalid URL" });
  358. }
  359. }
  360. }