The next generation of the Teknik Services. Written in ASP.NET.
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

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