Merge pull request #1114 from harshavardhana/add-support-for-signaturev2
Add support for signature v2 - fixes #1111
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
cover.out
|
||||
mc
|
||||
*~
|
||||
*.test
|
||||
|
||||
+10
-2
@@ -26,6 +26,7 @@ import (
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/client/fs"
|
||||
"github.com/minio/mc/pkg/client/s3"
|
||||
"github.com/minio/mc/pkg/client/s3v2"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
@@ -134,7 +135,7 @@ func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error)
|
||||
url := client.NewURL(urlStr)
|
||||
switch url.Type {
|
||||
case client.Object: // Minio and S3 compatible cloud storage
|
||||
s3Config := new(s3.Config)
|
||||
s3Config := new(client.Config)
|
||||
s3Config.AccessKeyID = func() string {
|
||||
if auth.AccessKeyID == globalAccessKeyID {
|
||||
return ""
|
||||
@@ -152,7 +153,14 @@ func getNewClient(urlStr string, auth hostConfig) (client.Client, *probe.Error)
|
||||
s3Config.AppComments = []string{os.Args[0], runtime.GOOS, runtime.GOARCH}
|
||||
s3Config.HostURL = urlStr
|
||||
s3Config.Debug = globalDebugFlag
|
||||
s3Client, err := s3.New(s3Config)
|
||||
|
||||
var s3Client client.Client
|
||||
var err *probe.Error
|
||||
if auth.Signature == "v2" {
|
||||
s3Client, err = s3v2.New(s3Config)
|
||||
} else {
|
||||
s3Client, err = s3.New(s3Config)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ func listAliases() {
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
for k, v := range newConf.Aliases {
|
||||
Prints("%s\n", AliasMessage{
|
||||
op: "list",
|
||||
@@ -173,7 +173,7 @@ func removeAlias(alias string) {
|
||||
}
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
if _, ok := newConf.Aliases[alias]; !ok {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias ‘%s’ does not exist.", alias))
|
||||
}
|
||||
@@ -209,7 +209,7 @@ func addAlias(alias, url string) {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
|
||||
}
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
if oldURL, ok := newConf.Aliases[alias]; ok {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias ‘%s’ already exists for ‘%s’.", alias, oldURL))
|
||||
}
|
||||
|
||||
+31
-14
@@ -26,15 +26,20 @@ USAGE:
|
||||
OPERATION = add | list | remove
|
||||
|
||||
EXAMPLES:
|
||||
1. Add host configuration for a URL. For security reasons turn off bash history
|
||||
1. Add host configuration for a URL, using default signature V4. For security reasons turn off bash history
|
||||
$ set +o history
|
||||
$ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1C\wQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr1
|
||||
$ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12
|
||||
$ set -o history
|
||||
|
||||
2. List all hosts.
|
||||
2. Add host configuration for a URL, using old signature v2. For security reasons turn off bash history
|
||||
$ set +o history
|
||||
$ mc config {{.Name}} add s3.amazonaws.com BKIKJAA5BMMU2RHO6IBB V7f1CwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr12 v2
|
||||
$ set -o history
|
||||
|
||||
3. List all hosts.
|
||||
$ mc config {{.Name}} list
|
||||
|
||||
3. Remove host config.
|
||||
4. Remove host config.
|
||||
$ mc config {{.Name}} remove s3.amazonaws.com
|
||||
|
||||
`,
|
||||
@@ -46,6 +51,7 @@ type HostMessage struct {
|
||||
Host string `json:"host"`
|
||||
AccessKeyID string `json:"accessKeyId,omitempty"`
|
||||
SecretAccessKey string `json:"secretAccessKey,omitempty"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
}
|
||||
|
||||
// String colorized host message
|
||||
@@ -54,7 +60,8 @@ func (a HostMessage) String() string {
|
||||
message := console.Colorize("Host", fmt.Sprintf("[%s] ", a.Host))
|
||||
if a.AccessKeyID != "" || a.SecretAccessKey != "" {
|
||||
message += console.Colorize("AccessKeyID", fmt.Sprintf("<- %s,", a.AccessKeyID))
|
||||
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s", a.SecretAccessKey))
|
||||
message += console.Colorize("SecretAccessKey", fmt.Sprintf(" %s,", a.SecretAccessKey))
|
||||
message += console.Colorize("Signature", fmt.Sprintf(" %s", a.Signature))
|
||||
}
|
||||
return message
|
||||
}
|
||||
@@ -84,12 +91,12 @@ func checkConfigHostSyntax(ctx *cli.Context) {
|
||||
if strings.TrimSpace(ctx.Args().First()) == "" {
|
||||
cli.ShowCommandHelpAndExit(ctx, "host", 1) // last argument is exit code
|
||||
}
|
||||
if len(ctx.Args().Tail()) > 3 {
|
||||
if len(ctx.Args().Tail()) > 4 {
|
||||
fatalIf(errDummy().Trace(), "Incorrect number of arguments to host command")
|
||||
}
|
||||
switch strings.TrimSpace(ctx.Args().First()) {
|
||||
case "add":
|
||||
if len(ctx.Args().Tail()) != 3 {
|
||||
if len(ctx.Args().Tail()) < 3 || len(ctx.Args().Tail()) > 4 {
|
||||
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for add host command.")
|
||||
}
|
||||
case "remove":
|
||||
@@ -108,9 +115,10 @@ func mainConfigHost(ctx *cli.Context) {
|
||||
// set new custom coloring
|
||||
console.SetCustomTheme(map[string]*color.Color{
|
||||
"Host": color.New(color.FgCyan, color.Bold),
|
||||
"Signature": color.New(color.FgYellow, color.Bold),
|
||||
"HostMessage": color.New(color.FgGreen, color.Bold),
|
||||
"AccessKeyID": color.New(color.FgBlue, color.Bold),
|
||||
"SecretAccessKey": color.New(color.FgRed, color.Bold),
|
||||
"HostMessage": color.New(color.FgGreen, color.Bold),
|
||||
})
|
||||
|
||||
arg := ctx.Args().First()
|
||||
@@ -118,7 +126,7 @@ func mainConfigHost(ctx *cli.Context) {
|
||||
|
||||
switch strings.TrimSpace(arg) {
|
||||
case "add":
|
||||
addHost(tailArgs.Get(0), tailArgs.Get(1), tailArgs.Get(2))
|
||||
addHost(tailArgs.Get(0), tailArgs.Get(1), tailArgs.Get(2), tailArgs.Get(3))
|
||||
case "remove":
|
||||
removeHost(tailArgs.Get(0))
|
||||
case "list":
|
||||
@@ -135,13 +143,14 @@ func listHosts() {
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
for k, v := range newConf.Hosts {
|
||||
Prints("%s\n", HostMessage{
|
||||
op: "list",
|
||||
Host: k,
|
||||
AccessKeyID: v.AccessKeyID,
|
||||
SecretAccessKey: v.SecretAccessKey,
|
||||
Signature: v.Signature,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -162,7 +171,7 @@ func removeHost(hostGlob string) {
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
if _, ok := newConf.Hosts[hostGlob]; !ok {
|
||||
fatalIf(errDummy().Trace(), fmt.Sprintf("Host glob ‘%s’ does not exist.", hostGlob))
|
||||
}
|
||||
@@ -197,11 +206,17 @@ func isValidAccessKey(accessKeyID string) bool {
|
||||
return regex.MatchString(accessKeyID)
|
||||
}
|
||||
|
||||
// addHosts - add new hosts
|
||||
func addHost(hostGlob, accessKeyID, secretAccessKey string) {
|
||||
// addHost - add new host
|
||||
func addHost(hostGlob, accessKeyID, secretAccessKey, signature string) {
|
||||
if strings.TrimSpace(hostGlob) == "" {
|
||||
fatalIf(errDummy().Trace(), "Unable to proceed, empty arguments provided.")
|
||||
}
|
||||
if strings.TrimSpace(signature) == "" {
|
||||
signature = "v4"
|
||||
}
|
||||
if strings.ToLower(signature) != "v2" && strings.ToLower(signature) != "v4" {
|
||||
fatalIf(errInvalidArgument().Trace(), "Unrecognized version name provided, supported inputs are ‘v4’, ‘v2’")
|
||||
}
|
||||
config, err := newConfig()
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
|
||||
@@ -220,10 +235,11 @@ func addHost(hostGlob, accessKeyID, secretAccessKey string) {
|
||||
}
|
||||
}
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
newConf.Hosts[hostGlob] = hostConfig{
|
||||
AccessKeyID: accessKeyID,
|
||||
SecretAccessKey: secretAccessKey,
|
||||
Signature: signature,
|
||||
}
|
||||
newConfig, err := quick.New(newConf)
|
||||
fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.")
|
||||
@@ -236,5 +252,6 @@ func addHost(hostGlob, accessKeyID, secretAccessKey string) {
|
||||
Host: hostGlob,
|
||||
AccessKeyID: accessKeyID,
|
||||
SecretAccessKey: secretAccessKey,
|
||||
Signature: signature,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func mainConfigVersion(ctx *cli.Context) {
|
||||
fatalIf(err.Trace(configPath), "Unable to load config path")
|
||||
|
||||
// convert interface{} back to its original struct
|
||||
newConf := config.Data().(*configV3)
|
||||
newConf := config.Data().(*configV4)
|
||||
type Version struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
@@ -28,12 +28,23 @@ import (
|
||||
"github.com/minio/minio/pkg/quick"
|
||||
)
|
||||
|
||||
type configV3 struct {
|
||||
type configV4 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
Hosts map[string]hostConfig `json:"hosts"`
|
||||
}
|
||||
|
||||
type configV3 struct {
|
||||
Version string `json:"version"`
|
||||
Aliases map[string]string `json:"alias"`
|
||||
// custom anonymous struct is necessary from version to 3 to version 4
|
||||
// since hostConfig{} has changed to camelcase fields for unmarshal
|
||||
Hosts map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
} `json:"hosts"`
|
||||
}
|
||||
|
||||
type configV2 struct {
|
||||
Version string
|
||||
Aliases map[string]string
|
||||
@@ -116,7 +127,7 @@ func mustGetMcConfigPath() string {
|
||||
}
|
||||
|
||||
// getMcConfig - reads configuration file and returns config
|
||||
func getMcConfig() (*configV3, *probe.Error) {
|
||||
func getMcConfig() (*configV4, *probe.Error) {
|
||||
if !isMcConfigExists() {
|
||||
return nil, errInvalidArgument().Trace()
|
||||
}
|
||||
@@ -128,10 +139,10 @@ func getMcConfig() (*configV3, *probe.Error) {
|
||||
|
||||
// Cached in private global variable.
|
||||
if v := cache.Get(); v != nil { // Use previously cached config.
|
||||
return v.(quick.Config).Data().(*configV3), nil
|
||||
return v.(quick.Config).Data().(*configV4), nil
|
||||
}
|
||||
|
||||
conf := newConfigV3()
|
||||
conf := newConfigV4()
|
||||
qconf, err := quick.New(conf)
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
@@ -142,15 +153,13 @@ func getMcConfig() (*configV3, *probe.Error) {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
cache.Put(qconf)
|
||||
return qconf.Data().(*configV3), nil
|
||||
|
||||
return qconf.Data().(*configV4), nil
|
||||
}
|
||||
|
||||
// mustGetMcConfig - reads configuration file and returns configs, exits on error
|
||||
func mustGetMcConfig() *configV3 {
|
||||
func mustGetMcConfig() *configV4 {
|
||||
config, err := getMcConfig()
|
||||
fatalIf(err.Trace(), "Unable to read mc configuration.")
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
@@ -192,6 +201,8 @@ func migrateConfig() {
|
||||
migrateConfigV101ToV2()
|
||||
// Migrate config V2 to V3
|
||||
migrateConfigV2ToV3()
|
||||
// Migrate config V3 to V4
|
||||
migrateConfigV3ToV4()
|
||||
}
|
||||
|
||||
func fixConfig() {
|
||||
@@ -278,14 +289,20 @@ func migrateConfigV2ToV3() {
|
||||
if mcConfigV2.Version() == "2" {
|
||||
confV3 := new(configV3)
|
||||
confV3.Aliases = mcConfigV2.Data().(*configV2).Aliases
|
||||
confV3.Hosts = make(map[string]hostConfig)
|
||||
confV3.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
})
|
||||
for host, hostConf := range mcConfigV2.Data().(*configV2).Hosts {
|
||||
newHostConf := hostConfig{}
|
||||
newHostConf := struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
}{}
|
||||
newHostConf.AccessKeyID = hostConf.AccessKeyID
|
||||
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
|
||||
confV3.Hosts[host] = newHostConf
|
||||
}
|
||||
confV3.Version = globalMCConfigVersion
|
||||
confV3.Version = "3"
|
||||
|
||||
mcNewConfigV3, err := quick.New(confV3)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘3’.")
|
||||
@@ -297,6 +314,37 @@ func migrateConfigV2ToV3() {
|
||||
}
|
||||
}
|
||||
|
||||
func migrateConfigV3ToV4() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
}
|
||||
mcConfigV3, err := quick.Load(mustGetMcConfigPath(), newConfigV3())
|
||||
fatalIf(err.Trace(), "Unable to load mc config V2.")
|
||||
|
||||
// update to newer version
|
||||
if mcConfigV3.Version() == "3" {
|
||||
confV4 := new(configV4)
|
||||
confV4.Aliases = mcConfigV3.Data().(*configV3).Aliases
|
||||
confV4.Hosts = make(map[string]hostConfig)
|
||||
for host, hostConf := range mcConfigV3.Data().(*configV3).Hosts {
|
||||
confV4.Hosts[host] = hostConfig{
|
||||
AccessKeyID: hostConf.AccessKeyID,
|
||||
SecretAccessKey: hostConf.SecretAccessKey,
|
||||
Signature: "v4",
|
||||
}
|
||||
}
|
||||
confV4.Version = globalMCConfigVersion
|
||||
|
||||
mcNewConfigV4, err := quick.New(confV4)
|
||||
fatalIf(err.Trace(), "Unable to initialize quick config for config version ‘4’.")
|
||||
|
||||
err = mcNewConfigV4.Save(mustGetMcConfigPath())
|
||||
fatalIf(err.Trace(), "Unable to save config version ‘4’.")
|
||||
|
||||
console.Infof("Successfully migrated %s from version ‘3’ to version ‘4’.\n", mustGetMcConfigPath())
|
||||
}
|
||||
}
|
||||
|
||||
func fixConfigV3() {
|
||||
if !isMcConfigExists() {
|
||||
return
|
||||
@@ -326,9 +374,15 @@ func fixConfigV3() {
|
||||
if len(mcConfigV3.Data().(*brokenConfigV3).Aliases) != 0 || mcConfigV3.Data().(*brokenConfigV3).ACL != "" || mcConfigV3.Data().(*brokenConfigV3).Access != "" && mcConfigV3.Version() == "3" {
|
||||
confV3 := new(configV3)
|
||||
confV3.Aliases = mcConfigV3.Data().(*brokenConfigV3).Aliases
|
||||
confV3.Hosts = make(map[string]hostConfig)
|
||||
confV3.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
})
|
||||
for host, hostConf := range mcConfigV3.Data().(*brokenConfigV3).Hosts {
|
||||
newHostConf := hostConfig{}
|
||||
newHostConf := struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
}{}
|
||||
newHostConf.AccessKeyID = hostConf.AccessKeyID
|
||||
newHostConf.SecretAccessKey = hostConf.SecretAccessKey
|
||||
confV3.Hosts[host] = newHostConf
|
||||
@@ -390,32 +444,55 @@ func newConfigV2() *configV2 {
|
||||
// newConfigV3 - get new config version 3
|
||||
func newConfigV3() *configV3 {
|
||||
conf := new(configV3)
|
||||
conf.Version = "3"
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
})
|
||||
conf.Aliases = make(map[string]string)
|
||||
return conf
|
||||
}
|
||||
|
||||
func newConfigV4() *configV4 {
|
||||
conf := new(configV4)
|
||||
conf.Version = globalMCConfigVersion
|
||||
// make sure to allocate map's otherwise Golang
|
||||
// exits silently without providing any errors
|
||||
conf.Hosts = make(map[string]hostConfig)
|
||||
conf.Aliases = make(map[string]string)
|
||||
|
||||
localHostConfig := hostConfig{}
|
||||
localHostConfig.AccessKeyID = ""
|
||||
localHostConfig.SecretAccessKey = ""
|
||||
localHostConfig := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
Signature: "v4",
|
||||
}
|
||||
|
||||
s3HostConf := hostConfig{}
|
||||
s3HostConf.AccessKeyID = globalAccessKeyID
|
||||
s3HostConf.SecretAccessKey = globalSecretAccessKey
|
||||
s3HostConf := hostConfig{
|
||||
AccessKeyID: globalAccessKeyID,
|
||||
SecretAccessKey: globalSecretAccessKey,
|
||||
Signature: "v4",
|
||||
}
|
||||
|
||||
// Your example host config
|
||||
exampleHostConf := hostConfig{}
|
||||
exampleHostConf.AccessKeyID = globalAccessKeyID
|
||||
exampleHostConf.SecretAccessKey = globalSecretAccessKey
|
||||
exampleHostConf := hostConfig{
|
||||
AccessKeyID: globalAccessKeyID,
|
||||
SecretAccessKey: globalSecretAccessKey,
|
||||
Signature: "v4",
|
||||
}
|
||||
|
||||
playHostConfig := hostConfig{}
|
||||
playHostConfig.AccessKeyID = ""
|
||||
playHostConfig.SecretAccessKey = ""
|
||||
playHostConfig := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
Signature: "v4",
|
||||
}
|
||||
|
||||
dlHostConfig := hostConfig{}
|
||||
dlHostConfig.AccessKeyID = ""
|
||||
dlHostConfig.SecretAccessKey = ""
|
||||
dlHostConfig := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
Signature: "v4",
|
||||
}
|
||||
|
||||
conf.Hosts[globalExampleHostURL] = exampleHostConf
|
||||
conf.Hosts["localhost:*"] = localHostConfig
|
||||
@@ -436,8 +513,7 @@ func newConfigV3() *configV3 {
|
||||
|
||||
// newConfig - get new config interface
|
||||
func newConfig() (config quick.Config, err *probe.Error) {
|
||||
conf := newConfigV3()
|
||||
config, err = quick.New(conf)
|
||||
config, err = quick.New(newConfigV4())
|
||||
if err != nil {
|
||||
return nil, err.Trace()
|
||||
}
|
||||
|
||||
+9
-1
@@ -51,7 +51,15 @@ func (s *TestSuite) TestConfigHostContext(c *C) {
|
||||
// reset back
|
||||
console.IsExited = false
|
||||
|
||||
err = app.Run([]string{os.Args[0], "config", "host", "add", "*my-example.com", "AKIKJAA5BMMU2RHO6IBB", "V7f1CCwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr9"})
|
||||
err = app.Run([]string{os.Args[0],
|
||||
"config",
|
||||
"host",
|
||||
"add",
|
||||
"*my-example.com",
|
||||
"AKIKJAA5BMMU2RHO6IBB",
|
||||
"V7f1CCwQqAcwo80UEIJEjc5gVQUSSx5ohQ9GSrr9",
|
||||
"v2",
|
||||
})
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(console.IsExited, Equals, false)
|
||||
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ var (
|
||||
|
||||
// mc configuration related constants.
|
||||
const (
|
||||
globalMCConfigVersion = "3"
|
||||
globalMCConfigVersion = "4"
|
||||
globalMCVersion = Version
|
||||
|
||||
globalMCConfigDir = ".mc/"
|
||||
|
||||
+4
-2
@@ -24,8 +24,9 @@ import (
|
||||
)
|
||||
|
||||
type hostConfig struct {
|
||||
AccessKeyID string `json:"access-key-id"`
|
||||
SecretAccessKey string `json:"secret-access-key"`
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
SecretAccessKey string `json:"secretAccessKey"`
|
||||
Signature string `json:"signature"`
|
||||
}
|
||||
|
||||
// getHostConfig retrieves host specific configuration such as access keys, certs.
|
||||
@@ -40,6 +41,7 @@ func getHostConfig(URL string) (hostConfig, *probe.Error) {
|
||||
hostCfg := hostConfig{
|
||||
AccessKeyID: "",
|
||||
SecretAccessKey: "",
|
||||
Signature: "",
|
||||
}
|
||||
return hostCfg, nil
|
||||
}
|
||||
|
||||
+4
-3
@@ -97,7 +97,7 @@ func (s *TestSuite) TestGetNewClient(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
}
|
||||
|
||||
func (s *TestSuite) TestNewConfigV2(c *C) {
|
||||
func (s *TestSuite) TestNewConfigV4(c *C) {
|
||||
root, err := ioutil.TempDir(os.TempDir(), "mc-")
|
||||
c.Assert(err, IsNil)
|
||||
defer os.RemoveAll(root)
|
||||
@@ -108,12 +108,12 @@ func (s *TestSuite) TestNewConfigV2(c *C) {
|
||||
perr = conf.Save(configFile)
|
||||
c.Assert(perr, IsNil)
|
||||
|
||||
confNew := newConfigV3()
|
||||
confNew := newConfigV4()
|
||||
config, perr := quick.New(confNew)
|
||||
c.Assert(perr, IsNil)
|
||||
perr = config.Load(configFile)
|
||||
c.Assert(perr, IsNil)
|
||||
data := config.Data().(*configV3)
|
||||
data := config.Data().(*configV4)
|
||||
|
||||
type aliases struct {
|
||||
name string
|
||||
@@ -167,6 +167,7 @@ func (s *TestSuite) TestHostConfig(c *C) {
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(hostcfg.AccessKeyID, Equals, globalAccessKeyID)
|
||||
c.Assert(hostcfg.SecretAccessKey, Equals, globalSecretAccessKey)
|
||||
c.Assert(hostcfg.Signature, Equals, "v4")
|
||||
|
||||
_, err = getHostConfig("http://test.minio.io")
|
||||
c.Assert(err, Not(IsNil))
|
||||
|
||||
@@ -57,3 +57,14 @@ type Content struct {
|
||||
Size int64
|
||||
Type os.FileMode
|
||||
}
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
type Config struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
}
|
||||
|
||||
+1
-22
@@ -30,34 +30,13 @@ import (
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
// Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html
|
||||
type Config struct {
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
HostURL string
|
||||
AppName string
|
||||
AppVersion string
|
||||
AppComments []string
|
||||
Debug bool
|
||||
|
||||
// Used for SSL transport layer
|
||||
CertPEM string
|
||||
KeyPEM string
|
||||
}
|
||||
|
||||
// TLSConfig - TLS cert and key configuration
|
||||
type TLSConfig struct {
|
||||
CertPEMBlock []byte
|
||||
KeyPEMBlock []byte
|
||||
}
|
||||
|
||||
type s3Client struct {
|
||||
api minio.API
|
||||
hostURL *client.URL
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. if debug use a internal trace transport
|
||||
func New(config *Config) (client.Client, *probe.Error) {
|
||||
func New(config *client.Config) (client.Client, *probe.Error) {
|
||||
u := client.NewURL(config.HostURL)
|
||||
var transport http.RoundTripper
|
||||
switch {
|
||||
|
||||
@@ -26,6 +26,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
@@ -130,7 +132,7 @@ func (s *MySuite) TestBucketOperations(c *C) {
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(Config)
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
@@ -170,7 +172,7 @@ func (s *MySuite) TestObjectOperations(c *C) {
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(Config)
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Minio Client (C) 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 s3v2
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// HTTPTracer provides callback hook mechanism for HTTP transport.
|
||||
type HTTPTracer interface {
|
||||
Request(req *http.Request) error
|
||||
Response(res *http.Response) error
|
||||
}
|
||||
|
||||
// RoundTripTrace interposes HTTP transport requests and respsonses using HTTPTracer hooks
|
||||
type RoundTripTrace struct {
|
||||
Trace HTTPTracer // User provides callback methods
|
||||
Transport http.RoundTripper // HTTP transport that needs to be intercepted
|
||||
}
|
||||
|
||||
// RoundTrip executes user provided request and response hooks for each HTTP call.
|
||||
func (t RoundTripTrace) RoundTrip(req *http.Request) (res *http.Response, err error) {
|
||||
timeStamp := time.Now()
|
||||
|
||||
if t.Transport == nil {
|
||||
return nil, client.InvalidArgument{}
|
||||
}
|
||||
|
||||
res, err = t.Transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
if t.Trace != nil {
|
||||
err = t.Trace.Request(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = t.Trace.Response(res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
console.Debugln("Response Time: ", time.Since(timeStamp).String()+"\n")
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
// GetNewTraceTransport returns a traceable transport
|
||||
func GetNewTraceTransport(trace HTTPTracer, transport http.RoundTripper) RoundTripTrace {
|
||||
return RoundTripTrace{Trace: trace,
|
||||
Transport: transport}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
/*
|
||||
* Minio Client (C) 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 s3v2
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
"github.com/minio/minio-go-legacy"
|
||||
"github.com/minio/minio/pkg/probe"
|
||||
)
|
||||
|
||||
type s3Client struct {
|
||||
api minio.API
|
||||
hostURL *client.URL
|
||||
}
|
||||
|
||||
// New returns an initialized s3Client structure. if debug use a internal trace transport
|
||||
func New(config *client.Config) (client.Client, *probe.Error) {
|
||||
u := client.NewURL(config.HostURL)
|
||||
var transport http.RoundTripper
|
||||
switch {
|
||||
case config.Debug == true:
|
||||
transport = GetNewTraceTransport(NewTrace(), http.DefaultTransport)
|
||||
default:
|
||||
transport = http.DefaultTransport
|
||||
}
|
||||
s3Conf := minio.Config{
|
||||
AccessKeyID: config.AccessKeyID,
|
||||
SecretAccessKey: config.SecretAccessKey,
|
||||
Transport: transport,
|
||||
Endpoint: u.Scheme + u.SchemeSeparator + u.Host,
|
||||
}
|
||||
s3Conf.AccessKeyID = config.AccessKeyID
|
||||
s3Conf.SecretAccessKey = config.SecretAccessKey
|
||||
s3Conf.Transport = transport
|
||||
s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)
|
||||
s3Conf.Endpoint = u.Scheme + u.SchemeSeparator + u.Host
|
||||
api, err := minio.New(s3Conf)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
return &s3Client{api: api, hostURL: u}, nil
|
||||
}
|
||||
|
||||
// URL get url
|
||||
func (c *s3Client) URL() *client.URL {
|
||||
return c.hostURL
|
||||
}
|
||||
|
||||
// GetObject - get object
|
||||
func (c *s3Client) GetObject(offset, length int64) (io.ReadCloser, int64, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
reader, metadata, err := c.api.GetPartialObject(bucket, object, offset, length)
|
||||
if err != nil {
|
||||
return nil, length, probe.NewError(err)
|
||||
}
|
||||
return reader, metadata.Size, nil
|
||||
}
|
||||
|
||||
// Share - get a usable get object url to share
|
||||
func (c *s3Client) Share(expires time.Duration) (string, *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
return presignedURL, nil
|
||||
}
|
||||
|
||||
// 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
|
||||
// for a multipart upload and there is no need to cross verify,
|
||||
// invidual parts are properly verified
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
err := c.api.PutObject(bucket, object, "application/octet-stream", size, data)
|
||||
if err != nil {
|
||||
errResponse := minio.ToErrorResponse(err)
|
||||
if errResponse != nil {
|
||||
if errResponse.Code == "MethodNotAllowed" {
|
||||
return probe.NewError(client.ObjectAlreadyExists{Object: object})
|
||||
}
|
||||
}
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MakeBucket - make a new bucket
|
||||
func (c *s3Client) MakeBucket() *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
if bucket == "" {
|
||||
return probe.NewError(errors.New("Bucket name is empty."))
|
||||
}
|
||||
|
||||
err := c.api.MakeBucket(bucket, minio.BucketACL("private"))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBucketACL get canned acl's on a bucket
|
||||
func (c *s3Client) GetBucketACL() (acl string, error *probe.Error) {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return "", probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
bucketACL, err := c.api.GetBucketACL(bucket)
|
||||
if err != nil {
|
||||
return "", probe.NewError(err)
|
||||
}
|
||||
return bucketACL.String(), nil
|
||||
}
|
||||
|
||||
// SetBucketACL add canned acl's on a bucket
|
||||
func (c *s3Client) SetBucketACL(acl string) *probe.Error {
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
if object != "" {
|
||||
return probe.NewError(client.InvalidQueryURL{URL: c.hostURL.String()})
|
||||
}
|
||||
err := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
|
||||
if err != nil {
|
||||
return probe.NewError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stat - send a 'HEAD' on a bucket or object to get its metadata
|
||||
func (c *s3Client) Stat() (*client.Content, *probe.Error) {
|
||||
objectMetadata := new(client.Content)
|
||||
bucket, object := c.url2BucketAndObject()
|
||||
switch {
|
||||
// valid case for s3/...
|
||||
case bucket == "" && object == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
return nil, probe.NewError(bucket.Err)
|
||||
}
|
||||
}
|
||||
return &client.Content{Type: os.ModeDir}, nil
|
||||
}
|
||||
if object != "" {
|
||||
metadata, err := c.api.StatObject(bucket, object)
|
||||
if err != nil {
|
||||
errResponse := minio.ToErrorResponse(err)
|
||||
if errResponse != nil {
|
||||
if errResponse.Code == "NoSuchKey" {
|
||||
for content := range c.List(false) {
|
||||
if content.Err != nil {
|
||||
return nil, content.Err.Trace()
|
||||
}
|
||||
content.Content.Type = os.ModeDir
|
||||
content.Content.Name = object
|
||||
content.Content.Size = 0
|
||||
return content.Content, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
objectMetadata.Name = metadata.Key
|
||||
objectMetadata.Time = metadata.LastModified
|
||||
objectMetadata.Size = metadata.Size
|
||||
objectMetadata.Type = os.FileMode(0664)
|
||||
return objectMetadata, nil
|
||||
}
|
||||
err := c.api.BucketExists(bucket)
|
||||
if err != nil {
|
||||
return nil, probe.NewError(err)
|
||||
}
|
||||
bucketMetadata := new(client.Content)
|
||||
bucketMetadata.Name = bucket
|
||||
bucketMetadata.Type = os.ModeDir
|
||||
return bucketMetadata, nil
|
||||
}
|
||||
|
||||
// url2BucketAndObject gives bucketName and objectName from URL path
|
||||
func (c *s3Client) url2BucketAndObject() (bucketName, objectName string) {
|
||||
// convert any virtual host styled requests
|
||||
path := c.hostURL.Path
|
||||
match, _ := filepath.Match("*.s3*.amazonaws.com", c.hostURL.Host)
|
||||
if match {
|
||||
hostSplits := strings.SplitN(c.hostURL.Host, ".", 2)
|
||||
path = string(c.hostURL.Separator) + hostSplits[0] + c.hostURL.Path
|
||||
}
|
||||
|
||||
splits := strings.SplitN(path, string(c.hostURL.Separator), 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
objectName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
objectName = ""
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
objectName = splits[2]
|
||||
}
|
||||
return bucketName, objectName
|
||||
}
|
||||
|
||||
/// Bucket API operations
|
||||
|
||||
// List - list at delimited path, if not recursive
|
||||
func (c *s3Client) List(recursive bool) <-chan client.ContentOnChannel {
|
||||
contentCh := make(chan client.ContentOnChannel)
|
||||
switch recursive {
|
||||
case true:
|
||||
go c.listRecursiveInRoutine(contentCh)
|
||||
default:
|
||||
go c.listInRoutine(contentCh)
|
||||
}
|
||||
return contentCh
|
||||
}
|
||||
|
||||
func (c *s3Client) listInRoutine(contentCh chan client.ContentOnChannel) {
|
||||
defer close(contentCh)
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(bucket.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.Name = bucket.Stat.Name
|
||||
content.Size = 0
|
||||
content.Time = bucket.Stat.CreationDate
|
||||
content.Type = os.ModeDir
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
default:
|
||||
metadata, err := c.api.StatObject(b, o)
|
||||
switch err.(type) {
|
||||
case nil:
|
||||
content := new(client.Content)
|
||||
content.Name = metadata.Key
|
||||
content.Time = metadata.LastModified
|
||||
content.Size = metadata.Size
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
default:
|
||||
for object := range c.api.ListObjects(b, o, false) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
normalizedPrefix := strings.TrimSuffix(o, string(c.hostURL.Separator)) + string(c.hostURL.Separator)
|
||||
normalizedKey := object.Stat.Key
|
||||
if normalizedPrefix != object.Stat.Key && strings.HasPrefix(object.Stat.Key, normalizedPrefix) {
|
||||
normalizedKey = strings.TrimPrefix(object.Stat.Key, normalizedPrefix)
|
||||
}
|
||||
content.Name = normalizedKey
|
||||
switch {
|
||||
case strings.HasSuffix(object.Stat.Key, string(c.hostURL.Separator)):
|
||||
content.Time = time.Now()
|
||||
content.Type = os.ModeDir
|
||||
default:
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
}
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *s3Client) listRecursiveInRoutine(contentCh chan client.ContentOnChannel) {
|
||||
defer close(contentCh)
|
||||
b, o := c.url2BucketAndObject()
|
||||
switch {
|
||||
case b == "" && o == "":
|
||||
for bucket := range c.api.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(bucket.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
for object := range c.api.ListObjects(bucket.Stat.Name, o, true) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
content.Name = filepath.Join(bucket.Stat.Name, object.Stat.Key)
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
for object := range c.api.ListObjects(b, o, true) {
|
||||
if object.Err != nil {
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: nil,
|
||||
Err: probe.NewError(object.Err),
|
||||
}
|
||||
return
|
||||
}
|
||||
content := new(client.Content)
|
||||
normalizedKey := object.Stat.Key
|
||||
switch {
|
||||
case o == "":
|
||||
// if no prefix provided and also URL is not delimited then we add bucket back into object name
|
||||
if strings.LastIndex(c.hostURL.Path, string(c.hostURL.Separator)) == 0 {
|
||||
if c.hostURL.String()[:strings.LastIndex(c.hostURL.String(), string(c.hostURL.Separator))+1] != b {
|
||||
normalizedKey = filepath.Join(b, object.Stat.Key)
|
||||
}
|
||||
}
|
||||
default:
|
||||
if strings.HasSuffix(o, string(c.hostURL.Separator)) {
|
||||
normalizedKey = strings.TrimPrefix(object.Stat.Key, o)
|
||||
}
|
||||
}
|
||||
content.Name = normalizedKey
|
||||
content.Size = object.Stat.Size
|
||||
content.Time = object.Stat.LastModified
|
||||
content.Type = os.FileMode(0664)
|
||||
contentCh <- client.ContentOnChannel{
|
||||
Content: content,
|
||||
Err: nil,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Minio Client (C) 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 s3v2
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/mc/pkg/client"
|
||||
|
||||
. "gopkg.in/check.v1"
|
||||
)
|
||||
|
||||
type bucketHandler struct {
|
||||
resource string
|
||||
}
|
||||
|
||||
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
response := []byte("<ListAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
case r.URL.Path == "/bucket":
|
||||
response := []byte("<ListBucketResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"><Contents><ETag>259d04a13802ae09c7e41be50ccc6baa</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
}
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
if r.Header.Get("x-amz-acl") != "public-read-write" {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
case r.Method == "HEAD":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// objectHandler is an http.Handler that verifies object responses and validates incoming requests
|
||||
type objectHandler struct {
|
||||
resource string
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "PUT":
|
||||
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
_, err = io.CopyN(&buffer, r.Body, int64(length))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(h.data, buffer.Bytes()) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "HEAD":
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "GET":
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "9af2f8218b150c351ad802c6f3d66abe")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.data))
|
||||
}
|
||||
}
|
||||
|
||||
func Test(t *testing.T) { TestingT(t) }
|
||||
|
||||
type MySuite struct{}
|
||||
|
||||
var _ = Suite(&MySuite{})
|
||||
|
||||
func (s *MySuite) TestBucketOperations(c *C) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + bucket.resource
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.MakeBucket()
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.SetBucketACL("public-read-write")
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
conf.HostURL = server.URL + string(s3c.URL().Separator)
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Content.Name, Equals, "bucket")
|
||||
c.Assert(content.Content.Type.IsDir(), Equals, true)
|
||||
}
|
||||
|
||||
conf.HostURL = server.URL + "/bucket"
|
||||
s3c, err = New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
for content := range s3c.List(false) {
|
||||
c.Assert(content.Err, IsNil)
|
||||
c.Assert(content.Content.Name, Equals, "object")
|
||||
c.Assert(content.Content.Type.IsRegular(), Equals, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MySuite) TestObjectOperations(c *C) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
})
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
conf := new(client.Config)
|
||||
conf.HostURL = server.URL + object.resource
|
||||
s3c, err := New(conf)
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
err = s3c.PutObject(int64(len(object.data)), bytes.NewReader(object.data))
|
||||
c.Assert(err, IsNil)
|
||||
|
||||
content, err := s3c.Stat()
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(content.Name, Equals, "object")
|
||||
c.Assert(content.Size, Equals, int64(len(object.data)))
|
||||
c.Assert(content.Type.IsRegular(), Equals, true)
|
||||
|
||||
reader, size, err := s3c.GetObject(0, 0)
|
||||
c.Assert(size, Equals, int64(len(object.data)))
|
||||
|
||||
var buffer bytes.Buffer
|
||||
{
|
||||
_, err := io.CopyN(&buffer, reader, int64(size))
|
||||
c.Assert(err, IsNil)
|
||||
c.Assert(buffer.Bytes(), DeepEquals, object.data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Minio Client (C) 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 s3v2
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio/mc/pkg/console"
|
||||
)
|
||||
|
||||
// Trace - tracing structure
|
||||
type Trace struct {
|
||||
}
|
||||
|
||||
// NewTrace - initialize Trace structure
|
||||
func NewTrace() HTTPTracer {
|
||||
return Trace{}
|
||||
}
|
||||
|
||||
// Request - Trace HTTP Request
|
||||
func (t Trace) Request(req *http.Request) (err error) {
|
||||
origAuth := req.Header.Get("Authorization")
|
||||
|
||||
if strings.TrimSpace(origAuth) != "" {
|
||||
// Authorization (S3 v4 signature) Format:
|
||||
// Authorization: AWS4-HMAC-SHA256 Credential=AKIAJNACEGBGMXBHLEZA/20150524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=bbfaa693c626021bcb5f911cd898a1a30206c1fad6bad1e0eb89e282173bd24c
|
||||
|
||||
// Strip out accessKeyID from: Credential=<access-key-id>/<date>/<aws-region>/<aws-service>/aws4_request
|
||||
regCred := regexp.MustCompile("Credential=([A-Z0-9]+)/")
|
||||
newAuth := regCred.ReplaceAllString(origAuth, "Credential=**REDACTED**/")
|
||||
|
||||
// Strip out 256-bit signature from: Signature=<256-bit signature>
|
||||
regSign := regexp.MustCompile("Signature=([[0-9a-f]+)")
|
||||
newAuth = regSign.ReplaceAllString(newAuth, "Signature=**REDACTED**")
|
||||
|
||||
// Set a temporary redacted auth
|
||||
req.Header.Set("Authorization", newAuth)
|
||||
|
||||
var reqTrace []byte
|
||||
reqTrace, err = httputil.DumpRequestOut(req, false) // Only display header
|
||||
if err == nil {
|
||||
console.Debug(string(reqTrace))
|
||||
}
|
||||
|
||||
// Undo
|
||||
req.Header.Set("Authorization", origAuth)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Response - Trace HTTP Response
|
||||
func (t Trace) Response(res *http.Response) (err error) {
|
||||
resTrace, err := httputil.DumpResponse(res, false) // Only display header
|
||||
if err == nil {
|
||||
console.Debug(string(resTrace))
|
||||
}
|
||||
return err
|
||||
}
|
||||
+1
-1
@@ -73,7 +73,7 @@ type ShareMessage struct {
|
||||
|
||||
// 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))
|
||||
return console.Colorize("Share", fmt.Sprintf("Expiry: %s\n URL: %s\n Key: %s", timeDurationToHumanizedTime(s.Expiry), s.URL, s.Key))
|
||||
}
|
||||
|
||||
// JSON json message for share command
|
||||
|
||||
@@ -44,6 +44,13 @@
|
||||
"revision": "cecdcf344829c73107f974a02026c501fe0f317a",
|
||||
"revisionTime": "2015-09-16T14:54:23-07:00"
|
||||
},
|
||||
{
|
||||
"canonical": "github.com/minio/minio-go-legacy",
|
||||
"comment": "",
|
||||
"local": "vendor/github.com/minio/minio-go-legacy",
|
||||
"revision": "c73c27f1a8bcde793d1218761bd2cae9733ab756",
|
||||
"revisionTime": "2015-09-21T20:50:10-07:00"
|
||||
},
|
||||
{
|
||||
"canonical": "github.com/minio/minio/pkg/probe",
|
||||
"comment": "",
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
|
||||
### Developer Guidelines
|
||||
|
||||
``minio-go-legacy`` welcomes your contribution. To make the process as seamless as possible, we ask for the following:
|
||||
|
||||
* Go ahead and fork the project and make your changes. We encourage pull requests to discuss code changes.
|
||||
- Fork it
|
||||
- Create your feature branch (git checkout -b my-new-feature)
|
||||
- Commit your changes (git commit -am 'Add some feature')
|
||||
- Push to the branch (git push origin my-new-feature)
|
||||
- Create new Pull Request
|
||||
|
||||
* When you're ready to create a pull request, be sure to:
|
||||
- Have test cases for the new code. If you have questions about how to do it, please ask in your pull request.
|
||||
- Run `go fmt`
|
||||
- Squash your commits into a single commit. `git rebase -i`. It's okay to force update your pull request.
|
||||
- Make sure `go test -race ./...` and `go build` completes.
|
||||
|
||||
* Read [Effective Go](https://github.com/golang/go/wiki/CodeReviewComments) article from Golang project
|
||||
- `minio-go-legacy` project is strictly conformant with Golang style
|
||||
- if you happen to observe offending code, please feel free to send a pull request
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
# Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage [](https://gitter.im/minio/minio?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
## Install [](https://travis-ci.org/minio/minio-go-legacy)
|
||||
|
||||
```sh
|
||||
$ go get github.com/minio/minio-go-legacy
|
||||
```
|
||||
## Example
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/minio/minio-go-legacy"
|
||||
)
|
||||
|
||||
func main() {
|
||||
config := minio.Config{
|
||||
AccessKeyID: "YOUR-ACCESS-KEY-HERE",
|
||||
SecretAccessKey: "YOUR-PASSWORD-HERE",
|
||||
Endpoint: "https://s3.amazonaws.com",
|
||||
}
|
||||
s3Client, err := minio.New(config)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
for bucket := range s3Client.ListBuckets() {
|
||||
if bucket.Err != nil {
|
||||
log.Fatalln(bucket.Err)
|
||||
}
|
||||
log.Println(bucket.Stat)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
### Bucket Level
|
||||
* [MakeBucket(bucket, acl) error](examples/makebucket.go)
|
||||
* [BucketExists(bucket) error](examples/bucketexists.go)
|
||||
* [RemoveBucket(bucket) error](examples/removebucket.go)
|
||||
* [GetBucketACL(bucket) (BucketACL, error)](examples/getbucketacl.go)
|
||||
* [SetBucketACL(bucket, BucketACL) error)](examples/setbucketacl.go)
|
||||
* [ListObjects(bucket, prefix, recursive) <-chan ObjectStat](examples/listobjects.go)
|
||||
* [ListBuckets() <-chan BucketStat](examples/listbuckets.go)
|
||||
* [DropAllIncompleteUploads(bucket) <-chan error](examples/dropallincompleteuploads.go)
|
||||
|
||||
### Object Level
|
||||
* [PutObject(bucket, object, size, io.Reader) error](examples/putobject.go)
|
||||
* [GetObject(bucket, object) (io.Reader, ObjectStat, error)](examples/getobject.go)
|
||||
* [GetPartialObject(bucket, object, offset, length) (io.Reader, ObjectStat, error)](examples/getpartialobject.go)
|
||||
* [StatObject(bucket, object) (ObjectStat, error)](examples/statobject.go)
|
||||
* [RemoveObject(bucket, object) error](examples/removeobject.go)
|
||||
* [DropIncompleteUpload(bucket, object) <-chan error](examples/dropincompleteuploads.go)
|
||||
* [PresignedGetObject(bucket, object, expires) (string, error)](examples/presignedgetobject.go)
|
||||
|
||||
### API Reference
|
||||
|
||||
[](http://godoc.org/github.com/minio/minio-go-legacy)
|
||||
|
||||
## Contribute
|
||||
|
||||
[Contributors Guide](./CONTRIBUTING.md)
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// listMultipartUploadsRequest wrapper creates a new listMultipartUploads request
|
||||
func (a apiV1) listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, prefix, delimiter string, maxuploads int) (*request, error) {
|
||||
// resourceQuery - get resources properly escaped and lined up before using them in http request
|
||||
resourceQuery := func() (string, error) {
|
||||
var err error
|
||||
switch {
|
||||
case keymarker != "":
|
||||
keymarker, err = urlEncodeName(keymarker)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
keymarker = fmt.Sprintf("&key-marker=%s", keymarker)
|
||||
fallthrough
|
||||
case uploadIDMarker != "":
|
||||
uploadIDMarker, err = urlEncodeName(uploadIDMarker)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
uploadIDMarker = fmt.Sprintf("&upload-id-marker=%s", uploadIDMarker)
|
||||
fallthrough
|
||||
case prefix != "":
|
||||
prefix, err = urlEncodeName(prefix)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
prefix = fmt.Sprintf("&prefix=%s", prefix)
|
||||
fallthrough
|
||||
case delimiter != "":
|
||||
delimiter, err = urlEncodeName(delimiter)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
delimiter = fmt.Sprintf("&delimiter=%s", delimiter)
|
||||
}
|
||||
query := fmt.Sprintf("?uploads&max-uploads=%d", maxuploads) + keymarker + uploadIDMarker + prefix + delimiter
|
||||
return query, nil
|
||||
}
|
||||
query, err := resourceQuery()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + query,
|
||||
}
|
||||
r, err := newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// listMultipartUploads - (List Multipart Uploads) - Lists some or all (up to 1000) in-progress multipart uploads in a bucket.
|
||||
//
|
||||
// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket.
|
||||
// request paramters :-
|
||||
// ---------
|
||||
// ?key-marker - Specifies the multipart upload after which listing should begin
|
||||
// ?upload-id-marker - Together with key-marker specifies the multipart upload after which listing should begin
|
||||
// ?delimiter - A delimiter is a character you use to group keys.
|
||||
// ?prefix - Limits the response to keys that begin with the specified prefix.
|
||||
// ?max-uploads - Sets the maximum number of multipart uploads returned in the response body.
|
||||
func (a apiV1) listMultipartUploads(bucket, keymarker, uploadIDMarker, prefix, delimiter string, maxuploads int) (listMultipartUploadsResult, error) {
|
||||
req, err := a.listMultipartUploadsRequest(bucket, keymarker, uploadIDMarker, prefix, delimiter, maxuploads)
|
||||
if err != nil {
|
||||
return listMultipartUploadsResult{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return listMultipartUploadsResult{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return listMultipartUploadsResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
listMultipartUploadsResult := listMultipartUploadsResult{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listMultipartUploadsResult)
|
||||
if err != nil {
|
||||
return listMultipartUploadsResult, err
|
||||
}
|
||||
// close body while returning, along with any error
|
||||
return listMultipartUploadsResult, nil
|
||||
}
|
||||
|
||||
// initiateMultipartRequest wrapper creates a new initiateMultiPart request
|
||||
func (a apiV1) initiateMultipartRequest(bucket, object string) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "POST",
|
||||
HTTPPath: separator + bucket + separator + encodedObject + "?uploads",
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// initiateMultipartUpload initiates a multipart upload and returns an upload ID
|
||||
func (a apiV1) initiateMultipartUpload(bucket, object string) (initiateMultipartUploadResult, error) {
|
||||
req, err := a.initiateMultipartRequest(bucket, object)
|
||||
if err != nil {
|
||||
return initiateMultipartUploadResult{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return initiateMultipartUploadResult{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return initiateMultipartUploadResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
initiateMultipartUploadResult := initiateMultipartUploadResult{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &initiateMultipartUploadResult)
|
||||
if err != nil {
|
||||
return initiateMultipartUploadResult, err
|
||||
}
|
||||
return initiateMultipartUploadResult, nil
|
||||
}
|
||||
|
||||
// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request
|
||||
func (a apiV1) completeMultipartUploadRequest(bucket, object, uploadID string, complete completeMultipartUpload) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "POST",
|
||||
HTTPPath: separator + bucket + separator + encodedObject + "?uploadId=" + uploadID,
|
||||
}
|
||||
var completeMultipartUploadBytes []byte
|
||||
switch {
|
||||
case a.config.AcceptType == "application/xml":
|
||||
completeMultipartUploadBytes, err = xml.Marshal(complete)
|
||||
case a.config.AcceptType == "application/json":
|
||||
completeMultipartUploadBytes, err = json.Marshal(complete)
|
||||
default:
|
||||
completeMultipartUploadBytes, err = xml.Marshal(complete)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
|
||||
r, err := newRequest(op, a.config, completeMultipartUploadBuffer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.req.ContentLength = int64(completeMultipartUploadBuffer.Len())
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// completeMultipartUpload completes a multipart upload by assembling previously uploaded parts.
|
||||
func (a apiV1) completeMultipartUpload(bucket, object, uploadID string, c completeMultipartUpload) (completeMultipartUploadResult, error) {
|
||||
req, err := a.completeMultipartUploadRequest(bucket, object, uploadID, c)
|
||||
if err != nil {
|
||||
return completeMultipartUploadResult{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return completeMultipartUploadResult{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return completeMultipartUploadResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
completeMultipartUploadResult := completeMultipartUploadResult{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &completeMultipartUploadResult)
|
||||
if err != nil {
|
||||
return completeMultipartUploadResult, err
|
||||
}
|
||||
return completeMultipartUploadResult, nil
|
||||
}
|
||||
|
||||
// abortMultipartUploadRequest wrapper creates a new AbortMultipartUpload request
|
||||
func (a apiV1) abortMultipartUploadRequest(bucket, object, uploadID string) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "DELETE",
|
||||
HTTPPath: separator + bucket + separator + encodedObject + "?uploadId=" + uploadID,
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// abortMultipartUpload aborts a multipart upload for the given uploadID, all parts are deleted
|
||||
func (a apiV1) abortMultipartUpload(bucket, object, uploadID string) error {
|
||||
req, err := a.abortMultipartUploadRequest(bucket, object, uploadID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
// Abort has no response body, handle it
|
||||
var errorResponse ErrorResponse
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "NoSuchUpload",
|
||||
Message: "The specified multipart upload does not exist.",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
}
|
||||
case http.StatusForbidden:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
}
|
||||
default:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: resp.Status,
|
||||
Message: "",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
}
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// listObjectPartsRequest wrapper creates a new ListObjectParts request
|
||||
func (a apiV1) listObjectPartsRequest(bucket, object, uploadID string, partNumberMarker, maxParts int) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// resourceQuery - get resources properly escaped and lined up before using them in http request
|
||||
resourceQuery := func() string {
|
||||
var partNumberMarkerStr string
|
||||
switch {
|
||||
case partNumberMarker != 0:
|
||||
partNumberMarkerStr = fmt.Sprintf("&part-number-marker=%d", partNumberMarker)
|
||||
}
|
||||
return fmt.Sprintf("?uploadId=%s&max-parts=%d", uploadID, maxParts) + partNumberMarkerStr
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + separator + encodedObject + resourceQuery(),
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// listObjectParts (List Parts) - lists some or all (up to 1000) parts that have been uploaded for a specific multipart upload
|
||||
//
|
||||
// You can use the request parameters as selection criteria to return a subset of the uploads in a bucket.
|
||||
// request paramters :-
|
||||
// ---------
|
||||
// ?part-number-marker - Specifies the part after which listing should begin.
|
||||
func (a apiV1) listObjectParts(bucket, object, uploadID string, partNumberMarker, maxParts int) (listObjectPartsResult, error) {
|
||||
req, err := a.listObjectPartsRequest(bucket, object, uploadID, partNumberMarker, maxParts)
|
||||
if err != nil {
|
||||
return listObjectPartsResult{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return listObjectPartsResult{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return listObjectPartsResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
listObjectPartsResult := listObjectPartsResult{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listObjectPartsResult)
|
||||
if err != nil {
|
||||
return listObjectPartsResult, err
|
||||
}
|
||||
return listObjectPartsResult, nil
|
||||
}
|
||||
|
||||
// uploadPartRequest wrapper creates a new UploadPart request
|
||||
func (a apiV1) uploadPartRequest(bucket, object, uploadID string, md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "PUT",
|
||||
HTTPPath: separator + bucket + separator + encodedObject + "?partNumber=" + strconv.Itoa(partNumber) + "&uploadId=" + uploadID,
|
||||
}
|
||||
r, err := newRequest(op, a.config, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// set Content-MD5 as base64 encoded md5
|
||||
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
|
||||
r.req.ContentLength = size
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// uploadPart uploads a part in a multipart upload.
|
||||
func (a apiV1) uploadPart(bucket, object, uploadID string, md5SumBytes []byte, partNumber int, size int64, body io.ReadSeeker) (completePart, error) {
|
||||
req, err := a.uploadPartRequest(bucket, object, uploadID, md5SumBytes, partNumber, size, body)
|
||||
if err != nil {
|
||||
return completePart{}, err
|
||||
}
|
||||
cPart := completePart{}
|
||||
cPart.PartNumber = partNumber
|
||||
cPart.ETag = "\"" + hex.EncodeToString(md5SumBytes) + "\""
|
||||
|
||||
// initiate the request
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return completePart{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return completePart{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
return cPart, nil
|
||||
}
|
||||
+915
@@ -0,0 +1,915 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
separator = "/"
|
||||
)
|
||||
|
||||
// apiV1 container to hold unexported internal functions
|
||||
type apiV1 struct {
|
||||
config *Config
|
||||
}
|
||||
|
||||
// closeResp close non nil response with any response Body
|
||||
func closeResp(resp *http.Response) {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// putBucketRequest wrapper creates a new putBucket request
|
||||
func (a apiV1) putBucketRequest(bucket, acl, location string) (*request, error) {
|
||||
var r *request
|
||||
var err error
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "PUT",
|
||||
HTTPPath: separator + bucket,
|
||||
}
|
||||
var createBucketConfigBuffer *bytes.Reader
|
||||
// If location is set use it and create proper bucket configuration
|
||||
switch {
|
||||
case location != "":
|
||||
createBucketConfig := new(createBucketConfiguration)
|
||||
createBucketConfig.Location = location
|
||||
var createBucketConfigBytes []byte
|
||||
switch {
|
||||
case a.config.AcceptType == "application/xml":
|
||||
createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
|
||||
case a.config.AcceptType == "application/json":
|
||||
createBucketConfigBytes, err = json.Marshal(createBucketConfig)
|
||||
default:
|
||||
createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes)
|
||||
}
|
||||
switch {
|
||||
case createBucketConfigBuffer == nil:
|
||||
r, err = newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
r, err = newRequest(op, a.config, createBucketConfigBuffer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.req.ContentLength = int64(createBucketConfigBuffer.Len())
|
||||
}
|
||||
// by default bucket is private
|
||||
switch {
|
||||
case acl != "":
|
||||
r.Set("x-amz-acl", acl)
|
||||
default:
|
||||
r.Set("x-amz-acl", "private")
|
||||
}
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
/// Bucket Write Operations
|
||||
|
||||
// putBucket create a new bucket
|
||||
//
|
||||
// Requires valid AWS Access Key ID to authenticate requests
|
||||
// Anonymous requests are never allowed to create buckets
|
||||
//
|
||||
// optional arguments are acl and location - by default all buckets are created
|
||||
// with ``private`` acl and location set to US Standard if one wishes to set
|
||||
// different ACLs and Location one can set them properly.
|
||||
//
|
||||
// ACL valid values
|
||||
// ------------------
|
||||
// private - owner gets full access [DEFAULT]
|
||||
// public-read - owner gets full access, others get read access
|
||||
// public-read-write - owner gets full access, others get full access too
|
||||
// authenticated-read - owner gets full access, authenticated users get read access
|
||||
// ------------------
|
||||
//
|
||||
// Location valid values
|
||||
// ------------------
|
||||
// [ us-west-1 | us-west-2 | eu-west-1 | eu-central-1 | ap-southeast-1 | ap-northeast-1 | ap-southeast-2 | sa-east-1 ]
|
||||
//
|
||||
// Default - US standard
|
||||
func (a apiV1) putBucket(bucket, acl, location string) error {
|
||||
req, err := a.putBucketRequest(bucket, acl, location)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// putBucketRequestACL wrapper creates a new putBucketACL request
|
||||
func (a apiV1) putBucketACLRequest(bucket, acl string) (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "PUT",
|
||||
HTTPPath: separator + bucket + "?acl",
|
||||
}
|
||||
req, err := newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Set("x-amz-acl", acl)
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// putBucketACL set the permissions on an existing bucket using Canned ACL's
|
||||
func (a apiV1) putBucketACL(bucket, acl string) error {
|
||||
req, err := a.putBucketACLRequest(bucket, acl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getBucketACLRequest wrapper creates a new getBucketACL request
|
||||
func (a apiV1) getBucketACLRequest(bucket string) (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + "?acl",
|
||||
}
|
||||
req, err := newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// getBucketACL get the acl information on an existing bucket
|
||||
func (a apiV1) getBucketACL(bucket string) (accessControlPolicy, error) {
|
||||
req, err := a.getBucketACLRequest(bucket)
|
||||
if err != nil {
|
||||
return accessControlPolicy{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return accessControlPolicy{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return accessControlPolicy{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
policy := accessControlPolicy{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &policy)
|
||||
if err != nil {
|
||||
return accessControlPolicy{}, err
|
||||
}
|
||||
if policy.AccessControlList.Grant == nil {
|
||||
errorResponse := ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Access control Grant list is empty, please report this at https://github.com/minio/minio-go-legacy/issues",
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
return accessControlPolicy{}, errorResponse
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
// getBucketLocationRequest wrapper creates a new getBucketLocation request
|
||||
func (a apiV1) getBucketLocationRequest(bucket string) (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + "?location",
|
||||
}
|
||||
req, err := newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// getBucketLocation uses location subresource to return a bucket's region
|
||||
func (a apiV1) getBucketLocation(bucket string) (string, error) {
|
||||
req, err := a.getBucketLocationRequest(bucket)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
var locationConstraint string
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &locationConstraint)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return locationConstraint, nil
|
||||
}
|
||||
|
||||
// listObjectsRequest wrapper creates a new listObjects request
|
||||
func (a apiV1) listObjectsRequest(bucket, marker, prefix, delimiter string, maxkeys int) (*request, error) {
|
||||
// resourceQuery - get resources properly escaped and lined up before using them in http request
|
||||
resourceQuery := func() (*string, error) {
|
||||
var err error
|
||||
switch {
|
||||
case marker != "":
|
||||
marker, err = urlEncodeName(marker)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
marker = fmt.Sprintf("&marker=%s", marker)
|
||||
fallthrough
|
||||
case prefix != "":
|
||||
prefix, err = urlEncodeName(prefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefix = fmt.Sprintf("&prefix=%s", prefix)
|
||||
fallthrough
|
||||
case delimiter != "":
|
||||
delimiter, err = urlEncodeName(delimiter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
delimiter = fmt.Sprintf("&delimiter=%s", delimiter)
|
||||
}
|
||||
query := fmt.Sprintf("?max-keys=%d", maxkeys) + marker + prefix + delimiter
|
||||
return &query, nil
|
||||
}
|
||||
query, err := resourceQuery()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + *query,
|
||||
}
|
||||
r, err := newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
/// Bucket Read Operations
|
||||
|
||||
// listObjects - (List Objects) - List some or all (up to 1000) of the objects in a bucket.
|
||||
//
|
||||
// You can use the request parameters as selection criteria to return a subset of the objects in a bucket.
|
||||
// request paramters :-
|
||||
// ---------
|
||||
// ?marker - Specifies the key to start with when listing objects in a bucket.
|
||||
// ?delimiter - A delimiter is a character you use to group keys.
|
||||
// ?prefix - Limits the response to keys that begin with the specified prefix.
|
||||
// ?max-keys - Sets the maximum number of keys returned in the response body.
|
||||
func (a apiV1) listObjects(bucket, marker, prefix, delimiter string, maxkeys int) (listBucketResult, error) {
|
||||
if err := invalidBucketError(bucket); err != nil {
|
||||
return listBucketResult{}, err
|
||||
}
|
||||
req, err := a.listObjectsRequest(bucket, marker, prefix, delimiter, maxkeys)
|
||||
if err != nil {
|
||||
return listBucketResult{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return listBucketResult{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return listBucketResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
listBucketResult := listBucketResult{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listBucketResult)
|
||||
if err != nil {
|
||||
return listBucketResult, err
|
||||
}
|
||||
// close body while returning, along with any error
|
||||
return listBucketResult, nil
|
||||
}
|
||||
|
||||
// headBucketRequest wrapper creates a new headBucket request
|
||||
func (a apiV1) headBucketRequest(bucket string) (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "HEAD",
|
||||
HTTPPath: separator + bucket,
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// headBucket useful to determine if a bucket exists and you have permission to access it.
|
||||
func (a apiV1) headBucket(bucket string) error {
|
||||
if err := invalidBucketError(bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := a.headBucketRequest(bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// Head has no response body, handle it
|
||||
var errorResponse ErrorResponse
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "NoSuchBucket",
|
||||
Message: "The specified bucket does not exist.",
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
case http.StatusForbidden:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied",
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
default:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: resp.Status,
|
||||
Message: resp.Status,
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteBucketRequest wrapper creates a new deleteBucket request
|
||||
func (a apiV1) deleteBucketRequest(bucket string) (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "DELETE",
|
||||
HTTPPath: separator + bucket,
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// deleteBucket deletes the bucket named in the URI
|
||||
//
|
||||
// NOTE: -
|
||||
// All objects (including all object versions and delete markers)
|
||||
// in the bucket must be deleted before successfully attempting this request
|
||||
func (a apiV1) deleteBucket(bucket string) error {
|
||||
if err := invalidBucketError(bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := a.deleteBucketRequest(bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var errorResponse ErrorResponse
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "NoSuchBucket",
|
||||
Message: "The specified bucket does not exist.",
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
case http.StatusForbidden:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied",
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
default:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: resp.Status,
|
||||
Message: resp.Status,
|
||||
Resource: separator + bucket,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Object Read/Write/Stat Operations
|
||||
|
||||
func (a apiV1) putObjectUnAuthenticatedRequest(bucket, object, contentType string, size int64, body io.Reader) (*request, error) {
|
||||
if strings.TrimSpace(contentType) == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "PUT",
|
||||
HTTPPath: separator + bucket + separator + encodedObject,
|
||||
}
|
||||
r, err := newUnauthenticatedRequest(op, a.config, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Content-MD5 is not set consciously
|
||||
r.Set("Content-Type", contentType)
|
||||
r.req.ContentLength = size
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// putObjectUnAuthenticated - add an object to a bucket
|
||||
// NOTE: You must have WRITE permissions on a bucket to add an object to it.
|
||||
func (a apiV1) putObjectUnAuthenticated(bucket, object, contentType string, size int64, body io.Reader) (ObjectStat, error) {
|
||||
req, err := a.putObjectUnAuthenticatedRequest(bucket, object, contentType, size, body)
|
||||
if err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return ObjectStat{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
var metadata ObjectStat
|
||||
metadata.ETag = strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
|
||||
if metadata.ETag == "" {
|
||||
return ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Missing Etag, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
// putObjectRequest wrapper creates a new PutObject request
|
||||
func (a apiV1) putObjectRequest(bucket, object, contentType string, md5SumBytes []byte, size int64, body io.ReadSeeker) (*request, error) {
|
||||
if strings.TrimSpace(contentType) == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "PUT",
|
||||
HTTPPath: separator + bucket + separator + encodedObject,
|
||||
}
|
||||
r, err := newRequest(op, a.config, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// set Content-MD5 as base64 encoded md5
|
||||
r.Set("Content-MD5", base64.StdEncoding.EncodeToString(md5SumBytes))
|
||||
r.Set("Content-Type", contentType)
|
||||
r.req.ContentLength = size
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// putObject - add an object to a bucket
|
||||
// NOTE: You must have WRITE permissions on a bucket to add an object to it.
|
||||
func (a apiV1) putObject(bucket, object, contentType string, md5SumBytes []byte, size int64, body io.ReadSeeker) (ObjectStat, error) {
|
||||
req, err := a.putObjectRequest(bucket, object, contentType, md5SumBytes, size, body)
|
||||
if err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return ObjectStat{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
var metadata ObjectStat
|
||||
metadata.ETag = strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
|
||||
if metadata.ETag == "" {
|
||||
return ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Missing Etag, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func (a apiV1) presignedGetObjectRequest(bucket, object string, expires, offset, length int64) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + separator + encodedObject,
|
||||
}
|
||||
r, err := newPresignedRequest(op, a.config, expires)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case length > 0 && offset > 0:
|
||||
r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
|
||||
case offset > 0 && length == 0:
|
||||
r.Set("Range", fmt.Sprintf("bytes=%d-", offset))
|
||||
case length > 0 && offset == 0:
|
||||
r.Set("Range", fmt.Sprintf("bytes=-%d", length))
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (a apiV1) presignedGetObject(bucket, object string, expires, offset, length int64) (string, error) {
|
||||
if err := invalidArgumentError(object); err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := a.presignedGetObjectRequest(bucket, object, expires, offset, length)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return req.PreSignV2()
|
||||
}
|
||||
|
||||
// getObjectRequest wrapper creates a new getObject request
|
||||
func (a apiV1) getObjectRequest(bucket, object string, offset, length int64) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator + bucket + separator + encodedObject,
|
||||
}
|
||||
r, err := newRequest(op, a.config, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case length > 0 && offset > 0:
|
||||
r.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1))
|
||||
case offset > 0 && length == 0:
|
||||
r.Set("Range", fmt.Sprintf("bytes=%d-", offset))
|
||||
case length > 0 && offset == 0:
|
||||
r.Set("Range", fmt.Sprintf("bytes=-%d", length))
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// getObject - retrieve object from Object Storage
|
||||
//
|
||||
// Additionally this function also takes range arguments to download the specified
|
||||
// range bytes of an object. Setting offset and length = 0 will download the full object.
|
||||
//
|
||||
// For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.
|
||||
func (a apiV1) getObject(bucket, object string, offset, length int64) (io.ReadCloser, ObjectStat, error) {
|
||||
if err := invalidArgumentError(object); err != nil {
|
||||
return nil, ObjectStat{}, err
|
||||
}
|
||||
req, err := a.getObjectRequest(bucket, object, offset, length)
|
||||
if err != nil {
|
||||
return nil, ObjectStat{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
if err != nil {
|
||||
return nil, ObjectStat{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
switch resp.StatusCode {
|
||||
case http.StatusOK:
|
||||
case http.StatusPartialContent:
|
||||
default:
|
||||
return nil, ObjectStat{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
|
||||
if md5sum == "" {
|
||||
return nil, ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Missing Etag, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified"))
|
||||
if err != nil {
|
||||
return nil, ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Content-Length not recognized, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
contentType := strings.TrimSpace(resp.Header.Get("Content-Type"))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
var objectstat ObjectStat
|
||||
objectstat.ETag = md5sum
|
||||
objectstat.Key = object
|
||||
objectstat.Size = resp.ContentLength
|
||||
objectstat.LastModified = date
|
||||
objectstat.ContentType = contentType
|
||||
|
||||
// do not close body here, caller will close
|
||||
return resp.Body, objectstat, nil
|
||||
}
|
||||
|
||||
// deleteObjectRequest wrapper creates a new deleteObject request
|
||||
func (a apiV1) deleteObjectRequest(bucket, object string) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "DELETE",
|
||||
HTTPPath: separator + bucket + separator + encodedObject,
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// deleteObject deletes a given object from a bucket
|
||||
func (a apiV1) deleteObject(bucket, object string) error {
|
||||
if err := invalidBucketError(bucket); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := invalidArgumentError(object); err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := a.deleteObjectRequest(bucket, object)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var errorResponse ErrorResponse
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "NoSuchKey",
|
||||
Message: "The specified key does not exist.",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
case http.StatusForbidden:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
default:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: resp.Status,
|
||||
Message: resp.Status,
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// headObjectRequest wrapper creates a new headObject request
|
||||
func (a apiV1) headObjectRequest(bucket, object string) (*request, error) {
|
||||
encodedObject, err := urlEncodeName(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "HEAD",
|
||||
HTTPPath: separator + bucket + separator + encodedObject,
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// headObject retrieves metadata from an object without returning the object itself
|
||||
func (a apiV1) headObject(bucket, object string) (ObjectStat, error) {
|
||||
if err := invalidBucketError(bucket); err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
if err := invalidArgumentError(object); err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
req, err := a.headObjectRequest(bucket, object)
|
||||
if err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return ObjectStat{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var errorResponse ErrorResponse
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "NoSuchKey",
|
||||
Message: "The specified key does not exist.",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
case http.StatusForbidden:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Access Denied",
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
default:
|
||||
errorResponse = ErrorResponse{
|
||||
Code: resp.Status,
|
||||
Message: resp.Status,
|
||||
Resource: separator + bucket + separator + object,
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
|
||||
}
|
||||
return ObjectStat{}, errorResponse
|
||||
}
|
||||
}
|
||||
md5sum := strings.Trim(resp.Header.Get("ETag"), "\"") // trim off the odd double quotes
|
||||
if md5sum == "" {
|
||||
return ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Missing Etag, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
size, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
|
||||
if err != nil {
|
||||
return ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Content-Length not recognized, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
date, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified"))
|
||||
if err != nil {
|
||||
return ObjectStat{}, ErrorResponse{
|
||||
Code: "InternalError",
|
||||
Message: "Last-Modified time format not recognized, please report this issue at https://github.com/minio/minio-go-legacy/issues",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
contentType := strings.TrimSpace(resp.Header.Get("Content-Type"))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
|
||||
var objectstat ObjectStat
|
||||
objectstat.ETag = md5sum
|
||||
objectstat.Key = object
|
||||
objectstat.Size = size
|
||||
objectstat.LastModified = date
|
||||
objectstat.ContentType = contentType
|
||||
return objectstat, nil
|
||||
}
|
||||
|
||||
/// Service Operations
|
||||
|
||||
// listBucketRequest wrapper creates a new listBuckets request
|
||||
func (a apiV1) listBucketsRequest() (*request, error) {
|
||||
op := &operation{
|
||||
HTTPServer: a.config.Endpoint,
|
||||
HTTPMethod: "GET",
|
||||
HTTPPath: separator,
|
||||
}
|
||||
return newRequest(op, a.config, nil)
|
||||
}
|
||||
|
||||
// listBuckets list of all buckets owned by the authenticated sender of the request
|
||||
func (a apiV1) listBuckets() (listAllMyBucketsResult, error) {
|
||||
req, err := a.listBucketsRequest()
|
||||
if err != nil {
|
||||
return listAllMyBucketsResult{}, err
|
||||
}
|
||||
resp, err := req.Do()
|
||||
defer closeResp(resp)
|
||||
if err != nil {
|
||||
return listAllMyBucketsResult{}, err
|
||||
}
|
||||
if resp != nil {
|
||||
// for un-authenticated requests, amazon sends a redirect handle it
|
||||
if resp.StatusCode == http.StatusTemporaryRedirect {
|
||||
return listAllMyBucketsResult{}, ErrorResponse{
|
||||
Code: "AccessDenied",
|
||||
Message: "Anonymous access is forbidden for this operation",
|
||||
RequestID: resp.Header.Get("x-amz-request-id"),
|
||||
HostID: resp.Header.Get("x-amz-id-2"),
|
||||
}
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return listAllMyBucketsResult{}, BodyToErrorResponse(resp.Body, a.config.AcceptType)
|
||||
}
|
||||
}
|
||||
listAllMyBucketsResult := listAllMyBucketsResult{}
|
||||
err = acceptTypeDecoder(resp.Body, a.config.AcceptType, &listAllMyBucketsResult)
|
||||
if err != nil {
|
||||
return listAllMyBucketsResult, err
|
||||
}
|
||||
return listAllMyBucketsResult, nil
|
||||
}
|
||||
+1002
File diff suppressed because it is too large
Load Diff
+159
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio_test
|
||||
|
||||
// bucketHandler is an http.Handler that verifies bucket responses and validates incoming requests
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type bucketHandler struct {
|
||||
resource string
|
||||
}
|
||||
|
||||
func (h bucketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "GET":
|
||||
switch {
|
||||
case r.URL.Path == "/":
|
||||
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Buckets><Bucket><Name>bucket</Name><CreationDate>2015-05-20T23:05:09.230Z</CreationDate></Bucket></Buckets><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner></ListAllMyBucketsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
case r.URL.Path == "/bucket":
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AccessControlPolicy><Owner><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\"><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>CustomersName@amazon.com</DisplayName></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case r.URL.Path == "/bucket":
|
||||
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Contents><ETag>\"259d04a13802ae09c7e41be50ccc6baa\"</ETag><Key>object</Key><LastModified>2015-05-21T18:24:21.097Z</LastModified><Size>22061</Size><Owner><ID>minio</ID><DisplayName>minio</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Delimiter></Delimiter><EncodingType></EncodingType><IsTruncated>false</IsTruncated><Marker></Marker><MaxKeys>1000</MaxKeys><Name>testbucket</Name><NextMarker></NextMarker><Prefix></Prefix></ListBucketResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
}
|
||||
case r.Method == "PUT":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
_, ok := r.URL.Query()["acl"]
|
||||
if ok {
|
||||
if r.Header.Get("x-amz-acl") != "public-read-write" {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}
|
||||
case r.Method == "HEAD":
|
||||
switch {
|
||||
case r.URL.Path == h.resource:
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}
|
||||
case r.Method == "DELETE":
|
||||
switch {
|
||||
case r.URL.Path != h.resource:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
default:
|
||||
h.resource = ""
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// objectHandler is an http.Handler that verifies object responses and validates incoming requests
|
||||
type objectHandler struct {
|
||||
resource string
|
||||
data []byte
|
||||
}
|
||||
|
||||
func (h objectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == "PUT":
|
||||
length, err := strconv.Atoi(r.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
_, err = io.CopyN(&buffer, r.Body, int64(length))
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(h.data, buffer.Bytes()) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", "\"9af2f8218b150c351ad802c6f3d66abe\"")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "HEAD":
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "\"9af2f8218b150c351ad802c6f3d66abe\"")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case r.Method == "POST":
|
||||
_, ok := r.URL.Query()["uploads"]
|
||||
if ok {
|
||||
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>example-bucket</Bucket><Key>object</Key><UploadId>XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA</UploadId></InitiateMultipartUploadResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
case r.Method == "GET":
|
||||
_, ok := r.URL.Query()["uploadId"]
|
||||
if ok {
|
||||
uploadID := r.URL.Query().Get("uploadId")
|
||||
if uploadID != "XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
response := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><ListPartsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Bucket>example-bucket</Bucket><Key>example-object</Key><UploadId>XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA</UploadId><Initiator><ID>arn:aws:iam::111122223333:user/some-user-11116a31-17b5-4fb7-9df5-b288870f11xx</ID><DisplayName>umat-user-11116a31-17b5-4fb7-9df5-b288870f11xx</DisplayName></Initiator><Owner><ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID><DisplayName>someName</DisplayName></Owner><StorageClass>STANDARD</StorageClass><PartNumberMarker>1</PartNumberMarker><NextPartNumberMarker>3</NextPartNumberMarker><MaxParts>2</MaxParts><IsTruncated>true</IsTruncated><Part><PartNumber>2</PartNumber><LastModified>2010-11-10T20:48:34.000Z</LastModified><ETag>\"7778aef83f66abc1fa1e8477f296d394\"</ETag><Size>10485760</Size></Part><Part><PartNumber>3</PartNumber><LastModified>2010-11-10T20:48:33.000Z</LastModified><ETag>\"aaaa18db4cc2f85cedef654fccc4a4x8\"</ETag><Size>10485760</Size></Part></ListPartsResult>")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
||||
w.Write(response)
|
||||
return
|
||||
}
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(h.data)))
|
||||
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
|
||||
w.Header().Set("ETag", "\"9af2f8218b150c351ad802c6f3d66abe\"")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
io.Copy(w, bytes.NewReader(h.data))
|
||||
case r.Method == "DELETE":
|
||||
if r.URL.Path != h.resource {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
h.resource = ""
|
||||
h.data = nil
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestACLTypes(t *testing.T) {
|
||||
want := map[string]bool{
|
||||
"private": true,
|
||||
"public-read": true,
|
||||
"public-read-write": true,
|
||||
"authenticated-read": true,
|
||||
"invalid": false,
|
||||
}
|
||||
for acl, ok := range want {
|
||||
if BucketACL(acl).isValidBucketACL() != ok {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAgent(t *testing.T) {
|
||||
conf := new(Config)
|
||||
conf.SetUserAgent("minio", "1.0", "amd64")
|
||||
if !strings.Contains(conf.userAgent, "minio") {
|
||||
t.Fatalf("Error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRegion(t *testing.T) {
|
||||
region := getRegion("s3.amazonaws.com")
|
||||
if region != "us-east-1" {
|
||||
t.Fatalf("Error")
|
||||
}
|
||||
region = getRegion("localhost:9000")
|
||||
if region != "milkyway" {
|
||||
t.Fatalf("Error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartSize(t *testing.T) {
|
||||
var maxPartSize int64 = 1024 * 1024 * 1024 * 5
|
||||
partSize := calculatePartSize(5000000000000000000)
|
||||
if partSize > minimumPartSize {
|
||||
if partSize > maxPartSize {
|
||||
t.Fatal("invalid result, cannot be bigger than maxPartSize 5GB")
|
||||
}
|
||||
}
|
||||
partSize = calculatePartSize(50000000000)
|
||||
if partSize > minimumPartSize {
|
||||
t.Fatal("invalid result, cannot be bigger than minimumPartSize 5MB")
|
||||
}
|
||||
}
|
||||
|
||||
func TestURLEncoding(t *testing.T) {
|
||||
type urlStrings struct {
|
||||
name string
|
||||
encodedName string
|
||||
}
|
||||
|
||||
want := []urlStrings{
|
||||
{
|
||||
name: "bigfile-1._%",
|
||||
encodedName: "bigfile-1._%25",
|
||||
},
|
||||
{
|
||||
name: "本語",
|
||||
encodedName: "%E6%9C%AC%E8%AA%9E",
|
||||
},
|
||||
{
|
||||
name: "本語.1",
|
||||
encodedName: "%E6%9C%AC%E8%AA%9E.1",
|
||||
},
|
||||
{
|
||||
name: ">123>3123123",
|
||||
encodedName: "%3E123%3E3123123",
|
||||
},
|
||||
{
|
||||
name: "test 1 2.txt",
|
||||
encodedName: "test%201%202.txt",
|
||||
},
|
||||
{
|
||||
name: "test++ 1.txt",
|
||||
encodedName: "test%2B%2B%201.txt",
|
||||
},
|
||||
}
|
||||
|
||||
for _, u := range want {
|
||||
encodedName, err := urlEncodeName(u.name)
|
||||
if err != nil {
|
||||
t.Fatalf("Error")
|
||||
}
|
||||
if u.encodedName != encodedName {
|
||||
t.Errorf("Error")
|
||||
}
|
||||
}
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go-legacy"
|
||||
)
|
||||
|
||||
func TestPresignedURL(t *testing.T) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
})
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
a, err := minio.New(minio.Config{Endpoint: server.URL})
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
// should error out for invalid access keys
|
||||
_, err = a.PresignedGetObject("bucket", "object", time.Duration(1000)*time.Second)
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
a, err = minio.New(minio.Config{
|
||||
Endpoint: server.URL,
|
||||
AccessKeyID: "accessKey",
|
||||
SecretAccessKey: "secretKey",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
url, err := a.PresignedGetObject("bucket", "object", time.Duration(1000)*time.Second)
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if url == "" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
_, err = a.PresignedGetObject("bucket", "object", time.Duration(0)*time.Second)
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
_, err = a.PresignedGetObject("bucket", "object", time.Duration(604801)*time.Second)
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketOperations(t *testing.T) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
a, err := minio.New(minio.Config{Endpoint: server.URL})
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
err = a.MakeBucket("bucket", "private")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.BucketExists("bucket")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.BucketExists("bucket1")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if err.Error() != "Access Denied" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.SetBucketACL("bucket", "public-read-write")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
acl, err := a.GetBucketACL("bucket")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if acl != minio.BucketACL("private") {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
for b := range a.ListBuckets() {
|
||||
if b.Err != nil {
|
||||
t.Fatal(b.Err.Error())
|
||||
}
|
||||
if b.Stat.Name != "bucket" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
|
||||
for o := range a.ListObjects("bucket", "", true) {
|
||||
if o.Err != nil {
|
||||
t.Fatal(o.Err.Error())
|
||||
}
|
||||
if o.Stat.Key != "object" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
|
||||
err = a.RemoveBucket("bucket")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.RemoveBucket("bucket1")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if err.Error() != "The specified bucket does not exist." {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketOperationsFail(t *testing.T) {
|
||||
bucket := bucketHandler(bucketHandler{
|
||||
resource: "/bucket",
|
||||
})
|
||||
server := httptest.NewServer(bucket)
|
||||
defer server.Close()
|
||||
|
||||
a, err := minio.New(minio.Config{Endpoint: server.URL})
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
err = a.MakeBucket("bucket$$$", "private")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.BucketExists("bucket.")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.SetBucketACL("bucket-.", "public-read-write")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
_, err = a.GetBucketACL("bucket??")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
for o := range a.ListObjects("bucket??", "", true) {
|
||||
if o.Err == nil {
|
||||
t.Fatal(o.Err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
err = a.RemoveBucket("bucket??")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
if err.Error() != "The specified bucket is not valid." {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestObjectOperations(t *testing.T) {
|
||||
object := objectHandler(objectHandler{
|
||||
resource: "/bucket/object",
|
||||
data: []byte("Hello, World"),
|
||||
})
|
||||
server := httptest.NewServer(object)
|
||||
defer server.Close()
|
||||
|
||||
a, err := minio.New(minio.Config{Endpoint: server.URL})
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
data := []byte("Hello, World")
|
||||
err = a.PutObject("bucket", "object", "", int64(len(data)), bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
metadata, err := a.StatObject("bucket", "object")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if metadata.Key != "object" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if metadata.ETag != "9af2f8218b150c351ad802c6f3d66abe" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
reader, metadata, err := a.GetObject("bucket", "object")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if metadata.Key != "object" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if metadata.ETag != "9af2f8218b150c351ad802c6f3d66abe" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
_, err = io.Copy(&buffer, reader)
|
||||
if !bytes.Equal(buffer.Bytes(), data) {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
|
||||
err = a.RemoveObject("bucket", "object")
|
||||
if err != nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
err = a.RemoveObject("bucket", "object1")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if err.Error() != "The specified key does not exist." {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorResponse(t *testing.T) {
|
||||
errorResponse := []byte("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>AccessDenied</Code><Message>Access Denied</Message><Resource>/mybucket/myphoto.jpg</Resource><RequestId>F19772218238A85A</RequestId><HostId>GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD</HostId></Error>")
|
||||
errorReader := bytes.NewReader(errorResponse)
|
||||
err := minio.BodyToErrorResponse(errorReader, "application/xml")
|
||||
if err == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if err.Error() != "Access Denied" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
resp := minio.ToErrorResponse(err)
|
||||
// valid all fields
|
||||
if resp == nil {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.Code != "AccessDenied" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.RequestID != "F19772218238A85A" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.Message != "Access Denied" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.Resource != "/mybucket/myphoto.jpg" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.HostID != "GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.ToXML() == "" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
if resp.ToJSON() == "" {
|
||||
t.Fatal("Error")
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
// BucketACL - bucket level access control
|
||||
type BucketACL string
|
||||
|
||||
// different types of ACL's currently supported for buckets
|
||||
const (
|
||||
bucketPrivate = BucketACL("private")
|
||||
bucketReadOnly = BucketACL("public-read")
|
||||
bucketPublic = BucketACL("public-read-write")
|
||||
bucketAuthenticated = BucketACL("authenticated-read")
|
||||
)
|
||||
|
||||
// String printer helper
|
||||
func (b BucketACL) String() string {
|
||||
if string(b) == "" {
|
||||
return "private"
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// isValidBucketACL - is provided acl string supported
|
||||
func (b BucketACL) isValidBucketACL() bool {
|
||||
switch true {
|
||||
case b.isPrivate():
|
||||
fallthrough
|
||||
case b.isReadOnly():
|
||||
fallthrough
|
||||
case b.isPublic():
|
||||
fallthrough
|
||||
case b.isAuthenticated():
|
||||
return true
|
||||
case b.String() == "private":
|
||||
// by default its "private"
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// IsPrivate - is acl Private
|
||||
func (b BucketACL) isPrivate() bool {
|
||||
return b == bucketPrivate
|
||||
}
|
||||
|
||||
// IsPublicRead - is acl PublicRead
|
||||
func (b BucketACL) isReadOnly() bool {
|
||||
return b == bucketReadOnly
|
||||
}
|
||||
|
||||
// IsPublicReadWrite - is acl PublicReadWrite
|
||||
func (b BucketACL) isPublic() bool {
|
||||
return b == bucketPublic
|
||||
}
|
||||
|
||||
// IsAuthenticated - is acl AuthenticatedRead
|
||||
func (b BucketACL) isAuthenticated() bool {
|
||||
return b == bucketAuthenticated
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"io"
|
||||
)
|
||||
|
||||
// part - message structure for results from the MultiPart
|
||||
type part struct {
|
||||
MD5Sum []byte
|
||||
ReadSeeker io.ReadSeeker
|
||||
Err error
|
||||
Len int64
|
||||
Num int // part number
|
||||
}
|
||||
|
||||
// skipPart - skipping uploaded parts
|
||||
type skipPart struct {
|
||||
md5sum []byte
|
||||
partNumber int
|
||||
}
|
||||
|
||||
// chopper reads from io.Reader, partitions the data into chunks of given chunksize, and sends
|
||||
// each chunk as io.ReadSeeker to the caller over a channel
|
||||
//
|
||||
// This method runs until an EOF or error occurs. If an error occurs,
|
||||
// the method sends the error over the channel and returns.
|
||||
// Before returning, the channel is always closed.
|
||||
//
|
||||
// additionally this function also skips list of parts if provided
|
||||
func chopper(reader io.Reader, chunkSize int64, skipParts []skipPart) <-chan part {
|
||||
ch := make(chan part, 3)
|
||||
go chopperInRoutine(reader, chunkSize, skipParts, ch)
|
||||
return ch
|
||||
}
|
||||
|
||||
func chopperInRoutine(reader io.Reader, chunkSize int64, skipParts []skipPart, ch chan part) {
|
||||
defer close(ch)
|
||||
p := make([]byte, chunkSize)
|
||||
n, err := io.ReadFull(reader, p)
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF { // short read, only single part return
|
||||
m := md5.Sum(p[0:n])
|
||||
ch <- part{
|
||||
MD5Sum: m[:],
|
||||
ReadSeeker: bytes.NewReader(p[0:n]),
|
||||
Err: nil,
|
||||
Len: int64(n),
|
||||
Num: 1,
|
||||
}
|
||||
return
|
||||
}
|
||||
// catastrophic error send error and return
|
||||
if err != nil {
|
||||
ch <- part{
|
||||
ReadSeeker: nil,
|
||||
Err: err,
|
||||
Num: 0,
|
||||
}
|
||||
return
|
||||
}
|
||||
// send the first part
|
||||
var num = 1
|
||||
md5SumBytes := md5.Sum(p)
|
||||
sp := skipPart{
|
||||
partNumber: num,
|
||||
md5sum: md5SumBytes[:],
|
||||
}
|
||||
if !isPartNumberUploaded(sp, skipParts) {
|
||||
ch <- part{
|
||||
MD5Sum: md5SumBytes[:],
|
||||
ReadSeeker: bytes.NewReader(p),
|
||||
Err: nil,
|
||||
Len: int64(n),
|
||||
Num: num,
|
||||
}
|
||||
}
|
||||
for err == nil {
|
||||
var n int
|
||||
p := make([]byte, chunkSize)
|
||||
n, err = io.ReadFull(reader, p)
|
||||
if err != nil {
|
||||
if err != io.EOF && err != io.ErrUnexpectedEOF { // catastrophic error
|
||||
ch <- part{
|
||||
ReadSeeker: nil,
|
||||
Err: err,
|
||||
Num: 0,
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
num++
|
||||
md5SumBytes := md5.Sum(p[0:n])
|
||||
sp := skipPart{
|
||||
partNumber: num,
|
||||
md5sum: md5SumBytes[:],
|
||||
}
|
||||
if isPartNumberUploaded(sp, skipParts) {
|
||||
continue
|
||||
}
|
||||
ch <- part{
|
||||
MD5Sum: md5SumBytes[:],
|
||||
ReadSeeker: bytes.NewReader(p[0:n]),
|
||||
Err: nil,
|
||||
Len: int64(n),
|
||||
Num: num,
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// to verify if partNumber is part of the skip part list
|
||||
func isPartNumberUploaded(part skipPart, skipParts []skipPart) bool {
|
||||
for _, p := range skipParts {
|
||||
if p.partNumber == part.partNumber && bytes.Equal(p.md5sum, part.md5sum) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// decoder provides a unified decoding method interface
|
||||
type decoder interface {
|
||||
Decode(v interface{}) error
|
||||
}
|
||||
|
||||
// acceptTypeDecoder provide decoded value in given acceptType
|
||||
func acceptTypeDecoder(body io.Reader, acceptType string, v interface{}) error {
|
||||
var d decoder
|
||||
switch {
|
||||
case acceptType == "application/xml":
|
||||
d = xml.NewDecoder(body)
|
||||
case acceptType == "application/json":
|
||||
d = json.NewDecoder(body)
|
||||
default:
|
||||
d = xml.NewDecoder(body)
|
||||
}
|
||||
return d.Decode(v)
|
||||
}
|
||||
|
||||
// urlEncodedName encode the strings from UTF-8 byte representations to HTML hex escape sequences
|
||||
//
|
||||
// This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
|
||||
// non english characters cannot be parsed due to the nature in which url.Encode() is written
|
||||
//
|
||||
// This function on the other hand is a direct replacement for url.Encode() technique to support
|
||||
// pretty much every UTF-8 character.
|
||||
func urlEncodeName(name string) (string, error) {
|
||||
// if object matches reserved string, no need to encode them
|
||||
reservedNames := regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$")
|
||||
if reservedNames.MatchString(name) {
|
||||
return name, nil
|
||||
}
|
||||
var encodedName string
|
||||
for _, s := range name {
|
||||
if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
|
||||
encodedName = encodedName + string(s)
|
||||
continue
|
||||
}
|
||||
switch s {
|
||||
case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
|
||||
encodedName = encodedName + string(s)
|
||||
continue
|
||||
default:
|
||||
len := utf8.RuneLen(s)
|
||||
if len < 0 {
|
||||
return "", errors.New("invalid utf-8")
|
||||
}
|
||||
u := make([]byte, len)
|
||||
utf8.EncodeRune(u, s)
|
||||
for _, r := range u {
|
||||
hex := hex.EncodeToString([]byte{r})
|
||||
encodedName = encodedName + "%" + strings.ToUpper(hex)
|
||||
}
|
||||
}
|
||||
}
|
||||
return encodedName, nil
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"time"
|
||||
)
|
||||
|
||||
// listAllMyBucketsResult container for listBuckets response
|
||||
type listAllMyBucketsResult struct {
|
||||
// Container for one or more buckets.
|
||||
Buckets struct {
|
||||
Bucket []BucketStat
|
||||
}
|
||||
Owner owner
|
||||
}
|
||||
|
||||
// owner container for bucket owner information
|
||||
type owner struct {
|
||||
DisplayName string
|
||||
ID string
|
||||
}
|
||||
|
||||
// commonPrefix container for prefix response
|
||||
type commonPrefix struct {
|
||||
Prefix string
|
||||
}
|
||||
|
||||
// listBucketResult container for listObjects response
|
||||
type listBucketResult struct {
|
||||
CommonPrefixes []commonPrefix // A response can contain CommonPrefixes only if you have specified a delimiter
|
||||
Contents []ObjectStat // Metadata about each object returned
|
||||
Delimiter string
|
||||
|
||||
// Encoding type used to encode object keys in the response.
|
||||
EncodingType string
|
||||
|
||||
// A flag that indicates whether or not ListObjects returned all of the results
|
||||
// that satisfied the search criteria.
|
||||
IsTruncated bool
|
||||
Marker string
|
||||
MaxKeys int64
|
||||
Name string
|
||||
|
||||
// When response is truncated (the IsTruncated element value in the response
|
||||
// is true), you can use the key name in this field as marker in the subsequent
|
||||
// request to get next set of objects. Object storage lists objects in alphabetical
|
||||
// order Note: This element is returned only if you have delimiter request parameter
|
||||
// specified. If response does not include the NextMaker and it is truncated,
|
||||
// you can use the value of the last Key in the response as the marker in the
|
||||
// subsequent request to get the next set of object keys.
|
||||
NextMarker string
|
||||
Prefix string
|
||||
}
|
||||
|
||||
// multiPartUpload container for multipart session
|
||||
type multiPartUpload struct {
|
||||
// Date and time at which the multipart upload was initiated.
|
||||
Initiated time.Time `type:"timestamp" timestampFormat:"iso8601"`
|
||||
|
||||
Initiator initiator
|
||||
Owner owner
|
||||
|
||||
StorageClass string
|
||||
|
||||
// Key of the object for which the multipart upload was initiated.
|
||||
Key string
|
||||
|
||||
// Upload ID that identifies the multipart upload.
|
||||
UploadID string `xml:"UploadId"`
|
||||
}
|
||||
|
||||
// listMultipartUploadsResult container for ListMultipartUploads response
|
||||
type listMultipartUploadsResult struct {
|
||||
Bucket string
|
||||
KeyMarker string
|
||||
UploadIDMarker string `xml:"UploadIdMarker"`
|
||||
NextKeyMarker string
|
||||
NextUploadIDMarker string `xml:"NextUploadIdMarker"`
|
||||
EncodingType string
|
||||
MaxUploads int64
|
||||
IsTruncated bool
|
||||
Uploads []multiPartUpload `xml:"Upload"`
|
||||
Prefix string
|
||||
Delimiter string
|
||||
CommonPrefixes []commonPrefix // A response can contain CommonPrefixes only if you specify a delimiter
|
||||
}
|
||||
|
||||
// initiator container for who initiated multipart upload
|
||||
type initiator struct {
|
||||
ID string
|
||||
DisplayName string
|
||||
}
|
||||
|
||||
// partMetadata container for particular part of an object
|
||||
type partMetadata struct {
|
||||
// Part number identifies the part.
|
||||
PartNumber int
|
||||
|
||||
// Date and time the part was uploaded.
|
||||
LastModified time.Time
|
||||
|
||||
// Entity tag returned when the part was uploaded, usually md5sum of the part
|
||||
ETag string
|
||||
|
||||
// Size of the uploaded part data.
|
||||
Size int64
|
||||
}
|
||||
|
||||
// listObjectPartsResult container for ListObjectParts response.
|
||||
type listObjectPartsResult struct {
|
||||
Bucket string
|
||||
Key string
|
||||
UploadID string `xml:"UploadId"`
|
||||
|
||||
Initiator initiator
|
||||
Owner owner
|
||||
|
||||
StorageClass string
|
||||
PartNumberMarker int
|
||||
NextPartNumberMarker int
|
||||
MaxParts int
|
||||
|
||||
// Indicates whether the returned list of parts is truncated.
|
||||
IsTruncated bool
|
||||
Parts []partMetadata `xml:"Part"`
|
||||
|
||||
EncodingType string
|
||||
}
|
||||
|
||||
// initiateMultipartUploadResult container for InitiateMultiPartUpload response.
|
||||
type initiateMultipartUploadResult struct {
|
||||
Bucket string
|
||||
Key string
|
||||
UploadID string `xml:"UploadId"`
|
||||
}
|
||||
|
||||
// completeMultipartUploadResult container for completed multipart upload response.
|
||||
type completeMultipartUploadResult struct {
|
||||
Location string
|
||||
Bucket string
|
||||
Key string
|
||||
ETag string
|
||||
}
|
||||
|
||||
// completePart sub container lists individual part numbers and their md5sum, part of completeMultipartUpload.
|
||||
type completePart struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ Part" json:"-"`
|
||||
|
||||
// Part number identifies the part.
|
||||
PartNumber int
|
||||
ETag string
|
||||
}
|
||||
|
||||
// completeMultipartUpload container for completing multipart upload
|
||||
type completeMultipartUpload struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CompleteMultipartUpload" json:"-"`
|
||||
Parts []completePart `xml:"Part"`
|
||||
}
|
||||
|
||||
// createBucketConfiguration container for bucket configuration
|
||||
type createBucketConfiguration struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CreateBucketConfiguration" json:"-"`
|
||||
Location string `xml:"LocationConstraint"`
|
||||
}
|
||||
|
||||
type grant struct {
|
||||
Grantee struct {
|
||||
ID string
|
||||
DisplayName string
|
||||
EmailAddress string
|
||||
Type string
|
||||
URI string
|
||||
}
|
||||
Permission string
|
||||
}
|
||||
|
||||
type accessControlPolicy struct {
|
||||
AccessControlList struct {
|
||||
Grant []grant
|
||||
}
|
||||
Owner owner
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
/* **** SAMPLE ERROR RESPONSE ****
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Error>
|
||||
<Code>AccessDenied</Code>
|
||||
<Message>Access Denied</Message>
|
||||
<Resource>/mybucket/myphoto.jpg</Resource>
|
||||
<RequestId>F19772218238A85A</RequestId>
|
||||
<HostId>GuWkjyviSiGHizehqpmsD1ndz5NClSP19DOT+s2mv7gXGQ8/X1lhbDGiIJEXpGFD</HostId>
|
||||
</Error>
|
||||
*/
|
||||
|
||||
// ErrorResponse is the type error returned by some API operations.
|
||||
type ErrorResponse struct {
|
||||
XMLName xml.Name `xml:"Error" json:"-"`
|
||||
Code string
|
||||
Message string
|
||||
Resource string
|
||||
RequestID string `xml:"RequestId"`
|
||||
HostID string `xml:"HostId"`
|
||||
}
|
||||
|
||||
// ToErrorResponse returns parsed ErrorResponse struct, if input is nil or not ErrorResponse return value is nil
|
||||
// this fuction is useful when some one wants to dig deeper into the error structures over the network.
|
||||
//
|
||||
// for example:
|
||||
//
|
||||
// import s3 "github.com/minio/minio-go-legacy"
|
||||
// ...
|
||||
// ...
|
||||
// ..., err := s3.GetObject(...)
|
||||
// if err != nil {
|
||||
// resp := s3.ToErrorResponse(err)
|
||||
// fmt.Println(resp.ToXML())
|
||||
// }
|
||||
// ...
|
||||
// ...
|
||||
func ToErrorResponse(err error) *ErrorResponse {
|
||||
switch err := err.(type) {
|
||||
case ErrorResponse:
|
||||
return &err
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ToXML send raw xml marshalled as string
|
||||
func (e ErrorResponse) ToXML() string {
|
||||
b, err := xml.Marshal(&e)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// ToJSON send raw json marshalled as string
|
||||
func (e ErrorResponse) ToJSON() string {
|
||||
b, err := json.Marshal(&e)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Error formats HTTP error string
|
||||
func (e ErrorResponse) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
// BodyToErrorResponse returns a new encoded ErrorResponse structure
|
||||
func BodyToErrorResponse(errBody io.Reader, acceptType string) error {
|
||||
var errorResponse ErrorResponse
|
||||
err := acceptTypeDecoder(errBody, acceptType, &errorResponse)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
|
||||
// invalidBucketToError - invalid bucket to errorResponse
|
||||
func invalidBucketError(bucket string) error {
|
||||
// verify bucket name in accordance with
|
||||
// - http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
|
||||
isValidBucket := func(bucket string) bool {
|
||||
if len(bucket) < 3 || len(bucket) > 63 {
|
||||
return false
|
||||
}
|
||||
if bucket[0] == '.' || bucket[len(bucket)-1] == '.' {
|
||||
return false
|
||||
}
|
||||
if match, _ := regexp.MatchString("\\.\\.", bucket); match == true {
|
||||
return false
|
||||
}
|
||||
// We don't support buckets with '.' in them
|
||||
match, _ := regexp.MatchString("^[a-zA-Z][a-zA-Z0-9\\-]+[a-zA-Z0-9]$", bucket)
|
||||
return match
|
||||
}
|
||||
|
||||
if !isValidBucket(strings.TrimSpace(bucket)) {
|
||||
// no resource since bucket is empty string
|
||||
errorResponse := ErrorResponse{
|
||||
Code: "InvalidBucketName",
|
||||
Message: "The specified bucket is not valid.",
|
||||
RequestID: "minio",
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// invalidObjectError invalid object name to errorResponse
|
||||
func invalidObjectError(object string) error {
|
||||
if strings.TrimSpace(object) == "" || object == "" {
|
||||
// no resource since object name is empty
|
||||
errorResponse := ErrorResponse{
|
||||
Code: "NoSuchKey",
|
||||
Message: "The specified key does not exist.",
|
||||
RequestID: "minio",
|
||||
}
|
||||
return errorResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// invalidArgumentError invalid argument to errorResponse
|
||||
func invalidArgumentError(arg string) error {
|
||||
errorResponse := ErrorResponse{
|
||||
Code: "InvalidArgument",
|
||||
Message: "Invalid Argument",
|
||||
RequestID: "minio",
|
||||
}
|
||||
if strings.TrimSpace(arg) == "" || arg == "" {
|
||||
// no resource since arg is empty string
|
||||
return errorResponse
|
||||
}
|
||||
if !utf8.ValidString(arg) {
|
||||
// add resource to reply back with invalid string
|
||||
errorResponse.Resource = arg
|
||||
return errorResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
/*
|
||||
* Minio Go Library for Amazon S3 Legacy v2 Signature Compatible Cloud Storage (C) 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 minio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// operation - rest operation
|
||||
type operation struct {
|
||||
HTTPServer string
|
||||
HTTPMethod string
|
||||
HTTPPath string
|
||||
}
|
||||
|
||||
// request - a http request
|
||||
type request struct {
|
||||
req *http.Request
|
||||
config *Config
|
||||
body io.ReadSeeker
|
||||
expires int64
|
||||
}
|
||||
|
||||
func path2BucketAndObject(path string) (bucketName, objectName string) {
|
||||
pathSplits := strings.SplitN(path, "?", 2)
|
||||
splits := strings.SplitN(pathSplits[0], separator, 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
bucketName = ""
|
||||
objectName = ""
|
||||
case 2:
|
||||
bucketName = splits[1]
|
||||
objectName = ""
|
||||
case 3:
|
||||
bucketName = splits[1]
|
||||
objectName = splits[2]
|
||||
}
|
||||
return bucketName, objectName
|
||||
}
|
||||
|
||||
// path2Object gives objectName from URL path
|
||||
func path2Object(path string) (objectName string) {
|
||||
pathSplits := strings.SplitN(path, "?", 2)
|
||||
splits := strings.SplitN(pathSplits[0], separator, 3)
|
||||
switch len(splits) {
|
||||
case 0, 1:
|
||||
fallthrough
|
||||
case 2:
|
||||
objectName = ""
|
||||
case 3:
|
||||
objectName = splits[2]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// path2Query gives query part from URL path
|
||||
func path2Query(path string) (query string) {
|
||||
pathSplits := strings.SplitN(path, "?", 2)
|
||||
if len(pathSplits) > 1 {
|
||||
query = pathSplits[1]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (op *operation) getRequestURL(config Config) (url string) {
|
||||
// parse URL for the combination of HTTPServer + HTTPPath
|
||||
if config.Region != "milkyway" {
|
||||
// if virtual style hosts, bucket name is not needed to be part of path
|
||||
if config.isVirtualStyle {
|
||||
url = op.HTTPServer + separator + path2Object(op.HTTPPath)
|
||||
query := path2Query(op.HTTPPath)
|
||||
// verify if there is a query string to
|
||||
if query != "" {
|
||||
url = url + "?" + query
|
||||
}
|
||||
} else {
|
||||
url = op.HTTPServer + op.HTTPPath
|
||||
}
|
||||
} else {
|
||||
url = op.HTTPServer + op.HTTPPath
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func httpNewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
|
||||
u, err := url.Parse(urlStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// make sure to encode properly, url.Parse in golang is buggy and creates erroneous encoding
|
||||
uEncoded := u
|
||||
bucketName, objectName := path2BucketAndObject(uEncoded.Path)
|
||||
if objectName != "" {
|
||||
encodedObjectName, err := urlEncodeName(objectName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uEncoded.Opaque = "//" + uEncoded.Host + separator + bucketName + separator + encodedObjectName
|
||||
} else {
|
||||
uEncoded.Opaque = "//" + uEncoded.Host + separator + bucketName
|
||||
}
|
||||
rc, ok := body.(io.ReadCloser)
|
||||
if !ok && body != nil {
|
||||
rc = ioutil.NopCloser(body)
|
||||
}
|
||||
req := &http.Request{
|
||||
Method: method,
|
||||
URL: uEncoded,
|
||||
Proto: "HTTP/1.1",
|
||||
ProtoMajor: 1,
|
||||
ProtoMinor: 1,
|
||||
Header: make(http.Header),
|
||||
Body: rc,
|
||||
Host: uEncoded.Host,
|
||||
}
|
||||
if body != nil {
|
||||
switch v := body.(type) {
|
||||
case *bytes.Buffer:
|
||||
req.ContentLength = int64(v.Len())
|
||||
case *bytes.Reader:
|
||||
req.ContentLength = int64(v.Len())
|
||||
case *strings.Reader:
|
||||
req.ContentLength = int64(v.Len())
|
||||
}
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func newPresignedRequest(op *operation, config *Config, expires int64) (*request, error) {
|
||||
// if no method default to POST
|
||||
method := op.HTTPMethod
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
|
||||
u := op.getRequestURL(*config)
|
||||
|
||||
// get a new HTTP request, for the requested method
|
||||
req, err := httpNewRequest(method, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// set UserAgent
|
||||
req.Header.Set("User-Agent", config.userAgent)
|
||||
|
||||
// set Accept header for response encoding style, if available
|
||||
if config.AcceptType != "" {
|
||||
req.Header.Set("Accept", config.AcceptType)
|
||||
}
|
||||
|
||||
// save for subsequent use
|
||||
r := new(request)
|
||||
r.config = config
|
||||
r.expires = expires
|
||||
r.req = req
|
||||
r.body = nil
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// newUnauthenticatedRequest - instantiate a new unauthenticated request
|
||||
func newUnauthenticatedRequest(op *operation, config *Config, body io.Reader) (*request, error) {
|
||||
// if no method default to POST
|
||||
method := op.HTTPMethod
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
|
||||
u := op.getRequestURL(*config)
|
||||
|
||||
// get a new HTTP request, for the requested method
|
||||
req, err := httpNewRequest(method, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// set UserAgent
|
||||
req.Header.Set("User-Agent", config.userAgent)
|
||||
|
||||
// set Accept header for response encoding style, if available
|
||||
if config.AcceptType != "" {
|
||||
req.Header.Set("Accept", config.AcceptType)
|
||||
}
|
||||
|
||||
// add body
|
||||
switch {
|
||||
case body == nil:
|
||||
req.Body = nil
|
||||
default:
|
||||
req.Body = ioutil.NopCloser(body)
|
||||
}
|
||||
|
||||
// save for subsequent use
|
||||
r := new(request)
|
||||
r.req = req
|
||||
r.config = config
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// newRequest - instantiate a new request
|
||||
func newRequest(op *operation, config *Config, body io.ReadSeeker) (*request, error) {
|
||||
// if no method default to POST
|
||||
method := op.HTTPMethod
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
|
||||
u := op.getRequestURL(*config)
|
||||
|
||||
// get a new HTTP request, for the requested method
|
||||
req, err := httpNewRequest(method, u, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// set UserAgent
|
||||
req.Header.Set("User-Agent", config.userAgent)
|
||||
|
||||
// set Accept header for response encoding style, if available
|
||||
if config.AcceptType != "" {
|
||||
req.Header.Set("Accept", config.AcceptType)
|
||||
}
|
||||
|
||||
// add body
|
||||
switch {
|
||||
case body == nil:
|
||||
req.Body = nil
|
||||
default:
|
||||
req.Body = ioutil.NopCloser(body)
|
||||
}
|
||||
|
||||
// save for subsequent use
|
||||
r := new(request)
|
||||
r.config = config
|
||||
r.req = req
|
||||
r.body = body
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// Do - start the request
|
||||
func (r *request) Do() (resp *http.Response, err error) {
|
||||
if r.config.AccessKeyID != "" && r.config.SecretAccessKey != "" {
|
||||
r.SignV2()
|
||||
}
|
||||
transport := http.DefaultTransport
|
||||
if r.config.Transport != nil {
|
||||
transport = r.config.Transport
|
||||
}
|
||||
// do not use http.Client{}, while it may seem intuitive but the problem seems to be
|
||||
// that http.Client{} internally follows redirects and there is no easier way to disable
|
||||
// it from outside using a configuration parameter -
|
||||
// this auto redirect causes complications in verifying subsequent errors
|
||||
//
|
||||
// The best is to use RoundTrip() directly, so the request comes back to the caller where
|
||||
// we are going to handle such replies. And indeed that is the right thing to do here.
|
||||
//
|
||||
return transport.RoundTrip(r.req)
|
||||
}
|
||||
|
||||
// Set - set additional headers if any
|
||||
func (r *request) Set(key, value string) {
|
||||
r.req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
// Get - get header values
|
||||
func (r *request) Get(key string) string {
|
||||
return r.req.Header.Get(key)
|
||||
}
|
||||
|
||||
// https://${S3_BUCKET}.s3.amazonaws.com/${S3_OBJECT}?AWSAccessKeyId=${S3_ACCESS_KEY}&Expires=${TIMESTAMP}&Signature=${SIGNATURE}
|
||||
func (r *request) PreSignV2() (string, error) {
|
||||
if r.config.AccessKeyID == "" || r.config.SecretAccessKey == "" {
|
||||
return "", errors.New("presign requires accesskey and secretkey")
|
||||
}
|
||||
// Add date if not present
|
||||
d := time.Now().UTC()
|
||||
if date := r.Get("Date"); date == "" {
|
||||
r.Set("Date", d.Format(http.TimeFormat))
|
||||
}
|
||||
epochExpires := d.Unix() + r.expires
|
||||
signText := fmt.Sprintf("GET\n\n\n%d\n%s", epochExpires, r.req.URL.Path)
|
||||
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
|
||||
hm.Write([]byte(signText))
|
||||
|
||||
query := r.req.URL.Query()
|
||||
query.Set("AWSAccessKeyId", r.config.AccessKeyID)
|
||||
query.Set("Expires", strconv.FormatInt(epochExpires, 10))
|
||||
query.Set("Signature", base64.StdEncoding.EncodeToString(hm.Sum(nil)))
|
||||
r.req.URL.RawQuery = query.Encode()
|
||||
|
||||
return r.req.URL.String(), nil
|
||||
}
|
||||
|
||||
// Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;
|
||||
// Signature = Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ) );
|
||||
//
|
||||
// StringToSign = HTTP-Verb + "\n" +
|
||||
// Content-MD5 + "\n" +
|
||||
// Content-Type + "\n" +
|
||||
// Date + "\n" +
|
||||
// CanonicalizedAmzHeaders +
|
||||
// CanonicalizedResource;
|
||||
//
|
||||
// CanonicalizedResource = [ "/" + Bucket ] +
|
||||
// <HTTP-Request-URI, from the protocol name up to the query string> +
|
||||
// [ subresource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
|
||||
//
|
||||
// CanonicalizedAmzHeaders = <described below>
|
||||
|
||||
// SignV2 the request before Do() (version 2.0)
|
||||
func (r *request) SignV2() {
|
||||
// Add date if not present
|
||||
if date := r.Get("Date"); date == "" {
|
||||
r.Set("Date", time.Now().UTC().Format(http.TimeFormat))
|
||||
}
|
||||
// Calculate HMAC for secretAccessKey
|
||||
hm := hmac.New(sha1.New, []byte(r.config.SecretAccessKey))
|
||||
hm.Write([]byte(r.getStringToSign()))
|
||||
|
||||
// prepare auth header
|
||||
authHeader := new(bytes.Buffer)
|
||||
authHeader.WriteString(fmt.Sprintf("AWS %s:", r.config.AccessKeyID))
|
||||
encoder := base64.NewEncoder(base64.StdEncoding, authHeader)
|
||||
encoder.Write(hm.Sum(nil))
|
||||
encoder.Close()
|
||||
|
||||
// Set Authorization header
|
||||
r.req.Header.Set("Authorization", authHeader.String())
|
||||
}
|
||||
|
||||
// From the Amazon docs:
|
||||
//
|
||||
// StringToSign = HTTP-Verb + "\n" +
|
||||
// Content-MD5 + "\n" +
|
||||
// Content-Type + "\n" +
|
||||
// Date + "\n" +
|
||||
// CanonicalizedAmzHeaders +
|
||||
// CanonicalizedResource;
|
||||
func (r *request) getStringToSign() string {
|
||||
buf := new(bytes.Buffer)
|
||||
// write standard headers
|
||||
r.writeDefaultHeaders(buf)
|
||||
// write canonicalized AMZ headers if any
|
||||
r.writeCanonicalizedAmzHeaders(buf)
|
||||
// write canonicalized Query resources if any
|
||||
r.writeCanonicalizedResource(buf)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (r *request) writeDefaultHeaders(buf *bytes.Buffer) {
|
||||
buf.WriteString(r.req.Method)
|
||||
buf.WriteByte('\n')
|
||||
buf.WriteString(r.req.Header.Get("Content-MD5"))
|
||||
buf.WriteByte('\n')
|
||||
buf.WriteString(r.req.Header.Get("Content-Type"))
|
||||
buf.WriteByte('\n')
|
||||
buf.WriteString(r.req.Header.Get("Date"))
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
|
||||
func (r *request) writeCanonicalizedAmzHeaders(buf *bytes.Buffer) {
|
||||
var amzHeaders []string
|
||||
vals := make(map[string][]string)
|
||||
for k, vv := range r.req.Header {
|
||||
// all the AMZ headers go lower
|
||||
lk := strings.ToLower(k)
|
||||
if strings.HasPrefix(lk, "x-amz") {
|
||||
amzHeaders = append(amzHeaders, lk)
|
||||
vals[lk] = vv
|
||||
}
|
||||
}
|
||||
sort.Strings(amzHeaders)
|
||||
for _, k := range amzHeaders {
|
||||
buf.WriteString(k)
|
||||
buf.WriteByte(':')
|
||||
for idx, v := range vals[k] {
|
||||
if idx > 0 {
|
||||
buf.WriteByte(',')
|
||||
}
|
||||
if strings.Contains(v, "\n") {
|
||||
// TODO: "Unfold" long headers that
|
||||
// span multiple lines (as allowed by
|
||||
// RFC 2616, section 4.2) by replacing
|
||||
// the folding white-space (including
|
||||
// new-line) by a single space.
|
||||
buf.WriteString(v)
|
||||
} else {
|
||||
buf.WriteString(v)
|
||||
}
|
||||
}
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
|
||||
// Must be sorted:
|
||||
var resourceList = []string{
|
||||
"acl",
|
||||
"location",
|
||||
"logging",
|
||||
"notification",
|
||||
"partNumber",
|
||||
"policy",
|
||||
"response-content-type",
|
||||
"response-content-language",
|
||||
"response-expires",
|
||||
"response-cache-control",
|
||||
"response-content-disposition",
|
||||
"response-content-encoding",
|
||||
"requestPayment",
|
||||
"torrent",
|
||||
"uploadId",
|
||||
"uploads",
|
||||
"versionId",
|
||||
"versioning",
|
||||
"versions",
|
||||
"website",
|
||||
}
|
||||
|
||||
// From the Amazon docs:
|
||||
//
|
||||
// CanonicalizedResource = [ "/" + Bucket ] +
|
||||
// <HTTP-Request-URI, from the protocol name up to the query string> +
|
||||
// [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
|
||||
func (r *request) writeCanonicalizedResource(buf *bytes.Buffer) error {
|
||||
requestURL := r.req.URL
|
||||
encodedURLPath, err := urlEncodeName(requestURL.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buf.WriteString(encodedURLPath)
|
||||
sort.Strings(resourceList)
|
||||
if requestURL.RawQuery != "" {
|
||||
var n int
|
||||
vals, _ := url.ParseQuery(requestURL.RawQuery)
|
||||
// loop through all the supported resourceList
|
||||
for _, resource := range resourceList {
|
||||
if vv, ok := vals[resource]; ok && len(vv) > 0 {
|
||||
n++
|
||||
// first element
|
||||
switch n {
|
||||
case 1:
|
||||
buf.WriteByte('?')
|
||||
// the rest
|
||||
default:
|
||||
buf.WriteByte('&')
|
||||
}
|
||||
buf.WriteString(resource)
|
||||
// request parameters
|
||||
if len(vv[0]) > 0 {
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(url.QueryEscape(vv[0]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user