DocSpace-client/common/ASC.Data.Storage/StorageHandler.cs

185 lines
7.6 KiB
C#
Raw Normal View History

2019-06-04 14:43:20 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using System;
2020-02-17 08:58:14 +00:00
using System.Collections.Generic;
2019-06-04 14:43:20 +00:00
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
2020-02-17 08:58:14 +00:00
using System.Threading.Tasks;
using System.Web;
2020-01-21 12:44:05 +00:00
2020-02-17 08:58:14 +00:00
using ASC.Common;
using ASC.Common.Web;
2019-06-04 14:43:20 +00:00
using ASC.Core;
2020-02-17 08:58:14 +00:00
using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
2019-06-04 14:43:20 +00:00
namespace ASC.Data.Storage.DiscStorage
{
public class StorageHandler
{
private readonly string _path;
private readonly string _module;
private readonly string _domain;
private readonly bool _checkAuth;
2019-09-09 12:56:33 +00:00
public StorageHandler(IServiceProvider serviceProvider, string path, string module, string domain, bool checkAuth = true)
2020-02-17 08:58:14 +00:00
{
ServiceProvider = serviceProvider;
2019-06-04 14:43:20 +00:00
_path = path;
_module = module;
_domain = domain;
_checkAuth = checkAuth;
2020-02-17 08:58:14 +00:00
}
public IServiceProvider ServiceProvider { get; }
2019-06-04 14:43:20 +00:00
public async Task Invoke(HttpContext context)
2020-02-17 08:58:14 +00:00
{
using var scope = ServiceProvider.CreateScope();
var tenantManager = scope.ServiceProvider.GetService<TenantManager>();
var securityContext = scope.ServiceProvider.GetService<SecurityContext>();
var storageFactory = scope.ServiceProvider.GetService<StorageFactory>();
var emailValidationKeyProvider = scope.ServiceProvider.GetService<EmailValidationKeyProvider>();
2019-09-09 12:56:33 +00:00
2019-09-17 12:42:32 +00:00
if (_checkAuth && !securityContext.IsAuthenticated)
2019-07-09 10:29:53 +00:00
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
2019-06-04 14:43:20 +00:00
2019-09-17 12:42:32 +00:00
var storage = storageFactory.GetStorage(tenantManager.GetCurrentTenant().TenantId.ToString(CultureInfo.InvariantCulture), _module);
2019-06-04 14:43:20 +00:00
var path = Path.Combine(_path, GetRouteValue("pathInfo").Replace('/', Path.DirectorySeparatorChar));
var header = context.Request.Query[Constants.QUERY_HEADER].FirstOrDefault() ?? "";
var auth = context.Request.Query[Constants.QUERY_AUTH].FirstOrDefault() ?? "";
var storageExpire = storage.GetExpire(_domain);
if (storageExpire != TimeSpan.Zero && storageExpire != TimeSpan.MinValue && storageExpire != TimeSpan.MaxValue || !string.IsNullOrEmpty(auth))
{
var expire = context.Request.Query[Constants.QUERY_EXPIRE];
if (string.IsNullOrEmpty(expire)) expire = storageExpire.TotalMinutes.ToString(CultureInfo.InvariantCulture);
2019-09-17 12:42:32 +00:00
var validateResult = emailValidationKeyProvider.ValidateEmailKey(path + "." + header + "." + expire, auth ?? "", TimeSpan.FromMinutes(Convert.ToDouble(expire)));
2019-06-04 14:43:20 +00:00
if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
}
if (!storage.IsFile(_domain, path))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
var headers = header.Length > 0 ? header.Split('&').Select(HttpUtility.UrlDecode) : new string[] { };
2019-08-15 12:04:42 +00:00
const int bigSize = 5 * 1024 * 1024;
2019-06-04 14:43:20 +00:00
if (storage.IsSupportInternalUri && bigSize < storage.GetFileSize(_domain, path))
{
var uri = storage.GetInternalUri(_domain, path, TimeSpan.FromMinutes(15), headers);
2020-02-17 08:58:14 +00:00
2019-06-04 14:43:20 +00:00
//TODO
//context.Response.Cache.SetAllowResponseInBrowserHistory(false);
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Redirect(uri.ToString());
return;
}
string encoding = null;
if (storage is DiscDataStore && storage.IsFile(_domain, path + ".gz"))
{
path += ".gz";
encoding = "gzip";
}
using (var stream = storage.GetReadStream(_domain, path))
{
2020-05-06 08:41:27 +00:00
await stream.CopyToAsync(context.Response.Body);
2020-02-17 08:58:14 +00:00
}
var headersToCopy = new List<string> { "Content-Disposition", "Cache-Control", "Content-Encoding", "Content-Language", "Content-Type", "Expires" };
foreach (var h in headers)
{
var toCopy = headersToCopy.Find(x => h.StartsWith(x));
if (string.IsNullOrEmpty(toCopy)) continue;
context.Response.Headers[toCopy] = h.Substring(toCopy.Length + 1);
2019-06-04 14:43:20 +00:00
}
context.Response.ContentType = MimeMapping.GetMimeMapping(path);
if (encoding != null)
2020-02-17 08:58:14 +00:00
context.Response.Headers["Content-Encoding"] = encoding;
string GetRouteValue(string name)
{
return (context.GetRouteValue(name) ?? "").ToString();
2019-06-04 14:43:20 +00:00
}
}
2020-02-17 08:58:14 +00:00
}
public static class StorageHandlerExtensions
{
2019-06-04 14:43:20 +00:00
public static IEndpointRouteBuilder RegisterStorageHandler(this IEndpointRouteBuilder builder, string module, string domain, bool publicRoute = false)
2020-02-17 08:58:14 +00:00
{
var pathUtils = builder.ServiceProvider.GetService<PathUtils>();
2019-09-21 16:39:17 +00:00
var virtPath = pathUtils.ResolveVirtualPath(module, domain);
2020-02-17 08:58:14 +00:00
virtPath = virtPath.TrimStart('/');
var handler = new StorageHandler(builder.ServiceProvider, string.Empty, module, domain, !publicRoute);
var url = virtPath + "{*pathInfo}";
if (!builder.DataSources.Any(r => r.Endpoints.Any(e => e.DisplayName == url)))
{
builder.Map(url, handler.Invoke);
var newUrl = url.Replace("{0}", "{t1}/{t2}/{t3}");
if (newUrl != url)
{
builder.Map(url, handler.Invoke);
}
}
2019-06-04 14:43:20 +00:00
return builder;
2020-02-17 08:58:14 +00:00
}
public static DIHelper AddStorageHandlerService(this DIHelper services)
{
return services
.AddTenantManagerService()
.AddSecurityContextService()
.AddStorageFactoryService()
.AddEmailValidationKeyProviderService();
}
2019-06-04 14:43:20 +00:00
}
}