The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
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 20KB

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