Merge pull request #1168 from krishnasrinivas/mc-upload-presign
mc share upload
This commit is contained in:
@@ -36,7 +36,8 @@ type Client interface {
|
||||
SetBucketACL(acl string) *probe.Error
|
||||
|
||||
// Object operations
|
||||
Share(expires time.Duration) (string, *probe.Error)
|
||||
ShareDownload(expires time.Duration) (string, *probe.Error)
|
||||
ShareUpload(bool, time.Duration, string) (map[string]string, *probe.Error)
|
||||
GetObject(offset, length int64) (body io.ReadCloser, size int64, err *probe.Error)
|
||||
PutObject(size int64, data io.Reader) *probe.Error
|
||||
|
||||
|
||||
+6
-2
@@ -145,8 +145,12 @@ func (f *fsClient) get() (io.ReadCloser, int64, *probe.Error) {
|
||||
return body, content.Size, nil
|
||||
}
|
||||
|
||||
func (f *fsClient) Share(expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(client.APINotImplemented{API: "Share", APIType: "filesystem"})
|
||||
func (f *fsClient) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
return "", probe.NewError(client.APINotImplemented{API: "ShareDownload", APIType: "filesystem"})
|
||||
}
|
||||
|
||||
func (f *fsClient) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
return nil, probe.NewError(client.APINotImplemented{API: "ShareUpload", APIType: "filesystem"})
|
||||
}
|
||||
|
||||
// GetObject download an full or part object from bucket
|
||||
|
||||
@@ -77,7 +77,7 @@ func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe
|
||||
}
|
||||
|
||||
// Share - get a usable get object url to share
|
||||
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if err != nil {
|
||||
@@ -86,6 +86,10 @@ func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
func (c *s3Client) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
return nil, probe.NewError(client.APINotImplemented{API: "Share", APIType: "filesystem"})
|
||||
}
|
||||
|
||||
// PutObject - put object
|
||||
func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error {
|
||||
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
|
||||
|
||||
+18
-1
@@ -77,7 +77,7 @@ func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe
|
||||
}
|
||||
|
||||
// Share - get a usable get object url to share
|
||||
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if err != nil {
|
||||
@@ -86,6 +86,23 @@ func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
func (c *s3Client) ShareUpload(recursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
p := minio.NewPostPolicy()
|
||||
p.SetExpires(time.Now().UTC().Add(expires))
|
||||
if len(contentType) > 0 {
|
||||
p.SetContentType(contentType)
|
||||
}
|
||||
p.SetBucket(bucket)
|
||||
if recursive {
|
||||
p.SetKeyStartsWith(object)
|
||||
} else {
|
||||
p.SetKey(object)
|
||||
}
|
||||
m, err := c.api.PresignedPostPolicy(p)
|
||||
return m, probe.NewError(err)
|
||||
}
|
||||
|
||||
// PutObject - put object
|
||||
func (c *s3Client) PutObject(size int64, data io.Reader) *probe.Error {
|
||||
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareDownload = cli.Command{
|
||||
Name: "download",
|
||||
Usage: "Share documents via URL.",
|
||||
Action: mainShareDownload,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}} download TARGET [DURATION]
|
||||
|
||||
DURATION = NN[h|m|s] [DEFAULT=168h]
|
||||
|
||||
EXAMPLES:
|
||||
1. Generate URL for sharing, with a default expiry of 7 days.
|
||||
$ mc share {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Generate URL for sharing, with an expiry of 10 minutes.
|
||||
$ mc share {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz 10m
|
||||
|
||||
3. Generate list of URLs for sharing a folder recursively, with expiration of 5 days each.
|
||||
$ mc share {{.Name}} https://s3.amazonaws.com/backup... 120h
|
||||
|
||||
4. Generate URL with space characters for sharing, with an expiry of 5 seconds.
|
||||
$ mc share {{.Name}} s3/miniocloud/nothing-like-anything 5s
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
func checkShareDownloadSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() || args.First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code
|
||||
}
|
||||
if len(args) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "download", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainShareDownload(ctx *cli.Context) {
|
||||
shareDataDirSetup()
|
||||
checkShareDownloadSyntax(ctx)
|
||||
args := ctx.Args()
|
||||
config := mustGetMcConfig()
|
||||
url := args.Get(0)
|
||||
// default expiration is 7days
|
||||
expires := time.Duration(604800) * time.Second
|
||||
if len(args) == 2 {
|
||||
var err error
|
||||
expires, err = time.ParseDuration(args.Get(1))
|
||||
fatalIf(probe.NewError(err), "Unable to parse time argument.")
|
||||
}
|
||||
|
||||
targetURL := getAliasURL(url, config.Aliases)
|
||||
|
||||
setSharePalette(ctx.GlobalString("colors"))
|
||||
|
||||
// if recursive strip off the "..."
|
||||
err := doShareDownloadURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
|
||||
return
|
||||
}
|
||||
|
||||
// doShareURL share files from target
|
||||
func doShareDownloadURL(targetURL string, recursive bool, expires time.Duration) *probe.Error {
|
||||
shareDate := time.Now().UTC()
|
||||
sURLs, err := loadSharedURLsV3()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
var clnt client.Client
|
||||
clnt, err = target2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if expires.Seconds() < 1 {
|
||||
return probe.NewError(errors.New("Too low expires, expiration cannot be less than 1 second."))
|
||||
}
|
||||
if expires.Seconds() > 604800 {
|
||||
return probe.NewError(errors.New("Too high expires, expiration cannot be larger than 7 days."))
|
||||
}
|
||||
for contentCh := range clnt.List(recursive) {
|
||||
if contentCh.Err != nil {
|
||||
return contentCh.Err.Trace()
|
||||
}
|
||||
var newClnt client.Client
|
||||
newClnt, err = url2Client(getNewTargetURL(clnt.URL(), contentCh.Content.Name))
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
var sharedURL string
|
||||
sharedURL, err = newClnt.ShareDownload(expires)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
shareMessage := ShareMessage{
|
||||
Expiry: expires,
|
||||
DownloadURL: sharedURL,
|
||||
Key: newClnt.URL().String(),
|
||||
}
|
||||
shareMessageV3 := ShareMessageV3{
|
||||
Expiry: expires,
|
||||
DownloadURL: sharedURL,
|
||||
Key: newClnt.URL().String(),
|
||||
}
|
||||
sURLs.URLs = append(sURLs.URLs, struct {
|
||||
Date time.Time
|
||||
Message ShareMessageV3
|
||||
}{
|
||||
Date: shareDate,
|
||||
Message: shareMessageV3,
|
||||
})
|
||||
Prints("%s\n", shareMessage)
|
||||
}
|
||||
saveSharedURLsV3(sURLs)
|
||||
return nil
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareList = cli.Command{
|
||||
Name: "list",
|
||||
Usage: "List the shared URLs",
|
||||
Action: mainShareList,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}}
|
||||
|
||||
EXAMPLES:
|
||||
$ mc share {{.Name}}
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
func mainShareList(ctx *cli.Context) {
|
||||
shareDataDirSetup()
|
||||
setSharePalette(ctx.GlobalString("colors"))
|
||||
err := doShareList()
|
||||
fatalIf(err.Trace(), "Unable to list shared URLs.")
|
||||
}
|
||||
|
||||
// doShareList list shared url's
|
||||
func doShareList() *probe.Error {
|
||||
sURLs, err := loadSharedURLsV3()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
saveList := newSharedURLsV3()
|
||||
for _, data := range sURLs.URLs {
|
||||
if time.Since(data.Date) > data.Message.Expiry {
|
||||
continue
|
||||
}
|
||||
saveList.URLs = append(saveList.URLs, data)
|
||||
expiry := data.Message.Expiry - time.Since(data.Date)
|
||||
if !globalJSONFlag {
|
||||
var kind string
|
||||
if len(data.Message.DownloadURL) > 0 {
|
||||
kind = "Download"
|
||||
} else {
|
||||
kind = "Upload"
|
||||
}
|
||||
msg := console.Colorize("Share", "Name: ")
|
||||
msg += console.Colorize("URL", data.Message.Key+" ("+kind+")\n")
|
||||
msg += console.Colorize("Share", "Expiry: ")
|
||||
msg += console.Colorize("Expires", timeDurationToHumanizedTime(expiry))
|
||||
msg += "\n"
|
||||
console.Println(msg)
|
||||
continue
|
||||
}
|
||||
var shareMessageBytes []byte
|
||||
var err error
|
||||
s := data.Message
|
||||
if len(s.DownloadURL) > 0 {
|
||||
shareMessageBytes, err = json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
DownloadURL string `json:"downloadUrl"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(s.Expiry),
|
||||
DownloadURL: s.DownloadURL,
|
||||
Key: s.Key,
|
||||
})
|
||||
} else {
|
||||
shareMessageBytes, err = json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
UploadInfo map[string]string `json:"uploadInfo"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(s.Expiry),
|
||||
UploadInfo: s.UploadInfo,
|
||||
Key: s.Key,
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
console.Println(string(shareMessageBytes))
|
||||
}
|
||||
if err := saveSharedURLsV3(saveList); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+68
-237
@@ -19,13 +19,9 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
@@ -37,56 +33,91 @@ var shareCmd = cli.Command{
|
||||
Name: "share",
|
||||
Usage: "Share documents via URL.",
|
||||
Action: mainShare,
|
||||
Subcommands: []cli.Command{
|
||||
shareDownload,
|
||||
shareUpload,
|
||||
shareList,
|
||||
},
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc {{.Name}} - {{.Usage}}
|
||||
{{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc {{.Name}} TARGET [DURATION]
|
||||
{{.Name}} command [arguments...]
|
||||
|
||||
DURATION = NN[h|m|s] [DEFAULT=168h]
|
||||
|
||||
EXAMPLES:
|
||||
1. Generate URL for sharing, with a default expiry of 7 days.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Generate URL for sharing, with an expiry of 10 minutes.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz 10m
|
||||
|
||||
3. Generate list of URLs for sharing a folder recursively, with expiration of 5 days each.
|
||||
$ mc {{.Name}} https://s3.amazonaws.com/backup... 120h
|
||||
|
||||
4. Generate URL with space characters for sharing, with an expiry of 5 seconds.
|
||||
$ mc {{.Name}} s3/miniocloud/nothing-like-anything 5s
|
||||
|
||||
5. List all the shared URLs which have not expired yet.
|
||||
$ mc {{.Name}} list
|
||||
COMMANDS:
|
||||
{{range .Commands}}{{ .Name }}{{ "\t" }}{{.Usage}}
|
||||
{{end}}
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
// ShareMessage is container for share command on success and failure messages
|
||||
type ShareMessage struct {
|
||||
// ShareMessageV1 ...
|
||||
type ShareMessageV1 struct {
|
||||
Expiry time.Duration `json:"expiry"`
|
||||
URL string `json:"url"`
|
||||
Key string `json:"keyName"`
|
||||
}
|
||||
|
||||
// ShareMessageV2 ...
|
||||
type ShareMessageV2 ShareMessageV1
|
||||
|
||||
// ShareMessageV3 ...
|
||||
type ShareMessageV3 struct {
|
||||
Expiry time.Duration `json:"expiry"`
|
||||
DownloadURL string `json:"downloadUrl,omitempty"`
|
||||
UploadInfo map[string]string `json:"uploadInfo,omitempty"`
|
||||
Key string `json:"keyName"`
|
||||
}
|
||||
|
||||
// ShareMessage ...
|
||||
type ShareMessage ShareMessageV3
|
||||
|
||||
// String - regular colorized message
|
||||
func (s ShareMessage) String() string {
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), s.URL, s.Key))
|
||||
if len(s.DownloadURL) > 0 {
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n DownloadURL: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), s.DownloadURL, s.Key))
|
||||
}
|
||||
var key string
|
||||
URL := client.NewURL(s.Key)
|
||||
postURL := URL.Scheme + URL.SchemeSeparator + URL.Host + string(URL.Separator) + s.UploadInfo["bucket"] + " "
|
||||
curlCommand := "curl " + postURL
|
||||
for k, v := range s.UploadInfo {
|
||||
if k == "key" {
|
||||
key = v
|
||||
continue
|
||||
}
|
||||
curlCommand = curlCommand + fmt.Sprintf("-F %s=%s ", k, v)
|
||||
}
|
||||
curlCommand = curlCommand + fmt.Sprintf("-F key=%s ", key) + "-F file=@<LOCALFILEPATH> "
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n curl-command: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), curlCommand, s.Key))
|
||||
}
|
||||
|
||||
// JSON json message for share command
|
||||
func (s ShareMessage) JSON() string {
|
||||
shareMessageBytes, err := json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
URL string `json:"url"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(s.Expiry),
|
||||
URL: s.URL,
|
||||
Key: s.Key,
|
||||
})
|
||||
var shareMessageBytes []byte
|
||||
var err error
|
||||
if len(s.DownloadURL) > 0 {
|
||||
shareMessageBytes, err = json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
DownloadURL string `json:"downloadUrl"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(s.Expiry),
|
||||
DownloadURL: s.DownloadURL,
|
||||
Key: s.Key,
|
||||
})
|
||||
} else {
|
||||
shareMessageBytes, err = json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
UploadInfo map[string]string `json:"uploadInfo"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(s.Expiry),
|
||||
UploadInfo: s.UploadInfo,
|
||||
Key: s.Key,
|
||||
})
|
||||
}
|
||||
|
||||
fatalIf(probe.NewError(err), "Failed to marshal into JSON.")
|
||||
|
||||
// json encoding escapes ampersand into its unicode character which is not usable directly for share
|
||||
@@ -95,209 +126,9 @@ func (s ShareMessage) JSON() string {
|
||||
return string(shareMessageBytes)
|
||||
}
|
||||
|
||||
// migrateSharedURLs migrate to newest version sequentially
|
||||
func migrateSharedURLs() {
|
||||
migrateSharedURLsV1ToV2()
|
||||
}
|
||||
|
||||
func checkShareSyntax(ctx *cli.Context) {
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" || len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args()) > 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
if ctx.Args().Get(0) == "list" {
|
||||
if len(ctx.Args()) >= 2 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "share", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(ctx.Args().Get(0)) == "" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unable to validate empty argument.")
|
||||
}
|
||||
}
|
||||
|
||||
func setSharePalette(style string) {
|
||||
console.SetCustomPalette(map[string]*color.Color{
|
||||
"Share": color.New(color.FgGreen, color.Bold),
|
||||
"Expires": color.New(color.FgRed, color.Bold),
|
||||
"URL": color.New(color.FgCyan, color.Bold),
|
||||
})
|
||||
if style == "light" {
|
||||
console.SetCustomPalette(map[string]*color.Color{
|
||||
"Share": color.New(color.FgWhite, color.Bold),
|
||||
"Expires": color.New(color.FgWhite, color.Bold),
|
||||
"URL": color.New(color.FgWhite, color.Bold),
|
||||
})
|
||||
return
|
||||
}
|
||||
/// Add more styles here
|
||||
|
||||
if style == "nocolor" {
|
||||
// All coloring options exhausted, setting nocolor safely
|
||||
console.SetNoColor()
|
||||
}
|
||||
}
|
||||
|
||||
// mainShare - is a handler for mc share command
|
||||
func mainShare(ctx *cli.Context) {
|
||||
checkShareSyntax(ctx)
|
||||
|
||||
if !isSharedURLsDataDirExists() {
|
||||
shareDir, err := getSharedURLsDataDir()
|
||||
fatalIf(err.Trace(), "Unable to get shared URL data directory")
|
||||
|
||||
fatalIf(createSharedURLsDataDir().Trace(), "Unable to create shared URL data directory ‘"+shareDir+"’.")
|
||||
if !ctx.Args().Present() || ctx.Args().First() == "help" {
|
||||
cli.ShowAppHelp(ctx)
|
||||
}
|
||||
if !isSharedURLsDataFileExists() {
|
||||
shareFile, err := getSharedURLsDataFile()
|
||||
fatalIf(err.Trace(), "Unable to get shared URL data file")
|
||||
|
||||
fatalIf(createSharedURLsDataFile().Trace(), "Unable to create shared URL data file ‘"+shareFile+"’.")
|
||||
}
|
||||
|
||||
setSharePalette(ctx.GlobalString("colors"))
|
||||
|
||||
args := ctx.Args()
|
||||
config := mustGetMcConfig()
|
||||
|
||||
// if its only list, return quickly
|
||||
if args.Get(0) == "list" {
|
||||
err := doShareList()
|
||||
fatalIf(err.Trace(), "Unable to list shared URLs.")
|
||||
return
|
||||
}
|
||||
|
||||
/// get first and last arguments
|
||||
url := args.Get(0) // url to be shared
|
||||
// default expiration is 7days
|
||||
expires := time.Duration(604800) * time.Second
|
||||
if len(args) == 2 {
|
||||
var err error
|
||||
expires, err = time.ParseDuration(args.Get(1))
|
||||
fatalIf(probe.NewError(err), "Unable to parse time argument.")
|
||||
}
|
||||
|
||||
targetURL := getAliasURL(url, config.Aliases)
|
||||
|
||||
// if recursive strip off the "..."
|
||||
err := doShareURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires)
|
||||
fatalIf(err.Trace(targetURL), "Unable to generate URL for sharing.")
|
||||
}
|
||||
|
||||
// doShareList list shared url's
|
||||
func doShareList() *probe.Error {
|
||||
sURLs, err := loadSharedURLsV2()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
for i, data := range sURLs.URLs {
|
||||
if time.Since(data.Date) > data.Message.Expiry {
|
||||
sURLs.URLs = append(sURLs.URLs[:i], sURLs.URLs[i+1:]...)
|
||||
continue
|
||||
}
|
||||
expiry := data.Message.Expiry - time.Since(data.Date)
|
||||
if !globalJSONFlag {
|
||||
msg := console.Colorize("Share", "Name: ")
|
||||
msg += console.Colorize("URL", data.Message.Key+"\n")
|
||||
msg += console.Colorize("Share", "Expiry: ")
|
||||
msg += console.Colorize("Expires", timeDurationToHumanizedTime(expiry))
|
||||
msg += "\n"
|
||||
console.Println(msg)
|
||||
continue
|
||||
}
|
||||
shareListBytes, err := json.Marshal(struct {
|
||||
Expiry humanizedTime `json:"expiry"`
|
||||
URL string `json:"url"`
|
||||
Key string `json:"keyName"`
|
||||
}{
|
||||
Expiry: timeDurationToHumanizedTime(expiry),
|
||||
URL: data.Message.URL,
|
||||
Key: data.Message.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
console.Println(string(shareListBytes))
|
||||
}
|
||||
if err := saveSharedURLsV2(sURLs); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// doShareURL share files from target
|
||||
func doShareURL(targetURL string, recursive bool, expires time.Duration) *probe.Error {
|
||||
shareDate := time.Now().UTC()
|
||||
sURLs, err := loadSharedURLsV2()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
var clnt client.Client
|
||||
clnt, err = target2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
if expires.Seconds() < 1 {
|
||||
return probe.NewError(errors.New("Too low expires, expiration cannot be less than 1 second."))
|
||||
}
|
||||
if expires.Seconds() > 604800 {
|
||||
return probe.NewError(errors.New("Too high expires, expiration cannot be larger than 7 days."))
|
||||
}
|
||||
for contentCh := range clnt.List(recursive) {
|
||||
if contentCh.Err != nil {
|
||||
return contentCh.Err.Trace()
|
||||
}
|
||||
var newClnt client.Client
|
||||
newClnt, err = url2Client(getNewTargetURL(clnt.URL(), contentCh.Content.Name))
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
var sharedURL string
|
||||
sharedURL, err = newClnt.Share(expires)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
shareMessage := ShareMessage{
|
||||
Expiry: expires,
|
||||
URL: sharedURL,
|
||||
Key: newClnt.URL().String(),
|
||||
}
|
||||
sURLs.URLs = append(sURLs.URLs, struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
}{
|
||||
Date: shareDate,
|
||||
Message: shareMessage,
|
||||
})
|
||||
Prints("%s\n", shareMessage)
|
||||
}
|
||||
saveSharedURLsV2(sURLs)
|
||||
return nil
|
||||
}
|
||||
|
||||
func getNewTargetURL(targetParser *client.URL, name string) string {
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host)
|
||||
if match {
|
||||
targetParser.Path = string(targetParser.Separator) + name
|
||||
} else {
|
||||
targetParser.Path = string(targetParser.Separator) + path2Bucket(targetParser) + string(targetParser.Separator) + name
|
||||
}
|
||||
return targetParser.String()
|
||||
}
|
||||
|
||||
// this code is necessary since, share only operates on cloud storage URLs not filesystem
|
||||
func path2Bucket(u *client.URL) (bucketName string) {
|
||||
pathSplits := strings.SplitN(u.Path, "?", 2)
|
||||
splits := strings.SplitN(pathSplits[0], string(u.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
}
|
||||
return bucketName
|
||||
}
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/minio/cli"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Share documents via URL.
|
||||
var shareUpload = cli.Command{
|
||||
Name: "upload",
|
||||
Usage: "Share link that can be used to upload files to private bucket",
|
||||
Action: mainShareUpload,
|
||||
CustomHelpTemplate: `NAME:
|
||||
mc share {{.Name}} - {{.Usage}}
|
||||
|
||||
USAGE:
|
||||
mc share {{.Name}} TARGET [DURATION] [Content-Type]
|
||||
|
||||
DURATION = NN[h|m|s] [DEFAULT=168h]
|
||||
|
||||
EXAMPLES:
|
||||
1. Generate Curl upload command, with a default expiry of 7 days.
|
||||
$ mc share {{.Name}} https://s3.amazonaws.com/backup/2006-Mar-1/backup.tar.gz
|
||||
|
||||
2. Generate Curl upload command to upload files to a folder, with expiry of 120 hours
|
||||
$ mc share {{.Name}} https://s3.amazonaws.com/backup/2007-Mar-2/... 120h
|
||||
|
||||
3. Generate Curl upload command to upload with expiry of 2 hours with content-type image/png
|
||||
$ mc share {{.Name}} https://s3.amazonaws.com/backup/2007-Mar-2/... 2h image/png
|
||||
|
||||
`,
|
||||
}
|
||||
|
||||
func checkShareUploadSyntax(ctx *cli.Context) {
|
||||
args := ctx.Args()
|
||||
if !args.Present() || args.First() == "help" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code
|
||||
}
|
||||
if len(args) > 3 {
|
||||
cli.ShowCommandHelpAndExit(ctx, "upload", 1) // last argument is exit code
|
||||
}
|
||||
}
|
||||
|
||||
func mainShareUpload(ctx *cli.Context) {
|
||||
var expires time.Duration
|
||||
var err error
|
||||
shareDataDirSetup()
|
||||
checkShareUploadSyntax(ctx)
|
||||
args := ctx.Args()
|
||||
config := mustGetMcConfig()
|
||||
url := args.Get(0)
|
||||
if len(args.Get(1)) == 0 {
|
||||
expires = time.Duration(604800) * time.Second
|
||||
} else {
|
||||
expires, err = time.ParseDuration(args.Get(1))
|
||||
if err != nil {
|
||||
fatalIf(probe.NewError(err), "Unable to parse time argument.")
|
||||
}
|
||||
}
|
||||
contentType := args.Get(2)
|
||||
targetURL := getAliasURL(url, config.Aliases)
|
||||
|
||||
setSharePalette(ctx.GlobalString("colors"))
|
||||
|
||||
e := doShareUploadURL(stripRecursiveURL(targetURL), isURLRecursive(targetURL), expires, contentType)
|
||||
fatalIf(e.Trace(targetURL), "Unable to generate URL for sharing.")
|
||||
}
|
||||
|
||||
// doShareURL share files from target
|
||||
func doShareUploadURL(targetURL string, recursive bool, expires time.Duration, contentType string) *probe.Error {
|
||||
shareDate := time.Now().UTC()
|
||||
sURLs, err := loadSharedURLsV3()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
|
||||
clnt, err := url2Client(targetURL)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
m, err := clnt.ShareUpload(recursive, expires, contentType)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
Key := targetURL
|
||||
if recursive {
|
||||
Key = Key + recursiveSeparator
|
||||
m["key"] = "<KEY>"
|
||||
}
|
||||
shareMessage := ShareMessage{
|
||||
Expiry: expires,
|
||||
UploadInfo: m,
|
||||
Key: Key,
|
||||
}
|
||||
shareMessageV3 := ShareMessageV3{
|
||||
Expiry: expires,
|
||||
UploadInfo: m,
|
||||
Key: Key,
|
||||
}
|
||||
sURLs.URLs = append(sURLs.URLs, struct {
|
||||
Date time.Time
|
||||
Message ShareMessageV3
|
||||
}{
|
||||
Date: shareDate,
|
||||
Message: shareMessageV3,
|
||||
})
|
||||
Prints("%s\n", shareMessage)
|
||||
saveSharedURLsV3(sURLs)
|
||||
return nil
|
||||
}
|
||||
+2
-2
@@ -28,7 +28,7 @@ type sharedURLsV1 struct {
|
||||
Version string
|
||||
URLs map[string]struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
Message ShareMessageV1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ func newSharedURLsV1() *sharedURLsV1 {
|
||||
Version: "1.0.0",
|
||||
URLs: make(map[string]struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
Message ShareMessageV1
|
||||
}),
|
||||
}
|
||||
return s
|
||||
|
||||
+2
-2
@@ -28,7 +28,7 @@ type sharedURLsV2 struct {
|
||||
Version string
|
||||
URLs []struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
Message ShareMessageV2
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ func saveSharedURLsV2(s *sharedURLsV2) *probe.Error {
|
||||
func newSharedURLsV2() *sharedURLsV2 {
|
||||
var urls []struct {
|
||||
Date time.Time
|
||||
Message ShareMessage
|
||||
Message ShareMessageV2
|
||||
}
|
||||
s := &sharedURLsV2{
|
||||
Version: "1.1.0",
|
||||
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Minio Client (C) 2014, 2015 Minio, Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
type sharedURLsV3 struct {
|
||||
Version string
|
||||
URLs []struct {
|
||||
Date time.Time
|
||||
Message ShareMessageV3
|
||||
}
|
||||
}
|
||||
|
||||
func loadSharedURLsV3() (*sharedURLsV3, *probe.Error) {
|
||||
sharedURLsDataFile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
if _, err := os.Stat(sharedURLsDataFile); err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
qs, err := quick.New(newSharedURLsV3())
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
err = qs.Load(sharedURLsDataFile)
|
||||
if err != nil {
|
||||
return nil, err.Trace(sharedURLsDataFile)
|
||||
}
|
||||
s := qs.Data().(*sharedURLsV3)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func saveSharedURLsV3(s *sharedURLsV3) *probe.Error {
|
||||
qs, err := quick.New(s)
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
sharedURLsDataFile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return qs.Save(sharedURLsDataFile).Trace(sharedURLsDataFile)
|
||||
}
|
||||
|
||||
func newSharedURLsV3() *sharedURLsV3 {
|
||||
var urls []struct {
|
||||
Date time.Time
|
||||
Message ShareMessageV3
|
||||
}
|
||||
s := &sharedURLsV3{
|
||||
Version: "3",
|
||||
URLs: urls,
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -20,12 +20,35 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
func newSharedURLs() *sharedURLsV2 {
|
||||
return newSharedURLsV2()
|
||||
func shareDataDirSetup() {
|
||||
if !isSharedURLsDataDirExists() {
|
||||
shareDir, err := getSharedURLsDataDir()
|
||||
fatalIf(err.Trace(), "Unable to get shared URL data directory")
|
||||
|
||||
fatalIf(createSharedURLsDataDir().Trace(), "Unable to create shared URL data directory ‘"+shareDir+"’.")
|
||||
}
|
||||
if !isSharedURLsDataFileExists() {
|
||||
shareFile, err := getSharedURLsDataFile()
|
||||
fatalIf(err.Trace(), "Unable to get shared URL data file")
|
||||
|
||||
fatalIf(createSharedURLsDataFile().Trace(), "Unable to create shared URL data file ‘"+shareFile+"’.")
|
||||
}
|
||||
}
|
||||
|
||||
// migrateSharedURLs migrate to newest version sequentially
|
||||
func migrateSharedURLs() {
|
||||
migrateSharedURLsV1ToV2()
|
||||
migrateSharedURLsV2ToV3()
|
||||
}
|
||||
|
||||
func migrateSharedURLsV1ToV2() {
|
||||
@@ -48,7 +71,18 @@ func migrateSharedURLsV1ToV2() {
|
||||
sURLsV2 = newSharedURLsV2()
|
||||
for key, value := range sURLsV1.URLs {
|
||||
value.Message.Key = key
|
||||
sURLsV2.URLs = append(sURLsV2.URLs, value)
|
||||
entry := struct {
|
||||
Date time.Time
|
||||
Message ShareMessageV2
|
||||
}{
|
||||
Date: value.Date,
|
||||
Message: ShareMessageV2{
|
||||
Expiry: value.Message.Expiry,
|
||||
URL: value.Message.URL,
|
||||
Key: value.Message.Key,
|
||||
},
|
||||
}
|
||||
sURLsV2.URLs = append(sURLsV2.URLs, entry)
|
||||
}
|
||||
err = saveSharedURLsV2(sURLsV2)
|
||||
fatalIf(err.Trace(), "Unable to save new shared url version ‘1.1.0’.")
|
||||
@@ -58,6 +92,47 @@ func migrateSharedURLsV1ToV2() {
|
||||
}
|
||||
}
|
||||
|
||||
func migrateSharedURLsV2ToV3() {
|
||||
if !isSharedURLsDataFileExists() {
|
||||
return
|
||||
}
|
||||
conffile, err := getSharedURLsDataFile()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
v3, err := quick.CheckVersion(conffile, "3")
|
||||
if err != nil {
|
||||
fatalIf(err.Trace(), "Unable to check version on share list file")
|
||||
}
|
||||
if v3 {
|
||||
return
|
||||
}
|
||||
|
||||
// try to load V2 if possible
|
||||
sURLsV2, err := loadSharedURLsV2()
|
||||
fatalIf(err.Trace(), "Unable to load shared url version ‘1.1.0’.")
|
||||
if sURLsV2.Version != "1.1.0" {
|
||||
fatalIf(errDummy().Trace(), "Invalid version loaded ‘"+sURLsV2.Version+"’.")
|
||||
}
|
||||
sURLsV3 := newSharedURLsV3()
|
||||
for _, value := range sURLsV2.URLs {
|
||||
entry := struct {
|
||||
Date time.Time
|
||||
Message ShareMessageV3
|
||||
}{
|
||||
Date: value.Date,
|
||||
Message: ShareMessageV3{
|
||||
Expiry: value.Message.Expiry,
|
||||
DownloadURL: value.Message.URL,
|
||||
Key: value.Message.Key,
|
||||
},
|
||||
}
|
||||
sURLsV3.URLs = append(sURLsV3.URLs, entry)
|
||||
}
|
||||
err = saveSharedURLsV3(sURLsV3)
|
||||
fatalIf(err.Trace(), "Unable to save new shared url version ‘1.2.0’.")
|
||||
}
|
||||
|
||||
func getSharedURLsDataDir() (string, *probe.Error) {
|
||||
configDir, err := getMcConfigDir()
|
||||
if err != nil {
|
||||
@@ -111,8 +186,55 @@ func isSharedURLsDataFileExists() bool {
|
||||
}
|
||||
|
||||
func createSharedURLsDataFile() *probe.Error {
|
||||
if err := saveSharedURLsV2(newSharedURLs()); err != nil {
|
||||
if err := saveSharedURLsV3(newSharedURLsV3()); err != nil {
|
||||
return err.Trace()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getNewTargetURL(targetParser *client.URL, name string) string {
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", targetParser.Host)
|
||||
if match {
|
||||
targetParser.Path = string(targetParser.Separator) + name
|
||||
} else {
|
||||
targetParser.Path = string(targetParser.Separator) + path2Bucket(targetParser) + string(targetParser.Separator) + name
|
||||
}
|
||||
return targetParser.String()
|
||||
}
|
||||
|
||||
// this code is necessary since, share only operates on cloud storage URLs not filesystem
|
||||
func path2Bucket(u *client.URL) (bucketName string) {
|
||||
pathSplits := strings.SplitN(u.Path, "?", 2)
|
||||
splits := strings.SplitN(pathSplits[0], string(u.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
}
|
||||
return bucketName
|
||||
}
|
||||
|
||||
func setSharePalette(style string) {
|
||||
console.SetCustomPalette(map[string]*color.Color{
|
||||
"Share": color.New(color.FgGreen, color.Bold),
|
||||
"Expires": color.New(color.FgRed, color.Bold),
|
||||
"URL": color.New(color.FgCyan, color.Bold),
|
||||
})
|
||||
if style == "light" {
|
||||
console.SetCustomPalette(map[string]*color.Color{
|
||||
"Share": color.New(color.FgWhite, color.Bold),
|
||||
"Expires": color.New(color.FgWhite, color.Bold),
|
||||
"URL": color.New(color.FgWhite, color.Bold),
|
||||
})
|
||||
return
|
||||
}
|
||||
/// Add more styles here
|
||||
|
||||
if style == "nocolor" {
|
||||
// All coloring options exhausted, setting nocolor safely
|
||||
console.SetNoColor()
|
||||
}
|
||||
}
|
||||
|
||||
+22
@@ -556,6 +556,28 @@ func (a apiCore) putObject(bucket, object, contentType string, md5SumBytes []byt
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func (a apiCore) presignedPostPolicyRequest(p *PostPolicy) *request {
|
||||
r := new(request)
|
||||
r.config = a.config
|
||||
return r
|
||||
}
|
||||
|
||||
func (a apiCore) presignedPostPolicy(p *PostPolicy) map[string]string {
|
||||
t := time.Now().UTC()
|
||||
r := a.presignedPostPolicyRequest(p)
|
||||
p.policies = append(p.policies, policy{"eq", "$x-amz-date", t.Format(iso8601DateFormat)})
|
||||
p.policies = append(p.policies, policy{"eq", "$x-amz-algorithm", authHeader})
|
||||
p.policies = append(p.policies, policy{"eq", "$x-amz-credential", r.config.AccessKeyID + "/" + getScope(a.config.Region, t)})
|
||||
|
||||
policyBase64 := p.base64()
|
||||
p.formData["policy"] = policyBase64
|
||||
p.formData["x-amz-algorithm"] = authHeader
|
||||
p.formData["x-amz-credential"] = a.config.AccessKeyID + "/" + getScope(a.config.Region, t)
|
||||
p.formData["x-amz-date"] = t.Format(iso8601DateFormat)
|
||||
p.formData["x-amz-signature"] = r.PostPresignSignature(policyBase64, t)
|
||||
return p.formData
|
||||
}
|
||||
|
||||
func (a apiCore) presignedGetObjectRequest(bucket, object string, expires, offset, length int64) (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
|
||||
+15
@@ -73,6 +73,7 @@ type ObjectAPI interface {
|
||||
// PresignedAPI - object specific for now
|
||||
type PresignedAPI interface {
|
||||
PresignedGetObject(bucket, object string, expires time.Duration) (string, error)
|
||||
PresignedPostPolicy(*PostPolicy) (map[string]string, error)
|
||||
}
|
||||
|
||||
// BucketStatCh - bucket metadata over read channel
|
||||
@@ -555,6 +556,20 @@ func (a api) listMultipartUploadsRecursiveInRoutine(bucket, object string, ch ch
|
||||
}
|
||||
}
|
||||
|
||||
// PresignedPostPolicy return POST form data that can be used for object upload
|
||||
func (a api) PresignedPostPolicy(p *PostPolicy) (map[string]string, error) {
|
||||
if p.expiration.IsZero() {
|
||||
return nil, errors.New("Expiration time must be specified")
|
||||
}
|
||||
if _, ok := p.formData["key"]; !ok {
|
||||
return nil, errors.New("object key must be specified")
|
||||
}
|
||||
if _, ok := p.formData["bucket"]; !ok {
|
||||
return nil, errors.New("bucket name must be specified")
|
||||
}
|
||||
return a.presignedPostPolicy(p), nil
|
||||
}
|
||||
|
||||
// PutObject create an object in a bucket
|
||||
//
|
||||
// You must have WRITE permissions on a bucket to create an object
|
||||
|
||||
+28
@@ -19,9 +19,12 @@ package minio
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// decoder provides a unified decoding method interface
|
||||
@@ -79,3 +82,28 @@ func sumHMAC(key []byte, data []byte) []byte {
|
||||
hash.Write(data)
|
||||
return hash.Sum(nil)
|
||||
}
|
||||
|
||||
// getSigningKey hmac seed to calculate final signature
|
||||
func getSigningKey(secret, region string, t time.Time) []byte {
|
||||
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
|
||||
regionbytes := sumHMAC(date, []byte(region))
|
||||
service := sumHMAC(regionbytes, []byte("s3"))
|
||||
signingKey := sumHMAC(service, []byte("aws4_request"))
|
||||
return signingKey
|
||||
}
|
||||
|
||||
// getSignature final signature in hexadecimal form
|
||||
func getSignature(signingKey []byte, stringToSign string) string {
|
||||
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
|
||||
}
|
||||
|
||||
// getScope generate a string of a specific date, an AWS region, and a service
|
||||
func getScope(region string, t time.Time) string {
|
||||
scope := strings.Join([]string{
|
||||
t.Format(yyyymmdd),
|
||||
region,
|
||||
"s3",
|
||||
"aws4_request",
|
||||
}, "/")
|
||||
return scope
|
||||
}
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package minio
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// expirationDateFormat date format for expiration key in json policy
|
||||
const expirationDateFormat = "2006-01-02T15:04:05.999Z"
|
||||
|
||||
// contentLengthRange - min and max size of content
|
||||
type contentLengthRange struct {
|
||||
min int
|
||||
max int
|
||||
}
|
||||
|
||||
func (c contentLengthRange) marshalJSON() string {
|
||||
return fmt.Sprintf("[\"content-length-range\",%d,%d]", c.min, c.max)
|
||||
}
|
||||
|
||||
// Policy explanation: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
|
||||
type policy struct {
|
||||
matchType string
|
||||
key string
|
||||
value string
|
||||
}
|
||||
|
||||
func (p policy) marshalJSON() string {
|
||||
return fmt.Sprintf("[\"%s\",\"%s\",\"%s\"]", p.matchType, p.key, p.value)
|
||||
}
|
||||
|
||||
// PostPolicy provides strict static type conversion and validation for Amazon S3's POST policy JSON string.
|
||||
type PostPolicy struct {
|
||||
expiration time.Time // expiration date and time of the POST policy.
|
||||
policies []policy
|
||||
contentLengthRange contentLengthRange
|
||||
|
||||
// Post form data
|
||||
formData map[string]string
|
||||
}
|
||||
|
||||
// NewPostPolicy instantiate new post policy
|
||||
func NewPostPolicy() *PostPolicy {
|
||||
p := &PostPolicy{}
|
||||
p.policies = make([]policy, 0)
|
||||
p.formData = make(map[string]string)
|
||||
return p
|
||||
}
|
||||
|
||||
// SetExpires expiration time
|
||||
func (p *PostPolicy) SetExpires(t time.Time) error {
|
||||
if t.IsZero() {
|
||||
return errors.New("time input invalid")
|
||||
}
|
||||
p.expiration = t
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetKey Object name
|
||||
func (p *PostPolicy) SetKey(key string) error {
|
||||
if strings.TrimSpace(key) == "" || key == "" {
|
||||
return errors.New("key invalid")
|
||||
}
|
||||
policy := policy{"eq", "$key", key}
|
||||
p.policies = append(p.policies, policy)
|
||||
p.formData["key"] = key
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetKeyStartsWith Object name that can start with
|
||||
func (p *PostPolicy) SetKeyStartsWith(keyStartsWith string) error {
|
||||
if strings.TrimSpace(keyStartsWith) == "" || keyStartsWith == "" {
|
||||
return errors.New("key-starts-with invalid")
|
||||
}
|
||||
policy := policy{"starts-with", "$key", keyStartsWith}
|
||||
p.policies = append(p.policies, policy)
|
||||
p.formData["key"] = keyStartsWith
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetBucket bucket name
|
||||
func (p *PostPolicy) SetBucket(bucket string) error {
|
||||
if strings.TrimSpace(bucket) == "" || bucket == "" {
|
||||
return errors.New("bucket invalid")
|
||||
}
|
||||
policy := policy{"eq", "$bucket", bucket}
|
||||
p.policies = append(p.policies, policy)
|
||||
p.formData["bucket"] = bucket
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetContentType content-type
|
||||
func (p *PostPolicy) SetContentType(contentType string) error {
|
||||
if strings.TrimSpace(contentType) == "" || contentType == "" {
|
||||
return errors.New("contentType invalid")
|
||||
}
|
||||
policy := policy{"eq", "$Content-Type", contentType}
|
||||
p.policies = append(p.policies, policy)
|
||||
p.formData["Content-Type"] = contentType
|
||||
return nil
|
||||
}
|
||||
|
||||
// marshalJSON provides Marshalled JSON
|
||||
func (p PostPolicy) marshalJSON() []byte {
|
||||
var expirationStr string
|
||||
if p.expiration.IsZero() == false {
|
||||
expirationStr = `"expiration":"` + p.expiration.Format(expirationDateFormat) + `"`
|
||||
}
|
||||
var policiesStr string
|
||||
policies := []string{}
|
||||
for _, policy := range p.policies {
|
||||
policies = append(policies, policy.marshalJSON())
|
||||
}
|
||||
if p.contentLengthRange.min != 0 || p.contentLengthRange.max != 0 {
|
||||
policies = append(policies, p.contentLengthRange.marshalJSON())
|
||||
}
|
||||
if len(policies) > 0 {
|
||||
policiesStr = `"conditions":[` + strings.Join(policies, ",") + "]"
|
||||
}
|
||||
retStr := "{"
|
||||
if len(expirationStr) > 0 {
|
||||
retStr = retStr + expirationStr + ","
|
||||
}
|
||||
if len(policiesStr) > 0 {
|
||||
retStr = retStr + policiesStr
|
||||
}
|
||||
retStr = retStr + "}"
|
||||
return []byte(retStr)
|
||||
}
|
||||
|
||||
// base64 produces base64 of PostPolicy's Marshalled json
|
||||
func (p PostPolicy) base64() string {
|
||||
return base64.StdEncoding.EncodeToString(p.marshalJSON())
|
||||
}
|
||||
+16
-36
@@ -46,9 +46,9 @@ type request struct {
|
||||
}
|
||||
|
||||
const (
|
||||
authHeader = "AWS4-HMAC-SHA256"
|
||||
iso8601Format = "20060102T150405Z"
|
||||
yyyymmdd = "20060102"
|
||||
authHeader = "AWS4-HMAC-SHA256"
|
||||
iso8601DateFormat = "20060102T150405Z"
|
||||
yyyymmdd = "20060102"
|
||||
)
|
||||
|
||||
///
|
||||
@@ -422,40 +422,14 @@ func (r *request) getCanonicalRequest(hashedPayload string) string {
|
||||
return canonicalRequest
|
||||
}
|
||||
|
||||
// getScope generate a string of a specific date, an AWS region, and a service
|
||||
func (r *request) getScope(t time.Time) string {
|
||||
scope := strings.Join([]string{
|
||||
t.Format(yyyymmdd),
|
||||
r.config.Region,
|
||||
"s3",
|
||||
"aws4_request",
|
||||
}, "/")
|
||||
return scope
|
||||
}
|
||||
|
||||
// getStringToSign a string based on selected query values
|
||||
func (r *request) getStringToSign(canonicalRequest string, t time.Time) string {
|
||||
stringToSign := authHeader + "\n" + t.Format(iso8601Format) + "\n"
|
||||
stringToSign = stringToSign + r.getScope(t) + "\n"
|
||||
stringToSign := authHeader + "\n" + t.Format(iso8601DateFormat) + "\n"
|
||||
stringToSign = stringToSign + getScope(r.config.Region, t) + "\n"
|
||||
stringToSign = stringToSign + hex.EncodeToString(sum256([]byte(canonicalRequest)))
|
||||
return stringToSign
|
||||
}
|
||||
|
||||
// getSigningKey hmac seed to calculate final signature
|
||||
func (r *request) getSigningKey(t time.Time) []byte {
|
||||
secret := r.config.SecretAccessKey
|
||||
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
|
||||
region := sumHMAC(date, []byte(r.config.Region))
|
||||
service := sumHMAC(region, []byte("s3"))
|
||||
signingKey := sumHMAC(service, []byte("aws4_request"))
|
||||
return signingKey
|
||||
}
|
||||
|
||||
// getSignature final signature in hexadecimal form
|
||||
func (r *request) getSignature(signingKey []byte, stringToSign string) string {
|
||||
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
|
||||
}
|
||||
|
||||
// Presign the request, in accordance with - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
|
||||
func (r *request) PreSignV4() (string, error) {
|
||||
if r.config.AccessKeyID == "" && r.config.SecretAccessKey == "" {
|
||||
@@ -465,6 +439,12 @@ func (r *request) PreSignV4() (string, error) {
|
||||
return r.req.URL.String(), nil
|
||||
}
|
||||
|
||||
func (r *request) PostPresignSignature(policyBase64 string, t time.Time) string {
|
||||
signingkey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t)
|
||||
signature := getSignature(signingkey, policyBase64)
|
||||
return signature
|
||||
}
|
||||
|
||||
// SignV4 the request before Do(), in accordance with - http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
|
||||
func (r *request) SignV4() {
|
||||
query := r.req.URL.Query()
|
||||
@@ -474,10 +454,10 @@ func (r *request) SignV4() {
|
||||
t := time.Now().UTC()
|
||||
// Add date if not present
|
||||
if r.expires != "" {
|
||||
query.Set("X-Amz-Date", t.Format(iso8601Format))
|
||||
query.Set("X-Amz-Date", t.Format(iso8601DateFormat))
|
||||
query.Set("X-Amz-Expires", r.expires)
|
||||
} else {
|
||||
r.Set("X-Amz-Date", t.Format(iso8601Format))
|
||||
r.Set("X-Amz-Date", t.Format(iso8601DateFormat))
|
||||
}
|
||||
|
||||
hashedPayload := r.getHashedPayload()
|
||||
@@ -485,15 +465,15 @@ func (r *request) SignV4() {
|
||||
if r.expires != "" {
|
||||
query.Set("X-Amz-SignedHeaders", signedHeaders)
|
||||
}
|
||||
scope := r.getScope(t)
|
||||
scope := getScope(r.config.Region, t)
|
||||
if r.expires != "" {
|
||||
query.Set("X-Amz-Credential", r.config.AccessKeyID+"/"+scope)
|
||||
r.req.URL.RawQuery = query.Encode()
|
||||
}
|
||||
canonicalRequest := r.getCanonicalRequest(hashedPayload)
|
||||
stringToSign := r.getStringToSign(canonicalRequest, t)
|
||||
signingKey := r.getSigningKey(t)
|
||||
signature := r.getSignature(signingKey, stringToSign)
|
||||
signingKey := getSigningKey(r.config.SecretAccessKey, r.config.Region, t)
|
||||
signature := getSignature(signingKey, stringToSign)
|
||||
|
||||
if r.expires != "" {
|
||||
r.req.URL.RawQuery += "&X-Amz-Signature=" + signature
|
||||
|
||||
+74
-34
@@ -82,6 +82,80 @@ func New(data interface{}) (Config, *probe.Error) {
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// CheckVersion - loads json and compares the version number provided returns back true or false - any failure
|
||||
// is returned as error.
|
||||
func CheckVersion(filename string, version string) (bool, *probe.Error) {
|
||||
_, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return false, probe.NewError(err)
|
||||
}
|
||||
|
||||
fileData, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return false, probe.NewError(err)
|
||||
}
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
fileData = []byte(strings.Replace(string(fileData), "\r\n", "\n", -1))
|
||||
}
|
||||
data := struct {
|
||||
Version string
|
||||
}{
|
||||
Version: "",
|
||||
}
|
||||
err = json.Unmarshal(fileData, &data)
|
||||
if err != nil {
|
||||
switch err := err.(type) {
|
||||
case *json.SyntaxError:
|
||||
return false, probe.NewError(FormatJSONSyntaxError(bytes.NewReader(fileData), err))
|
||||
default:
|
||||
return false, probe.NewError(err)
|
||||
}
|
||||
}
|
||||
config, perr := New(data)
|
||||
if perr != nil {
|
||||
return false, perr.Trace()
|
||||
}
|
||||
if config.Version() != version {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Load - loads json config from filename for the a given struct data
|
||||
func Load(filename string, data interface{}) (Config, *probe.Error) {
|
||||
_, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
fileData, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
fileData = []byte(strings.Replace(string(fileData), "\r\n", "\n", -1))
|
||||
}
|
||||
|
||||
err = json.Unmarshal(fileData, &data)
|
||||
if err != nil {
|
||||
switch err := err.(type) {
|
||||
case *json.SyntaxError:
|
||||
return nil, probe.NewError(FormatJSONSyntaxError(bytes.NewReader(fileData), err))
|
||||
default:
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
}
|
||||
|
||||
config, perr := New(data)
|
||||
if perr != nil {
|
||||
return nil, perr.Trace()
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Version returns the current config file format version
|
||||
func (d config) Version() string {
|
||||
st := structs.New(d.data)
|
||||
@@ -127,40 +201,6 @@ func (d config) Save(filename string) *probe.Error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Load - loads json config
|
||||
func Load(filename string, data interface{}) (Config, *probe.Error) {
|
||||
_, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
fileData, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
fileData = []byte(strings.Replace(string(fileData), "\r\n", "\n", -1))
|
||||
}
|
||||
|
||||
err = json.Unmarshal(fileData, &data)
|
||||
if err != nil {
|
||||
switch err := err.(type) {
|
||||
case *json.SyntaxError:
|
||||
return nil, probe.NewError(FormatJSONSyntaxError(bytes.NewReader(fileData), err))
|
||||
default:
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
}
|
||||
|
||||
config, perr := New(data)
|
||||
if perr != nil {
|
||||
return nil, perr.Trace()
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Load - loads JSON config from file and merge with currently set values
|
||||
func (d *config) Load(filename string) *probe.Error {
|
||||
d.lock.Lock()
|
||||
|
||||
+23
@@ -57,6 +57,29 @@ func (s *MySuite) TestCheckData(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
func (s *MySuite) TestVersion(c *C) {
|
||||
defer os.RemoveAll("test.json")
|
||||
type myStruct struct {
|
||||
Version string
|
||||
User string
|
||||
Password string
|
||||
Folders []string
|
||||
}
|
||||
saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}
|
||||
config, err := quick.New(&saveMe)
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(config, Not(IsNil))
|
||||
config.Save("test.json")
|
||||
|
||||
valid, err := quick.CheckVersion("test.json", "1")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(valid, Equals, true)
|
||||
|
||||
valid, err = quick.CheckVersion("test.json", "2")
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(valid, Equals, false)
|
||||
}
|
||||
|
||||
func (s *MySuite) TestSaveLoad(c *C) {
|
||||
defer os.RemoveAll("test.json")
|
||||
type myStruct struct {
|
||||
|
||||
Vendored
+4
-9
@@ -29,8 +29,8 @@
|
||||
},
|
||||
{
|
||||
"path": "github.com/minio/minio-go",
|
||||
"revision": "4900c9c8695340456ca8409c2354d503f839a608",
|
||||
"revisionTime": "2015-10-02T12:03:54-07:00"
|
||||
"revision": "26948ab46dafaa60c6e14637ebfc1eb43802cb6c",
|
||||
"revisionTime": "2015-10-06T11:59:55-07:00"
|
||||
},
|
||||
{
|
||||
"path": "github.com/minio/minio-go-legacy",
|
||||
@@ -44,8 +44,8 @@
|
||||
},
|
||||
{
|
||||
"path": "github.com/minio/minio/pkg/quick",
|
||||
"revision": "09dc360e06ece15f14df0e15e77d42652b329f05",
|
||||
"revisionTime": "2015-10-03T12:26:04-07:00"
|
||||
"revision": "e719adec8bbe0b717acba2d1ab7c61a1392c70ce",
|
||||
"revisionTime": "2015-10-07T17:49:16-07:00"
|
||||
},
|
||||
{
|
||||
"path": "github.com/minio/pb",
|
||||
@@ -62,11 +62,6 @@
|
||||
"revision": "a5e2b567a4dd6cc74545b8a4f27c9d63b9e7735b",
|
||||
"revisionTime": "2015-07-19T16:15:31+09:00"
|
||||
},
|
||||
{
|
||||
"path": "github.com/tchap/go-patricia/patricia",
|
||||
"revision": "a560f85131e8aafc2cc4bcb1e265ae3fc6ee5f50",
|
||||
"revisionTime": "2015-06-11T09:53:39+02:00"
|
||||
},
|
||||
{
|
||||
"path": "gopkg.in/check.v1",
|
||||
"revision": "11d3bc7aa68e238947792f30573146a3231fc0f1",
|
||||
|
||||
Reference in New Issue
Block a user