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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. using (TeknikEntities db = new TeknikEntities())
  124. {
  125. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  126. if (upload != null)
  127. {
  128. upload.Downloads += 1;
  129. db.Entry(upload).State = EntityState.Modified;
  130. db.SaveChanges();
  131. // We don't have the key, so we need to decrypt it client side
  132. if (string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  133. {
  134. DownloadViewModel model = new DownloadViewModel();
  135. model.FileName = file;
  136. model.ContentType = upload.ContentType;
  137. model.ContentLength = upload.ContentLength;
  138. model.IV = upload.IV;
  139. return View(model);
  140. }
  141. else // We have the key, so that means server side decryption
  142. {
  143. // Are they downloading it by range?
  144. bool byRange = !string.IsNullOrEmpty(Request.ServerVariables["HTTP_RANGE"]); // We do not support ranges
  145. // Check to see if they have a cache
  146. bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]);
  147. if (isCached)
  148. {
  149. // The file is cached, let's just 304 this
  150. Response.StatusCode = 304;
  151. Response.StatusDescription = "Not Modified";
  152. Response.AddHeader("Content-Length", "0");
  153. return Content(string.Empty);
  154. }
  155. else
  156. {
  157. string subDir = upload.FileName[0].ToString();
  158. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  159. if (System.IO.File.Exists(filePath))
  160. {
  161. // Add cache parameters
  162. Response.Cache.SetCacheability(HttpCacheability.Public);
  163. Response.Cache.SetMaxAge(new TimeSpan(365, 0, 0, 0));
  164. Response.Cache.SetLastModified(upload.DateUploaded);
  165. // Notify the client the content length we'll be outputting
  166. Response.AddHeader("Content-Length", upload.ContentLength.ToString());
  167. // Create content disposition
  168. var cd = new System.Net.Mime.ContentDisposition
  169. {
  170. FileName = upload.Url,
  171. Inline = true
  172. };
  173. Response.AddHeader("Content-Disposition", cd.ToString());
  174. string contentType = upload.ContentType;
  175. // We need to prevent html (make cleaner later)
  176. if (contentType == "text/html")
  177. {
  178. contentType = "text/plain";
  179. }
  180. // Read in the file
  181. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  182. try
  183. {
  184. // If the IV is set, and Key is set, then decrypt it while sending
  185. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  186. {
  187. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  188. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  189. return new FileGenerateResult(upload.Url,
  190. contentType,
  191. (response) => ResponseHelper.StreamToOutput(response, true, new AESCryptoStream(fs, false, keyBytes, ivBytes, "CTR", "NoPadding"), (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
  192. false);
  193. }
  194. else // Otherwise just send it
  195. {
  196. // Don't buffer the response
  197. Response.Buffer = false;
  198. // Send the file
  199. return new FileGenerateResult(upload.Url,
  200. contentType,
  201. (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, Config.UploadConfig.ChunkSize),
  202. false);
  203. }
  204. }
  205. catch (Exception ex)
  206. {
  207. Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Download", ex);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  214. }
  215. }
  216. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  217. }
  218. [HttpPost]
  219. [AllowAnonymous]
  220. public FileResult DownloadData(string file)
  221. {
  222. if (Config.UploadConfig.DownloadEnabled)
  223. {
  224. using (TeknikEntities db = new TeknikEntities())
  225. {
  226. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  227. if (upload != null)
  228. {
  229. string subDir = upload.FileName[0].ToString();
  230. string filePath = Path.Combine(Config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  231. if (System.IO.File.Exists(filePath))
  232. {
  233. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  234. return File(fileStream, System.Net.Mime.MediaTypeNames.Application.Octet, file);
  235. }
  236. }
  237. Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  238. return null;
  239. }
  240. }
  241. Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  242. return null;
  243. }
  244. [HttpGet]
  245. [AllowAnonymous]
  246. public ActionResult Delete(string file, string key)
  247. {
  248. using (TeknikEntities db = new TeknikEntities())
  249. {
  250. ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
  251. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  252. if (upload != null)
  253. {
  254. DeleteViewModel model = new DeleteViewModel();
  255. model.File = file;
  256. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  257. {
  258. string filePath = upload.FileName;
  259. // Delete from the DB
  260. db.Uploads.Remove(upload);
  261. db.SaveChanges();
  262. // Delete the File
  263. if (System.IO.File.Exists(filePath))
  264. {
  265. System.IO.File.Delete(filePath);
  266. }
  267. model.Deleted = true;
  268. }
  269. else
  270. {
  271. model.Deleted = false;
  272. }
  273. return View(model);
  274. }
  275. return RedirectToRoute("Error.Http404");
  276. }
  277. }
  278. [HttpPost]
  279. public ActionResult GenerateDeleteKey(string file)
  280. {
  281. using (TeknikEntities db = new TeknikEntities())
  282. {
  283. Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
  284. if (upload != null)
  285. {
  286. if (upload.User.Username == User.Identity.Name)
  287. {
  288. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  289. upload.DeleteKey = delKey;
  290. db.Entry(upload).State = EntityState.Modified;
  291. db.SaveChanges();
  292. return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.Delete", new { file = file, key = delKey }) } });
  293. }
  294. return Json(new { error = new { message = "You do not own this upload" } });
  295. }
  296. return Json(new { error = new { message = "Invalid URL" } });
  297. }
  298. }
  299. }
  300. }