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

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