예제 #1
0
        public string[] ListDirectory(string url)
        {
            List <string> result = new List <string>();

            url = URLHelpers.AddSlash(url, SlashType.Suffix);

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);

            request.Proxy       = Options.ProxySettings;
            request.Method      = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(Options.Account.Username, Options.Account.Password);
            request.KeepAlive   = false;
            request.Timeout     = 10000;
            request.UsePassive  = !Options.Account.IsActive;

            using (WebResponse response = request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    while (!reader.EndOfStream)
                    {
                        result.Add(reader.ReadLine());
                    }

                    WriteOutput("ListDirectory: " + url);

                    return(result.ToArray());
                }
        }
예제 #2
0
        public static string VerifyPath(string path, string filename = null)
        {
            if (!string.IsNullOrEmpty(path))
            {
                path = path.Trim().Replace('\\', '/').Trim('/');
                path = URLHelpers.AddSlash(path, SlashType.Prefix);

                if (!string.IsNullOrEmpty(filename))
                {
                    path = URLHelpers.CombineURL(path, filename);
                }

                return(path);
            }

            if (!string.IsNullOrEmpty(filename))
            {
                return(filename);
            }

            return("");
        }
예제 #3
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            bool forcePathStyle = Settings.UsePathStyle;

            if (!forcePathStyle && Settings.Bucket.Contains("."))
            {
                forcePathStyle = true;
            }

            string endpoint            = URLHelpers.RemovePrefixes(Settings.Endpoint);
            string host                = forcePathStyle ? endpoint : $"{Settings.Bucket}.{endpoint}";
            string algorithm           = "AWS4-HMAC-SHA256";
            string credentialDate      = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string region              = GetRegion();
            string scope               = URLHelpers.CombineURL(credentialDate, region, "s3", "aws4_request");
            string credential          = URLHelpers.CombineURL(Settings.AccessKeyID, scope);
            string longDate            = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string expiresTotalSeconds = ((long)TimeSpan.FromHours(1).TotalSeconds).ToString();
            string contentType         = Helpers.GetMimeType(fileName);

            NameValueCollection headers = new NameValueCollection();

            headers["content-type"] = contentType;
            headers["host"]         = host;
            if (Settings.SetPublicACL)
            {
                headers["x-amz-acl"] = "public-read";
            }
            headers["x-amz-storage-class"] = Settings.StorageClass.ToString();

            string signedHeaders = GetSignedHeaders(headers);

            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("X-Amz-Algorithm", algorithm);
            args.Add("X-Amz-Credential", credential);
            args.Add("X-Amz-Date", longDate);
            args.Add("X-Amz-Expires", expiresTotalSeconds);
            args.Add("X-Amz-SignedHeaders", signedHeaders);

            string uploadPath = GetUploadPath(fileName);

            string canonicalURI = uploadPath;

            if (forcePathStyle)
            {
                canonicalURI = URLHelpers.CombineURL(Settings.Bucket, canonicalURI);
            }
            canonicalURI = URLHelpers.AddSlash(canonicalURI, SlashType.Prefix);
            canonicalURI = URLHelpers.URLPathEncode(canonicalURI);

            string canonicalQueryString = URLHelpers.CreateQuery(args, true);
            string canonicalHeaders     = CreateCanonicalHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      "UNSIGNED-PAYLOAD";

            string stringToSign = algorithm + "\n" +
                                  longDate + "\n" +
                                  scope + "\n" +
                                  Helpers.BytesToHex(Helpers.ComputeSHA256(canonicalRequest));

            byte[] dateKey              = Helpers.ComputeHMACSHA256(credentialDate, "AWS4" + Settings.SecretAccessKey);
            byte[] dateRegionKey        = Helpers.ComputeHMACSHA256(region, dateKey);
            byte[] dateRegionServiceKey = Helpers.ComputeHMACSHA256("s3", dateRegionKey);
            byte[] signingKey           = Helpers.ComputeHMACSHA256("aws4_request", dateRegionServiceKey);
            string signature            = Helpers.BytesToHex(Helpers.ComputeHMACSHA256(stringToSign, signingKey));

            args.Add("X-Amz-Signature", signature);

            headers.Remove("content-type");
            headers.Remove("host");

            string url = URLHelpers.CombineURL(host, canonicalURI);

            url = URLHelpers.CreateQuery(url, args, true);
            url = URLHelpers.ForcePrefix(url, "https://");

            NameValueCollection responseHeaders = SendRequestGetHeaders(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (responseHeaders == null || responseHeaders.Count == 0)
            {
                Errors.Add("Upload to Amazon S3 failed. Check your access credentials.");
                return(null);
            }

            if (responseHeaders["ETag"] == null)
            {
                Errors.Add("Upload to Amazon S3 failed.");
                return(null);
            }

            return(new UploadResult
            {
                IsSuccess = true,
                URL = GenerateURL(uploadPath)
            });
        }
예제 #4
0
파일: AmazonS3.cs 프로젝트: ralic/ShareX
        public override UploadResult Upload(Stream stream, string fileName)
        {
            bool isPathStyleRequest = Settings.UsePathStyle;

            if (!isPathStyleRequest && Settings.Bucket.Contains("."))
            {
                isPathStyleRequest = true;
            }

            string endpoint       = URLHelpers.RemovePrefixes(Settings.Endpoint);
            string host           = isPathStyleRequest ? endpoint : $"{Settings.Bucket}.{endpoint}";
            string algorithm      = "AWS4-HMAC-SHA256";
            string credentialDate = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string region         = GetRegion();
            string scope          = URLHelpers.CombineURL(credentialDate, region, "s3", "aws4_request");
            string credential     = URLHelpers.CombineURL(Settings.AccessKeyID, scope);
            string timeStamp      = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string contentType    = Helpers.GetMimeType(fileName);
            string uploadPath     = GetUploadPath(fileName);
            string hashedPayload  = "UNSIGNED-PAYLOAD";

            NameValueCollection headers = new NameValueCollection();

            headers["host"]                 = host;
            headers["content-type"]         = contentType;
            headers["x-amz-date"]           = timeStamp;
            headers["x-amz-content-sha256"] = hashedPayload;
            headers["x-amz-storage-class"]  = Settings.StorageClass.ToString();
            if (Settings.SetPublicACL)
            {
                headers["x-amz-acl"] = "public-read";
            }

            string canonicalURI = uploadPath;

            if (isPathStyleRequest)
            {
                canonicalURI = URLHelpers.CombineURL(Settings.Bucket, canonicalURI);
            }
            canonicalURI = URLHelpers.AddSlash(canonicalURI, SlashType.Prefix);
            canonicalURI = URLHelpers.URLPathEncode(canonicalURI);
            string canonicalQueryString = "";
            string canonicalHeaders     = CreateCanonicalHeaders(headers);
            string signedHeaders        = GetSignedHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      hashedPayload;

            string stringToSign = algorithm + "\n" +
                                  timeStamp + "\n" +
                                  scope + "\n" +
                                  Helpers.BytesToHex(Helpers.ComputeSHA256(canonicalRequest));

            byte[] dateKey              = Helpers.ComputeHMACSHA256(credentialDate, "AWS4" + Settings.SecretAccessKey);
            byte[] dateRegionKey        = Helpers.ComputeHMACSHA256(region, dateKey);
            byte[] dateRegionServiceKey = Helpers.ComputeHMACSHA256("s3", dateRegionKey);
            byte[] signingKey           = Helpers.ComputeHMACSHA256("aws4_request", dateRegionServiceKey);

            string signature = Helpers.BytesToHex(Helpers.ComputeHMACSHA256(stringToSign, signingKey));

            headers["Authorization"] = algorithm + " " +
                                       "Credential=" + credential + "," +
                                       "SignedHeaders=" + signedHeaders + "," +
                                       "Signature=" + signature;

            headers.Remove("host");
            headers.Remove("content-type");

            string url = URLHelpers.CombineURL(host, canonicalURI);

            url = URLHelpers.ForcePrefix(url, "https://");

            NameValueCollection responseHeaders = SendRequestGetHeaders(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (responseHeaders == null || responseHeaders.Count == 0 || responseHeaders["ETag"] == null)
            {
                Errors.Add("Upload to Amazon S3 failed.");
                return(null);
            }

            return(new UploadResult
            {
                IsSuccess = true,
                URL = GenerateURL(uploadPath)
            });
        }
예제 #5
0
        public override UploadResult Upload(Stream stream, string fileName)
        {
            bool isPathStyleRequest = Settings.UsePathStyle;

            if (!isPathStyleRequest && Settings.Bucket.Contains("."))
            {
                isPathStyleRequest = true;
            }

            string endpoint       = URLHelpers.RemovePrefixes(Settings.Endpoint);
            string host           = isPathStyleRequest ? endpoint : $"{Settings.Bucket}.{endpoint}";
            string algorithm      = "AWS4-HMAC-SHA256";
            string credentialDate = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string region         = GetRegion();
            string scope          = URLHelpers.CombineURL(credentialDate, region, "s3", "aws4_request");
            string credential     = URLHelpers.CombineURL(Settings.AccessKeyID, scope);
            string timeStamp      = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string contentType    = RequestHelpers.GetMimeType(fileName);
            string hashedPayload;

            if (Settings.SignedPayload)
            {
                hashedPayload = Helpers.BytesToHex(Helpers.ComputeSHA256(stream));
            }
            else
            {
                hashedPayload = "UNSIGNED-PAYLOAD";
            }

            string uploadPath = GetUploadPath(fileName);
            string resultURL  = GenerateURL(uploadPath);

            OnEarlyURLCopyRequested(resultURL);

            NameValueCollection headers = new NameValueCollection
            {
                ["Host"]                 = host,
                ["Content-Length"]       = stream.Length.ToString(),
                ["Content-Type"]         = contentType,
                ["x-amz-date"]           = timeStamp,
                ["x-amz-content-sha256"] = hashedPayload,
                // If you don't specify, S3 Standard is the default storage class. Amazon S3 supports other storage classes.
                // Valid Values: STANDARD | REDUCED_REDUNDANCY | STANDARD_IA | ONEZONE_IA | INTELLIGENT_TIERING | GLACIER | DEEP_ARCHIVE
                // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html
                ["x-amz-storage-class"] = Settings.StorageClass.ToString()
            };

            if (Settings.SetPublicACL)
            {
                // The canned ACL to apply to the object. For more information, see Canned ACL.
                // https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl
                headers["x-amz-acl"] = "public-read";
            }

            string canonicalURI = uploadPath;

            if (isPathStyleRequest)
            {
                canonicalURI = URLHelpers.CombineURL(Settings.Bucket, canonicalURI);
            }
            canonicalURI = URLHelpers.AddSlash(canonicalURI, SlashType.Prefix);
            canonicalURI = URLHelpers.URLEncode(canonicalURI, true);
            string canonicalQueryString = "";
            string canonicalHeaders     = CreateCanonicalHeaders(headers);
            string signedHeaders        = GetSignedHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      hashedPayload;

            string stringToSign = algorithm + "\n" +
                                  timeStamp + "\n" +
                                  scope + "\n" +
                                  Helpers.BytesToHex(Helpers.ComputeSHA256(canonicalRequest));

            byte[] dateKey              = Helpers.ComputeHMACSHA256(credentialDate, "AWS4" + Settings.SecretAccessKey);
            byte[] dateRegionKey        = Helpers.ComputeHMACSHA256(region, dateKey);
            byte[] dateRegionServiceKey = Helpers.ComputeHMACSHA256("s3", dateRegionKey);
            byte[] signingKey           = Helpers.ComputeHMACSHA256("aws4_request", dateRegionServiceKey);

            string signature = Helpers.BytesToHex(Helpers.ComputeHMACSHA256(stringToSign, signingKey));

            headers["Authorization"] = algorithm + " " +
                                       "Credential=" + credential + "," +
                                       "SignedHeaders=" + signedHeaders + "," +
                                       "Signature=" + signature;

            headers.Remove("Host");
            headers.Remove("Content-Type");

            string url = URLHelpers.CombineURL(host, canonicalURI);

            url = URLHelpers.ForcePrefix(url, "https://");

            SendRequest(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (LastResponseInfo != null && LastResponseInfo.IsSuccess)
            {
                return(new UploadResult
                {
                    IsSuccess = true,
                    URL = resultURL
                });
            }

            Errors.Add("Upload to Amazon S3 failed.");
            return(null);
        }
예제 #6
0
        private void lvFTPList_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(string[])))
            {
                Point        point = lvFTPList.PointToClient(new Point(e.X, e.Y));
                ListViewItem lvi   = lvFTPList.GetItemAt(point.X, point.Y);
                if (lvi != null && e.AllowedEffect == DragDropEffects.Move)
                {
                    if (tempSelected != null && tempSelected != lvi)
                    {
                        tempSelected.Selected = false;
                    }

                    FtpListItem file = lvi.Tag as FtpListItem;
                    if (file != null && file.Type == FtpFileSystemObjectType.Directory)
                    {
                        string[] filenames = e.Data.GetData(typeof(string[])) as string[];
                        if (filenames != null)
                        {
                            int renameCount = 0;
                            foreach (string filename in filenames)
                            {
                                if (file.Name != filename)
                                {
                                    string path     = URLHelpers.CombineURL(currentDirectory, filename);
                                    string movePath = string.Empty;
                                    if (file.Type == FtpFileSystemObjectType.Link)
                                    {
                                        if (file.Name == ".")
                                        {
                                            movePath = URLHelpers.AddSlash(filename, SlashType.Prefix, 2);
                                        }
                                        else if (file.Name == "..")
                                        {
                                            movePath = URLHelpers.AddSlash(filename, SlashType.Prefix);
                                        }
                                    }
                                    else
                                    {
                                        movePath = URLHelpers.CombineURL(file.FullName, filename);
                                    }

                                    if (!string.IsNullOrEmpty(movePath))
                                    {
                                        Client.Rename(path, movePath);
                                        renameCount++;
                                    }
                                }
                            }

                            if (renameCount > 0)
                            {
                                RefreshDirectory();
                            }
                        }
                    }
                }

                tempSelected = null;
            }
            else if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
                if (files != null)
                {
                    Client.UploadFiles(files, currentDirectory);
                    RefreshDirectory();
                }
            }
        }
예제 #7
0
파일: AmazonS3.cs 프로젝트: Gigabait/ShareX
        public override UploadResult Upload(Stream stream, string fileName)
        {
            string hostname            = URLHelpers.RemovePrefixes(Settings.RegionHostname);
            string host                = $"{Settings.Bucket}.{hostname}";
            string algorithm           = "AWS4-HMAC-SHA256";
            string credentialDate      = DateTime.UtcNow.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
            string scope               = $"{credentialDate}/{Settings.RegionIdentifier}/s3/aws4_request";
            string credential          = $"{Settings.AccessKeyID}/{scope}";
            string longDate            = DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ", CultureInfo.InvariantCulture);
            string expiresTotalSeconds = ((long)TimeSpan.FromHours(1).TotalSeconds).ToString();
            string contentType         = Helpers.GetMimeType(fileName);

            NameValueCollection headers = new NameValueCollection();

            headers["content-type"]        = contentType;
            headers["host"]                = host;
            headers["x-amz-acl"]           = "public-read";
            headers["x-amz-storage-class"] = Settings.UseReducedRedundancyStorage ? "REDUCED_REDUNDANCY" : "STANDARD";

            string signedHeaders = GetSignedHeaders(headers);

            Dictionary <string, string> args = new Dictionary <string, string>();

            args.Add("X-Amz-Algorithm", algorithm);
            args.Add("X-Amz-Credential", credential);
            args.Add("X-Amz-Date", longDate);
            args.Add("X-Amz-Expires", expiresTotalSeconds);
            args.Add("X-Amz-SignedHeaders", signedHeaders);

            string uploadPath   = GetUploadPath(fileName);
            string canonicalURI = URLHelpers.AddSlash(uploadPath, SlashType.Prefix);

            canonicalURI = URLHelpers.URLPathEncode(canonicalURI);

            string canonicalQueryString = CreateQueryString(args);
            string canonicalHeaders     = CreateCanonicalHeaders(headers);

            string canonicalRequest = "PUT" + "\n" +
                                      canonicalURI + "\n" +
                                      canonicalQueryString + "\n" +
                                      canonicalHeaders + "\n" +
                                      signedHeaders + "\n" +
                                      "UNSIGNED-PAYLOAD";

            string stringToSign = algorithm + "\n" +
                                  longDate + "\n" +
                                  scope + "\n" +
                                  BytesToHex(ComputeHash(canonicalRequest));

            byte[] secretKey            = Encoding.UTF8.GetBytes("AWS4" + Settings.SecretAccessKey);
            byte[] dateKey              = ComputeHMAC(Encoding.UTF8.GetBytes(credentialDate), secretKey);
            byte[] dateRegionKey        = ComputeHMAC(Encoding.UTF8.GetBytes(Settings.RegionIdentifier), dateKey);
            byte[] dateRegionServiceKey = ComputeHMAC(Encoding.UTF8.GetBytes("s3"), dateRegionKey);
            byte[] signingKey           = ComputeHMAC(Encoding.UTF8.GetBytes("aws4_request"), dateRegionServiceKey);
            string signature            = BytesToHex(ComputeHMAC(Encoding.UTF8.GetBytes(stringToSign), signingKey));

            args.Add("X-Amz-Signature", signature);

            headers.Remove("content-type");
            headers.Remove("host");

            string url = URLHelpers.CombineURL(host, canonicalURI) + "?" + CreateQueryString(args);

            url = URLHelpers.ForcePrefix(url, "https://");

            NameValueCollection responseHeaders = SendRequestGetHeaders(HttpMethod.PUT, url, stream, contentType, null, headers);

            if (responseHeaders == null || responseHeaders.Count == 0)
            {
                Errors.Add("Upload to Amazon S3 failed. Check your access credentials.");
                return(null);
            }

            if (responseHeaders["ETag"] == null)
            {
                Errors.Add("Upload to Amazon S3 failed.");
                return(null);
            }

            return(new UploadResult
            {
                IsSuccess = true,
                URL = GenerateURL(fileName)
            });
        }