Compare commits

..
19 Commits
Author SHA1 Message Date
Chris Lu 443a68484a 1.56 2020-02-17 12:54:45 -08:00
Chris Lu 0a57db7026 Merge pull request #1200 from chrislusf/add_s3_acl
Add s3 ACL
2020-02-17 12:53:30 -08:00
Chris Lu 4cdde5f569 configuration stores the identity list 2020-02-17 12:31:59 -08:00
Chris Lu 9232d3ac68 ignore error when counting closed connections 2020-02-14 10:28:02 -08:00
Chris Lu 96c1ae8471 refactoring the close http response 2020-02-14 09:46:36 -08:00
Chris Lu cf5064d702 properly close http response 2020-02-14 09:09:15 -08:00
Chris Lu 9b6296e77a volume: add grpc file read operation
This is added more for performance benchmarking.
2020-02-14 00:37:32 -08:00
Chris Lu 2cddc23ae8 Merge pull request #1198 from stlpmo-jn/resolve_core_when_loadVolume_failed
when Store.MountVolume(), the volume server will be core
2020-02-13 00:27:23 -08:00
panyc16 7b3764fd9e make loadExistingVolume() return bool 2020-02-13 15:19:00 +08:00
Chris Lu 62c34454d8 1.55 2020-02-11 23:00:31 -08:00
Chris Lu 83836f4299 filer: recursively batch delete file chunks
fix https://github.com/chrislusf/seaweedfs/issues/1197
2020-02-11 22:54:10 -08:00
Chris Lu 2a6db0fd43 volume: return 204 for unchanged file uploads
fix https://github.com/chrislusf/seaweedfs/issues/1196
2020-02-11 09:45:02 -08:00
Chris Lu 33b3bd467c Revert "HEAD operation changes to fasthttp"
This reverts commit 58f126fd27.
2020-02-10 13:43:53 -08:00
Chris Lu 58f126fd27 HEAD operation changes to fasthttp 2020-02-10 09:13:29 -08:00
Chris Lu b4abe3c081 unused 2020-02-09 18:02:17 -08:00
Chris Lu f3ce3166ad add streaming v4 2020-02-09 17:42:17 -08:00
Chris Lu b90ad6f452 add v2 support 2020-02-09 16:02:05 -08:00
Chris Lu e7b63d50b1 add s3.config to server.go 2020-02-09 14:31:51 -08:00
Chris Lu 9ed364f053 support acl 2020-02-09 14:30:02 -08:00
51 changed files with 3219 additions and 1457 deletions

No files matched your search

+1 -4
View File
@@ -9,7 +9,6 @@ require (
github.com/DataDog/zstd v1.4.1 // indirect
github.com/Shopify/sarama v1.23.1
github.com/aws/aws-sdk-go v1.23.13
github.com/chrislusf/glog v0.0.0-20180213072942-e58d74c04389
github.com/chrislusf/raft v0.0.0-20190225081310-10d6e2182d92
github.com/coreos/etcd v3.3.15+incompatible // indirect
github.com/coreos/go-semver v0.3.0 // indirect
@@ -37,8 +36,7 @@ require (
github.com/jcmturner/gofork v1.0.0 // indirect
github.com/karlseguin/ccache v2.0.3+incompatible
github.com/karlseguin/expect v1.0.1 // indirect
github.com/klauspost/compress v1.9.8 // indirect
github.com/klauspost/cpuid v1.2.3 // indirect
github.com/klauspost/cpuid v1.2.1 // indirect
github.com/klauspost/crc32 v1.2.0
github.com/klauspost/reedsolomon v1.9.2
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
@@ -78,7 +76,6 @@ require (
github.com/uber-go/atomic v1.4.0 // indirect
github.com/uber/jaeger-client-go v2.17.0+incompatible // indirect
github.com/uber/jaeger-lib v2.0.0+incompatible // indirect
github.com/valyala/fasthttp v1.9.0
github.com/willf/bitset v1.1.10 // indirect
github.com/willf/bloom v2.0.3+incompatible
github.com/wsxiaoys/terminal v0.0.0-20160513160801-0940f3fc43a0 // indirect
-14
View File
@@ -64,8 +64,6 @@ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dR
github.com/census-instrumentation/opencensus-proto v0.2.0 h1:LzQXZOgg4CQfE6bFvXGM30YZL1WW/M337pXml+GrcZ4=
github.com/census-instrumentation/opencensus-proto v0.2.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/chrislusf/glog v0.0.0-20180213072942-e58d74c04389 h1:05igzs+7KihLMjeY2TiINo4eE1kqgEKGpL+5XhFXtHs=
github.com/chrislusf/glog v0.0.0-20180213072942-e58d74c04389/go.mod h1:LBseU6dj13CwRT1XVQQKuT+dRXuzClILSvalxNpFao0=
github.com/chrislusf/raft v0.0.0-20190225081310-10d6e2182d92 h1:lM9SFsh0EPXkyJyrTJqLZPAIJBtNFP6LNkYXu2MnSZI=
github.com/chrislusf/raft v0.0.0-20190225081310-10d6e2182d92/go.mod h1:4jyiUCD5y548+yKW+oiHtccBiMaLCCbFBpK2t7X4eUo=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
@@ -284,15 +282,9 @@ github.com/karlseguin/expect v1.0.1/go.mod h1:zNBxMY8P21owkeogJELCLeHIt+voOSduHY
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.8.2 h1:Bx0qjetmNjdFXASH02NSAREKpiaDwkO1DRZ3dV2KCcs=
github.com/klauspost/compress v1.8.2/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/compress v1.9.8 h1:VMAMUUOh+gaxKTMk+zqbjsSjsIcUcL/LF4o63i82QyA=
github.com/klauspost/compress v1.9.8/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/cpuid v1.2.1 h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/cpuid v1.2.3 h1:CCtW0xUnWGVINKvE/WWOYKdsPV6mawAtvQuSl8guwQs=
github.com/klauspost/cpuid v1.2.3/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
github.com/klauspost/crc32 v1.2.0 h1:0VuyqOCruD33/lJ/ojXNvzVyl8Zr5zdTmj9l9qLZ86I=
github.com/klauspost/crc32 v1.2.0/go.mod h1:+ZoRqAPRLkC4NPOvfYeR5KNOrY6TD+/sAC3HXPZgDYg=
github.com/klauspost/reedsolomon v1.9.2 h1:E9CMS2Pqbv+C7tsrYad4YC9MfhnMVWhMRsTi7U0UB18=
@@ -553,11 +545,6 @@ github.com/unrolled/render v0.0.0-20180914162206-b9786414de4d h1:ggUgChAeyge4NZ4
github.com/unrolled/render v0.0.0-20180914162206-b9786414de4d/go.mod h1:tu82oB5W2ykJRVioYsB+IQKcft7ryBr7w12qMBUPyXg=
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/negroni v0.3.0/go.mod h1:Meg73S6kFm/4PpbYdq35yYWoCZ9mS/YSx+lKnmiohz4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.9.0 h1:hNpmUdy/+ZXYpGy0OBfm7K0UQTzb73W0T0U4iJIVrMw=
github.com/valyala/fasthttp v1.9.0/go.mod h1:FstJa9V+Pj9vQ7OJie2qMHdwemEDaDiSdBnvPM1Su9w=
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
github.com/willf/bitset v1.1.10 h1:NotGKqX0KwQ72NUzqrjZq5ipPNDQex9lo3WpaS8L2sc=
github.com/willf/bitset v1.1.10/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4=
github.com/willf/bloom v2.0.3+incompatible h1:QDacWdqcAUI1MPOwIQZRy9kOR7yxfyEmxX8Wdm2/JPA=
@@ -639,7 +626,6 @@ golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190619014844-b5b0513f8c1b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190909003024-a7b16738d86b h1:XfVGCX+0T4WOStkaOsJRllbsiImhB2jgVBGc9L0lPGc=
golang.org/x/net v0.0.0-20190909003024-a7b16738d86b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
+49 -8
View File
@@ -19,6 +19,7 @@ import (
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/operation"
"github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
"github.com/chrislusf/seaweedfs/weed/security"
"github.com/chrislusf/seaweedfs/weed/util"
"github.com/chrislusf/seaweedfs/weed/wdclient"
@@ -40,6 +41,7 @@ type BenchmarkOptions struct {
maxCpu *int
grpcDialOption grpc.DialOption
masterClient *wdclient.MasterClient
grpcRead *bool
}
var (
@@ -64,6 +66,7 @@ func init() {
b.replication = cmdBenchmark.Flag.String("replication", "000", "replication type")
b.cpuprofile = cmdBenchmark.Flag.String("cpuprofile", "", "cpu profile output file")
b.maxCpu = cmdBenchmark.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
b.grpcRead = cmdBenchmark.Flag.Bool("grpcRead", false, "use grpc API to read")
sharedBytes = make([]byte, 1024)
}
@@ -278,23 +281,61 @@ func readFiles(fileIdLineChan chan string, s *stat) {
fmt.Printf("reading file %s\n", fid)
}
start := time.Now()
url, err := b.masterClient.LookupFileId(fid)
if err != nil {
s.failed++
println("!!!! ", fid, " location not found!!!!!")
continue
var bytesRead int
var err error
if *b.grpcRead {
volumeServer, err := b.masterClient.LookupVolumeServer(fid)
if err != nil {
s.failed++
println("!!!! ", fid, " location not found!!!!!")
continue
}
bytesRead, err = grpcFileGet(volumeServer, fid, b.grpcDialOption)
} else {
url, err := b.masterClient.LookupFileId(fid)
if err != nil {
s.failed++
println("!!!! ", fid, " location not found!!!!!")
continue
}
var bytes []byte
bytes, err = util.Get(url)
bytesRead = len(bytes)
}
if bytesRead, err := util.Get(url); err == nil {
if err == nil {
s.completed++
s.transferred += int64(len(bytesRead))
s.transferred += int64(bytesRead)
readStats.addSample(time.Now().Sub(start))
} else {
s.failed++
fmt.Printf("Failed to read %s error:%v\n", url, err)
fmt.Printf("Failed to read %s error:%v\n", fid, err)
}
}
}
func grpcFileGet(volumeServer, fid string, grpcDialOption grpc.DialOption) (bytesRead int, err error) {
err = operation.WithVolumeServerClient(volumeServer, grpcDialOption, func(ctx context.Context, client volume_server_pb.VolumeServerClient) error {
fileGetClient, err := client.FileGet(ctx, &volume_server_pb.FileGetRequest{FileId: fid})
if err != nil {
return err
}
for {
resp, respErr := fileGetClient.Recv()
if resp != nil {
bytesRead += len(resp.Data)
}
if respErr != nil {
if respErr == io.EOF {
return nil
}
return respErr
}
}
})
return
}
func writeFileIds(fileName string, fileIdLineChan chan string, finishChan chan bool) {
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
+1
View File
@@ -71,6 +71,7 @@ func downloadToFile(server, fileId, saveDir string) error {
}
f, err := os.OpenFile(path.Join(saveDir, filename), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
io.Copy(ioutil.Discard, rc)
return err
}
defer f.Close()
+51 -1
View File
@@ -22,6 +22,7 @@ type S3Options struct {
filer *string
filerBucketsPath *string
port *int
config *string
domainName *string
tlsPrivateKey *string
tlsCertificate *string
@@ -33,15 +34,63 @@ func init() {
s3StandaloneOptions.filerBucketsPath = cmdS3.Flag.String("filer.dir.buckets", "/buckets", "folder on filer to store all buckets")
s3StandaloneOptions.port = cmdS3.Flag.Int("port", 8333, "s3 server http listen port")
s3StandaloneOptions.domainName = cmdS3.Flag.String("domainName", "", "suffix of the host name, {bucket}.{domainName}")
s3StandaloneOptions.config = cmdS3.Flag.String("config", "", "path to the config file")
s3StandaloneOptions.tlsPrivateKey = cmdS3.Flag.String("key.file", "", "path to the TLS private key file")
s3StandaloneOptions.tlsCertificate = cmdS3.Flag.String("cert.file", "", "path to the TLS certificate file")
}
var cmdS3 = &Command{
UsageLine: "s3 -port=8333 -filer=<ip:port>",
UsageLine: "s3 [-port=8333] [-filer=<ip:port>] [-config=</path/to/config.json>]",
Short: "start a s3 API compatible server that is backed by a filer",
Long: `start a s3 API compatible server that is backed by a filer.
By default, you can use any access key and secret key to access the S3 APIs.
To enable credential based access, create a config.json file similar to this:
{
"identities": [
{
"name": "some_name",
"credentials": [
{
"accessKey": "some_access_key1",
"secretKey": "some_secret_key1"
}
],
"actions": [
"Admin",
"Read",
"Write"
]
},
{
"name": "some_read_only_user",
"credentials": [
{
"accessKey": "some_access_key2",
"secretKey": "some_secret_key2"
}
],
"actions": [
"Read"
]
},
{
"name": "some_normal_user",
"credentials": [
{
"accessKey": "some_access_key3",
"secretKey": "some_secret_key3"
}
],
"actions": [
"Read",
"Write"
]
}
]
}
`,
}
@@ -66,6 +115,7 @@ func (s3opt *S3Options) startS3Server() bool {
_, s3ApiServer_err := s3api.NewS3ApiServer(router, &s3api.S3ApiServerOption{
Filer: *s3opt.filer,
FilerGrpcAddress: filerGrpcAddress,
Config: *s3opt.config,
DomainName: *s3opt.domainName,
BucketsPath: *s3opt.filerBucketsPath,
GrpcDialOption: security.LoadClientTLS(util.GetViper(), "grpc.client"),
+1
View File
@@ -97,6 +97,7 @@ func init() {
s3Options.domainName = cmdServer.Flag.String("s3.domainName", "", "suffix of the host name, {bucket}.{domainName}")
s3Options.tlsPrivateKey = cmdServer.Flag.String("s3.key.file", "", "path to the TLS private key file")
s3Options.tlsCertificate = cmdServer.Flag.String("s3.cert.file", "", "path to the TLS certificate file")
s3Options.config = cmdServer.Flag.String("s3.config", "", "path to the config file")
}
-3
View File
@@ -11,7 +11,6 @@ import (
"time"
"github.com/spf13/viper"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"github.com/chrislusf/seaweedfs/weed/security"
@@ -166,8 +165,6 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
*v.fileSizeLimitMB,
)
go fasthttp.ListenAndServe(":8081", volumeServer.HandleFastHTTP)
// starting grpc server
grpcS := v.startGrpcService(volumeServer)
+5 -5
View File
@@ -63,13 +63,13 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
var dirChunks []*filer_pb.FileChunk
if sub.IsDirectory() {
dirChunks, err = f.doBatchDeleteFolderMetaAndData(ctx, sub, isRecursive, ignoreRecursiveError, shouldDeleteChunks)
chunks = append(chunks, dirChunks...)
} else {
chunks = append(chunks, sub.Chunks...)
}
if err != nil && !ignoreRecursiveError {
return nil, err
}
if shouldDeleteChunks {
chunks = append(chunks, dirChunks...)
}
}
if len(entries) < PaginationSize {
@@ -79,7 +79,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
f.cacheDelDirectory(string(entry.FullPath))
glog.V(3).Infof("deleting directory %v", entry.FullPath)
glog.V(3).Infof("deleting directory %v delete %d chunks: %v", entry.FullPath, len(chunks), shouldDeleteChunks)
if storeDeletionErr := f.store.DeleteFolderChildren(ctx, entry.FullPath); storeDeletionErr != nil {
return nil, fmt.Errorf("filer store delete: %v", storeDeletionErr)
@@ -91,7 +91,7 @@ func (f *Filer) doBatchDeleteFolderMetaAndData(ctx context.Context, entry *Entry
func (f *Filer) doDeleteEntryMetaAndData(ctx context.Context, entry *Entry, shouldDeleteChunks bool) (err error) {
glog.V(3).Infof("deleting entry %v", entry.FullPath)
glog.V(3).Infof("deleting entry %v, delete chunks: %v", entry.FullPath, shouldDeleteChunks)
if storeDeletionErr := f.store.DeleteEntry(ctx, entry.FullPath); storeDeletionErr != nil {
return fmt.Errorf("filer store delete: %v", storeDeletionErr)
+1
View File
@@ -6,5 +6,6 @@ gen:
protoc master.proto --go_out=plugins=grpc:./master_pb
protoc volume_server.proto --go_out=plugins=grpc:./volume_server_pb
protoc filer.proto --go_out=plugins=grpc:./filer_pb
protoc iam.proto --go_out=plugins=grpc:./iam_pb
# protoc filer.proto --java_out=../../other/java/client/src/main/java
cp filer.proto ../../other/java/client/src/main/proto
+50
View File
@@ -0,0 +1,50 @@
syntax = "proto3";
package iam_pb;
option java_package = "seaweedfs.client";
option java_outer_classname = "IamProto";
//////////////////////////////////////////////////
service SeaweedIdentityAccessManagement {
}
//////////////////////////////////////////////////
message S3ApiConfiguration {
repeated Identity identities = 1;
}
message Identity {
string name = 1;
repeated Credential credentials = 2;
repeated string actions = 3;
}
message Credential {
string access_key = 1;
string secret_key = 2;
// uint64 expiration = 3;
// bool is_disabled = 4;
}
/*
message Policy {
repeated Statement statements = 1;
}
message Statement {
repeated Action action = 1;
repeated Resource resource = 2;
}
message Action {
string action = 1;
}
message Resource {
string bucket = 1;
// string path = 2;
}
*/
+174
View File
@@ -0,0 +1,174 @@
// Code generated by protoc-gen-go.
// source: iam.proto
// DO NOT EDIT!
/*
Package iam_pb is a generated protocol buffer package.
It is generated from these files:
iam.proto
It has these top-level messages:
Identities
Identity
Credential
*/
package iam_pb
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type S3ApiConfiguration struct {
Identities []*Identity `protobuf:"bytes,1,rep,name=identities" json:"identities,omitempty"`
}
func (m *S3ApiConfiguration) Reset() { *m = S3ApiConfiguration{} }
func (m *S3ApiConfiguration) String() string { return proto.CompactTextString(m) }
func (*S3ApiConfiguration) ProtoMessage() {}
func (*S3ApiConfiguration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
func (m *S3ApiConfiguration) GetIdentities() []*Identity {
if m != nil {
return m.Identities
}
return nil
}
type Identity struct {
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
Credentials []*Credential `protobuf:"bytes,2,rep,name=credentials" json:"credentials,omitempty"`
Actions []string `protobuf:"bytes,3,rep,name=actions" json:"actions,omitempty"`
}
func (m *Identity) Reset() { *m = Identity{} }
func (m *Identity) String() string { return proto.CompactTextString(m) }
func (*Identity) ProtoMessage() {}
func (*Identity) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
func (m *Identity) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *Identity) GetCredentials() []*Credential {
if m != nil {
return m.Credentials
}
return nil
}
func (m *Identity) GetActions() []string {
if m != nil {
return m.Actions
}
return nil
}
type Credential struct {
AccessKey string `protobuf:"bytes,1,opt,name=access_key,json=accessKey" json:"access_key,omitempty"`
SecretKey string `protobuf:"bytes,2,opt,name=secret_key,json=secretKey" json:"secret_key,omitempty"`
}
func (m *Credential) Reset() { *m = Credential{} }
func (m *Credential) String() string { return proto.CompactTextString(m) }
func (*Credential) ProtoMessage() {}
func (*Credential) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *Credential) GetAccessKey() string {
if m != nil {
return m.AccessKey
}
return ""
}
func (m *Credential) GetSecretKey() string {
if m != nil {
return m.SecretKey
}
return ""
}
func init() {
proto.RegisterType((*S3ApiConfiguration)(nil), "iam_pb.Identities")
proto.RegisterType((*Identity)(nil), "iam_pb.Identity")
proto.RegisterType((*Credential)(nil), "iam_pb.Credential")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for SeaweedIdentityAccessManagement service
type SeaweedIdentityAccessManagementClient interface {
}
type seaweedIdentityAccessManagementClient struct {
cc *grpc.ClientConn
}
func NewSeaweedIdentityAccessManagementClient(cc *grpc.ClientConn) SeaweedIdentityAccessManagementClient {
return &seaweedIdentityAccessManagementClient{cc}
}
// Server API for SeaweedIdentityAccessManagement service
type SeaweedIdentityAccessManagementServer interface {
}
func RegisterSeaweedIdentityAccessManagementServer(s *grpc.Server, srv SeaweedIdentityAccessManagementServer) {
s.RegisterService(&_SeaweedIdentityAccessManagement_serviceDesc, srv)
}
var _SeaweedIdentityAccessManagement_serviceDesc = grpc.ServiceDesc{
ServiceName: "iam_pb.SeaweedIdentityAccessManagement",
HandlerType: (*SeaweedIdentityAccessManagementServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{},
Metadata: "iam.proto",
}
func init() { proto.RegisterFile("iam.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 250 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x4c, 0x90, 0x41, 0x4b, 0xc3, 0x40,
0x10, 0x85, 0x69, 0x23, 0xb5, 0x99, 0x5e, 0xca, 0x9c, 0xf6, 0xa0, 0x18, 0x73, 0xca, 0x29, 0x48,
0xeb, 0x1f, 0xa8, 0x05, 0xa1, 0x16, 0x41, 0xd2, 0x1f, 0x50, 0xa6, 0xdb, 0x69, 0x19, 0xec, 0x6e,
0x42, 0x76, 0x45, 0xf2, 0xef, 0x25, 0xbb, 0x46, 0x7b, 0xdb, 0x7d, 0xdf, 0x7b, 0xb3, 0x3b, 0x0f,
0x52, 0x21, 0x53, 0x36, 0x6d, 0xed, 0x6b, 0x9c, 0x08, 0x99, 0x7d, 0x73, 0xc8, 0x5f, 0x01, 0x77,
0xcb, 0x55, 0x23, 0xeb, 0xda, 0x9e, 0xe4, 0xfc, 0xd5, 0x92, 0x97, 0xda, 0xe2, 0x13, 0x80, 0x1c,
0xd9, 0x7a, 0xf1, 0xc2, 0x4e, 0x8d, 0xb2, 0xa4, 0x98, 0x2d, 0xe6, 0x65, 0x8c, 0x94, 0x9b, 0x48,
0xba, 0xea, 0xca, 0x93, 0x5b, 0x98, 0x0e, 0x3a, 0x22, 0xdc, 0x58, 0x32, 0xac, 0x46, 0xd9, 0xa8,
0x48, 0xab, 0x70, 0xc6, 0x67, 0x98, 0xe9, 0x96, 0x83, 0x83, 0x2e, 0x4e, 0x8d, 0xc3, 0x48, 0x1c,
0x46, 0xae, 0xff, 0x50, 0x75, 0x6d, 0x43, 0x05, 0xb7, 0xa4, 0xfb, 0x1f, 0x39, 0x95, 0x64, 0x49,
0x91, 0x56, 0xc3, 0x35, 0x7f, 0x03, 0xf8, 0x0f, 0xe1, 0x3d, 0x00, 0x69, 0xcd, 0xce, 0xed, 0x3f,
0xb9, 0xfb, 0x7d, 0x37, 0x8d, 0xca, 0x96, 0xbb, 0x1e, 0x3b, 0xd6, 0x2d, 0xfb, 0x80, 0xc7, 0x11,
0x47, 0x65, 0xcb, 0xdd, 0xe2, 0x11, 0x1e, 0x76, 0x4c, 0xdf, 0xcc, 0xc7, 0x61, 0x85, 0x55, 0x88,
0xbe, 0x93, 0xa5, 0x33, 0x1b, 0xb6, 0xfe, 0xe5, 0x0e, 0xe6, 0x2e, 0x5a, 0x4e, 0xae, 0xd4, 0x17,
0xe9, 0xb5, 0xe9, 0x86, 0xcc, 0x47, 0x5f, 0xe6, 0x61, 0x12, 0x3a, 0x5d, 0xfe, 0x04, 0x00, 0x00,
0xff, 0xff, 0x83, 0x4f, 0x61, 0x03, 0x60, 0x01, 0x00, 0x00,
}
+20
View File
@@ -8,6 +8,10 @@ service VolumeServer {
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
rpc BatchDelete (BatchDeleteRequest) returns (BatchDeleteResponse) {
}
rpc FileGet (FileGetRequest) returns (stream FileGetResponse) {
}
rpc VacuumVolumeCheck (VacuumVolumeCheckRequest) returns (VacuumVolumeCheckResponse) {
}
rpc VacuumVolumeCompact (VacuumVolumeCompactRequest) returns (VacuumVolumeCompactResponse) {
@@ -100,6 +104,22 @@ message DeleteResult {
uint32 version = 5;
}
message FileGetRequest {
string file_id = 1;
bool accept_gzip = 2;
}
message FileGetResponse {
bytes data = 1;
uint32 content_length = 2;
string content_type = 3;
uint64 last_modified = 4;
string filename = 5;
string etag = 6;
bool is_gzipped = 7;
map<string, string> headers = 8;
int32 errorCode = 9;
}
message Empty {
}
File diff suppressed because it is too large. Load diff
+162
View File
@@ -0,0 +1,162 @@
package s3api
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"github.com/golang/protobuf/jsonpb"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/pb/iam_pb"
)
type Action string
const (
ACTION_READ = "Read"
ACTION_WRITE = "Write"
ACTION_ADMIN = "Admin"
)
type Iam interface {
Check(f http.HandlerFunc, actions ...Action) http.HandlerFunc
}
type IdentityAccessManagement struct {
identities []*Identity
domain string
}
type Identity struct {
Name string
Credentials []*Credential
Actions []Action
}
type Credential struct {
AccessKey string
SecretKey string
}
func NewIdentityAccessManagement(fileName string, domain string) *IdentityAccessManagement {
iam := &IdentityAccessManagement{
domain: domain,
}
if fileName == "" {
return iam
}
if err := iam.loadS3ApiConfiguration(fileName); err != nil {
glog.Fatalf("fail to load config file %s: %v", fileName, err)
}
return iam
}
func (iam *IdentityAccessManagement) loadS3ApiConfiguration(fileName string) error {
s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
rawData, readErr := ioutil.ReadFile(fileName)
if readErr != nil {
glog.Warningf("fail to read %s : %v", fileName, readErr)
return fmt.Errorf("fail to read %s : %v", fileName, readErr)
}
glog.V(1).Infof("maybeLoadVolumeInfo Unmarshal volume info %v", fileName)
if err := jsonpb.Unmarshal(bytes.NewReader(rawData), s3ApiConfiguration); err != nil {
glog.Warningf("unmarshal error: %v", err)
return fmt.Errorf("unmarshal %s error: %v", fileName, err)
}
for _, ident := range s3ApiConfiguration.Identities {
t := &Identity{
Name: ident.Name,
Credentials: nil,
Actions: nil,
}
for _, action := range ident.Actions {
t.Actions = append(t.Actions, Action(action))
}
for _, cred := range ident.Credentials {
t.Credentials = append(t.Credentials, &Credential{
AccessKey: cred.AccessKey,
SecretKey: cred.SecretKey,
})
}
iam.identities = append(iam.identities, t)
}
return nil
}
func (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {
for _, ident := range iam.identities {
for _, cred := range ident.Credentials {
if cred.AccessKey == accessKey {
return ident, cred, true
}
}
}
return nil, nil, false
}
func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, actions ...Action) http.HandlerFunc {
if len(iam.identities) == 0 {
return f
}
return func(w http.ResponseWriter, r *http.Request) {
errCode := iam.authRequest(r, actions)
if errCode == ErrNone {
f(w, r)
return
}
writeErrorResponse(w, errCode, r.URL)
}
}
// check whether the request has valid access keys
func (iam *IdentityAccessManagement) authRequest(r *http.Request, actions []Action) ErrorCode {
var identity *Identity
var s3Err ErrorCode
switch getRequestAuthType(r) {
case authTypeStreamingSigned:
return ErrNone
case authTypeUnknown:
glog.V(3).Infof("unknown auth type")
return ErrAccessDenied
case authTypePresignedV2, authTypeSignedV2:
glog.V(3).Infof("v2 auth type")
identity, s3Err = iam.isReqAuthenticatedV2(r)
case authTypeSigned, authTypePresigned:
glog.V(3).Infof("v4 auth type")
identity, s3Err = iam.reqSignatureV4Verify(r)
}
glog.V(3).Infof("auth error: %v", s3Err)
if s3Err != ErrNone {
return s3Err
}
glog.V(3).Infof("user name: %v actions: %v", identity.Name, identity.Actions)
if !identity.canDo(actions) {
return ErrAccessDenied
}
return ErrNone
}
func (identity *Identity) canDo(actions []Action) bool {
for _, a := range identity.Actions {
for _, b := range actions {
if a == b {
return true
}
}
}
return false
}
+68
View File
@@ -0,0 +1,68 @@
package s3api
import (
"testing"
"github.com/golang/protobuf/jsonpb"
"github.com/chrislusf/seaweedfs/weed/pb/iam_pb"
)
func TestIdentityListFileFormat(t *testing.T) {
s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
identity1 := &iam_pb.Identity{
Name: "some_name",
Credentials: []*iam_pb.Credential{
{
AccessKey: "some_access_key1",
SecretKey: "some_secret_key2",
},
},
Actions: []string{
ACTION_ADMIN,
ACTION_READ,
ACTION_WRITE,
},
}
identity2 := &iam_pb.Identity{
Name: "some_read_only_user",
Credentials: []*iam_pb.Credential{
{
AccessKey: "some_access_key1",
SecretKey: "some_secret_key1",
},
},
Actions: []string{
ACTION_READ,
},
}
identity3 := &iam_pb.Identity{
Name: "some_normal_user",
Credentials: []*iam_pb.Credential{
{
AccessKey: "some_access_key2",
SecretKey: "some_secret_key2",
},
},
Actions: []string{
ACTION_READ,
ACTION_WRITE,
},
}
s3ApiConfiguration.Identities = append(s3ApiConfiguration.Identities, identity1)
s3ApiConfiguration.Identities = append(s3ApiConfiguration.Identities, identity2)
s3ApiConfiguration.Identities = append(s3ApiConfiguration.Identities, identity3)
m := jsonpb.Marshaler{
EmitDefaults: true,
Indent: " ",
}
text, _ := m.MarshalToString(s3ApiConfiguration)
println(text)
}
+412
View File
@@ -0,0 +1,412 @@
/*
* The following code tries to reverse engineer the Amazon S3 APIs,
* and is mostly copied from minio implementation.
*/
// 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 s3api
import (
"crypto/hmac"
"crypto/sha1"
"crypto/subtle"
"encoding/base64"
"fmt"
"net"
"net/http"
"net/url"
"path"
"sort"
"strconv"
"strings"
"time"
)
// Whitelist resource list that will be used in query string for signature-V2 calculation.
// The list should be alphabetically sorted
var resourceList = []string{
"acl",
"delete",
"lifecycle",
"location",
"logging",
"notification",
"partNumber",
"policy",
"requestPayment",
"response-cache-control",
"response-content-disposition",
"response-content-encoding",
"response-content-language",
"response-content-type",
"response-expires",
"torrent",
"uploadId",
"uploads",
"versionId",
"versioning",
"versions",
"website",
}
// Verify if request has valid AWS Signature Version '2'.
func (iam *IdentityAccessManagement) isReqAuthenticatedV2(r *http.Request) (*Identity, ErrorCode) {
if isRequestSignatureV2(r) {
return iam.doesSignV2Match(r)
}
return iam.doesPresignV2SignatureMatch(r)
}
// Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;
// Signature = Base64( HMAC-SHA1( YourSecretKey, UTF-8-Encoding-Of( StringToSign ) ) );
//
// StringToSign = HTTP-Verb + "\n" +
// Content-Md5 + "\n" +
// Content-Type + "\n" +
// Date + "\n" +
// CanonicalizedProtocolHeaders +
// 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"];
//
// CanonicalizedProtocolHeaders = <described below>
// doesSignV2Match - Verify authorization header with calculated header in accordance with
// - http://docs.aws.amazon.com/AmazonS3/latest/dev/auth-request-sig-v2.html
// returns true if matches, false otherwise. if error is not nil then it is always false
func validateV2AuthHeader(v2Auth string) (accessKey string, errCode ErrorCode) {
if v2Auth == "" {
return "", ErrAuthHeaderEmpty
}
// Verify if the header algorithm is supported or not.
if !strings.HasPrefix(v2Auth, signV2Algorithm) {
return "", ErrSignatureVersionNotSupported
}
// below is V2 Signed Auth header format, splitting on `space` (after the `AWS` string).
// Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature
authFields := strings.Split(v2Auth, " ")
if len(authFields) != 2 {
return "", ErrMissingFields
}
// Then will be splitting on ":", this will seprate `AWSAccessKeyId` and `Signature` string.
keySignFields := strings.Split(strings.TrimSpace(authFields[1]), ":")
if len(keySignFields) != 2 {
return "", ErrMissingFields
}
return keySignFields[0], ErrNone
}
func (iam *IdentityAccessManagement) doesSignV2Match(r *http.Request) (*Identity, ErrorCode) {
v2Auth := r.Header.Get("Authorization")
accessKey, apiError := validateV2AuthHeader(v2Auth)
if apiError != ErrNone {
return nil, apiError
}
// Access credentials.
// Validate if access key id same.
ident, cred, found := iam.lookupByAccessKey(accessKey)
if !found {
return nil, ErrInvalidAccessKeyID
}
// r.RequestURI will have raw encoded URI as sent by the client.
tokens := strings.SplitN(r.RequestURI, "?", 2)
encodedResource := tokens[0]
encodedQuery := ""
if len(tokens) == 2 {
encodedQuery = tokens[1]
}
unescapedQueries, err := unescapeQueries(encodedQuery)
if err != nil {
return nil, ErrInvalidQueryParams
}
encodedResource, err = getResource(encodedResource, r.Host, iam.domain)
if err != nil {
return nil, ErrInvalidRequest
}
prefix := fmt.Sprintf("%s %s:", signV2Algorithm, cred.AccessKey)
if !strings.HasPrefix(v2Auth, prefix) {
return nil, ErrSignatureDoesNotMatch
}
v2Auth = v2Auth[len(prefix):]
expectedAuth := signatureV2(cred, r.Method, encodedResource, strings.Join(unescapedQueries, "&"), r.Header)
if !compareSignatureV2(v2Auth, expectedAuth) {
return nil, ErrSignatureDoesNotMatch
}
return ident, ErrNone
}
// doesPresignV2SignatureMatch - Verify query headers with presigned signature
// - http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#RESTAuthenticationQueryStringAuth
// returns ErrNone if matches. S3 errors otherwise.
func (iam *IdentityAccessManagement) doesPresignV2SignatureMatch(r *http.Request) (*Identity, ErrorCode) {
// r.RequestURI will have raw encoded URI as sent by the client.
tokens := strings.SplitN(r.RequestURI, "?", 2)
encodedResource := tokens[0]
encodedQuery := ""
if len(tokens) == 2 {
encodedQuery = tokens[1]
}
var (
filteredQueries []string
gotSignature string
expires string
accessKey string
err error
)
var unescapedQueries []string
unescapedQueries, err = unescapeQueries(encodedQuery)
if err != nil {
return nil, ErrInvalidQueryParams
}
// Extract the necessary values from presigned query, construct a list of new filtered queries.
for _, query := range unescapedQueries {
keyval := strings.SplitN(query, "=", 2)
if len(keyval) != 2 {
return nil, ErrInvalidQueryParams
}
switch keyval[0] {
case "AWSAccessKeyId":
accessKey = keyval[1]
case "Signature":
gotSignature = keyval[1]
case "Expires":
expires = keyval[1]
default:
filteredQueries = append(filteredQueries, query)
}
}
// Invalid values returns error.
if accessKey == "" || gotSignature == "" || expires == "" {
return nil, ErrInvalidQueryParams
}
// Validate if access key id same.
ident, cred, found := iam.lookupByAccessKey(accessKey)
if !found {
return nil, ErrInvalidAccessKeyID
}
// Make sure the request has not expired.
expiresInt, err := strconv.ParseInt(expires, 10, 64)
if err != nil {
return nil, ErrMalformedExpires
}
// Check if the presigned URL has expired.
if expiresInt < time.Now().UTC().Unix() {
return nil, ErrExpiredPresignRequest
}
encodedResource, err = getResource(encodedResource, r.Host, iam.domain)
if err != nil {
return nil, ErrInvalidRequest
}
expectedSignature := preSignatureV2(cred, r.Method, encodedResource, strings.Join(filteredQueries, "&"), r.Header, expires)
if !compareSignatureV2(gotSignature, expectedSignature) {
return nil, ErrSignatureDoesNotMatch
}
return ident, ErrNone
}
// Escape encodedQuery string into unescaped list of query params, returns error
// if any while unescaping the values.
func unescapeQueries(encodedQuery string) (unescapedQueries []string, err error) {
for _, query := range strings.Split(encodedQuery, "&") {
var unescapedQuery string
unescapedQuery, err = url.QueryUnescape(query)
if err != nil {
return nil, err
}
unescapedQueries = append(unescapedQueries, unescapedQuery)
}
return unescapedQueries, nil
}
// Returns "/bucketName/objectName" for path-style or virtual-host-style requests.
func getResource(path string, host string, domain string) (string, error) {
if domain == "" {
return path, nil
}
// If virtual-host-style is enabled construct the "resource" properly.
if strings.Contains(host, ":") {
// In bucket.mydomain.com:9000, strip out :9000
var err error
if host, _, err = net.SplitHostPort(host); err != nil {
return "", err
}
}
if !strings.HasSuffix(host, "."+domain) {
return path, nil
}
bucket := strings.TrimSuffix(host, "."+domain)
return "/" + pathJoin(bucket, path), nil
}
// pathJoin - like path.Join() but retains trailing "/" of the last element
func pathJoin(elem ...string) string {
trailingSlash := ""
if len(elem) > 0 {
if strings.HasSuffix(elem[len(elem)-1], "/") {
trailingSlash = "/"
}
}
return path.Join(elem...) + trailingSlash
}
// Return the signature v2 of a given request.
func signatureV2(cred *Credential, method string, encodedResource string, encodedQuery string, headers http.Header) string {
stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, "")
signature := calculateSignatureV2(stringToSign, cred.SecretKey)
return signature
}
// Return string to sign under two different conditions.
// - if expires string is set then string to sign includes date instead of the Date header.
// - if expires string is empty then string to sign includes date header instead.
func getStringToSignV2(method string, encodedResource, encodedQuery string, headers http.Header, expires string) string {
canonicalHeaders := canonicalizedAmzHeadersV2(headers)
if len(canonicalHeaders) > 0 {
canonicalHeaders += "\n"
}
date := expires // Date is set to expires date for presign operations.
if date == "" {
// If expires date is empty then request header Date is used.
date = headers.Get("Date")
}
// From the Amazon docs:
//
// StringToSign = HTTP-Verb + "\n" +
// Content-Md5 + "\n" +
// Content-Type + "\n" +
// Date/Expires + "\n" +
// CanonicalizedProtocolHeaders +
// CanonicalizedResource;
stringToSign := strings.Join([]string{
method,
headers.Get("Content-MD5"),
headers.Get("Content-Type"),
date,
canonicalHeaders,
}, "\n")
return stringToSign + canonicalizedResourceV2(encodedResource, encodedQuery)
}
// Return canonical resource string.
func canonicalizedResourceV2(encodedResource, encodedQuery string) string {
queries := strings.Split(encodedQuery, "&")
keyval := make(map[string]string)
for _, query := range queries {
key := query
val := ""
index := strings.Index(query, "=")
if index != -1 {
key = query[:index]
val = query[index+1:]
}
keyval[key] = val
}
var canonicalQueries []string
for _, key := range resourceList {
val, ok := keyval[key]
if !ok {
continue
}
if val == "" {
canonicalQueries = append(canonicalQueries, key)
continue
}
canonicalQueries = append(canonicalQueries, key+"="+val)
}
// The queries will be already sorted as resourceList is sorted, if canonicalQueries
// is empty strings.Join returns empty.
canonicalQuery := strings.Join(canonicalQueries, "&")
if canonicalQuery != "" {
return encodedResource + "?" + canonicalQuery
}
return encodedResource
}
// Return canonical headers.
func canonicalizedAmzHeadersV2(headers http.Header) string {
var keys []string
keyval := make(map[string]string)
for key := range headers {
lkey := strings.ToLower(key)
if !strings.HasPrefix(lkey, "x-amz-") {
continue
}
keys = append(keys, lkey)
keyval[lkey] = strings.Join(headers[key], ",")
}
sort.Strings(keys)
var canonicalHeaders []string
for _, key := range keys {
canonicalHeaders = append(canonicalHeaders, key+":"+keyval[key])
}
return strings.Join(canonicalHeaders, "\n")
}
func calculateSignatureV2(stringToSign string, secret string) string {
hm := hmac.New(sha1.New, []byte(secret))
hm.Write([]byte(stringToSign))
return base64.StdEncoding.EncodeToString(hm.Sum(nil))
}
// compareSignatureV2 returns true if and only if both signatures
// are equal. The signatures are expected to be base64 encoded strings
// according to the AWS S3 signature V2 spec.
func compareSignatureV2(sig1, sig2 string) bool {
// Decode signature string to binary byte-sequence representation is required
// as Base64 encoding of a value is not unique:
// For example "aGVsbG8=" and "aGVsbG8=\r" will result in the same byte slice.
signature1, err := base64.StdEncoding.DecodeString(sig1)
if err != nil {
return false
}
signature2, err := base64.StdEncoding.DecodeString(sig2)
if err != nil {
return false
}
return subtle.ConstantTimeCompare(signature1, signature2) == 1
}
// Return signature-v2 for the presigned request.
func preSignatureV2(cred *Credential, method string, encodedResource string, encodedQuery string, headers http.Header, expires string) string {
stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, expires)
return calculateSignatureV2(stringToSign, cred.SecretKey)
}
+720
View File
@@ -0,0 +1,720 @@
/*
* The following code tries to reverse engineer the Amazon S3 APIs,
* and is mostly copied from minio implementation.
*/
// 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 s3api
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
)
func (iam *IdentityAccessManagement) reqSignatureV4Verify(r *http.Request) (*Identity, ErrorCode) {
sha256sum := getContentSha256Cksum(r)
switch {
case isRequestSignatureV4(r):
return iam.doesSignatureMatch(sha256sum, r)
case isRequestPresignedSignatureV4(r):
return iam.doesPresignedSignatureMatch(sha256sum, r)
}
return nil, ErrAccessDenied
}
// Streaming AWS Signature Version '4' constants.
const (
emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
streamingContentSHA256 = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
signV4ChunkedAlgorithm = "AWS4-HMAC-SHA256-PAYLOAD"
// http Header "x-amz-content-sha256" == "UNSIGNED-PAYLOAD" indicates that the
// client did not calculate sha256 of the payload.
unsignedPayload = "UNSIGNED-PAYLOAD"
)
// Returns SHA256 for calculating canonical-request.
func getContentSha256Cksum(r *http.Request) string {
var (
defaultSha256Cksum string
v []string
ok bool
)
// For a presigned request we look at the query param for sha256.
if isRequestPresignedSignatureV4(r) {
// X-Amz-Content-Sha256, if not set in presigned requests, checksum
// will default to 'UNSIGNED-PAYLOAD'.
defaultSha256Cksum = unsignedPayload
v, ok = r.URL.Query()["X-Amz-Content-Sha256"]
if !ok {
v, ok = r.Header["X-Amz-Content-Sha256"]
}
} else {
// X-Amz-Content-Sha256, if not set in signed requests, checksum
// will default to sha256([]byte("")).
defaultSha256Cksum = emptySHA256
v, ok = r.Header["X-Amz-Content-Sha256"]
}
// We found 'X-Amz-Content-Sha256' return the captured value.
if ok {
return v[0]
}
// We couldn't find 'X-Amz-Content-Sha256'.
return defaultSha256Cksum
}
// Verify authorization header - http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
func (iam *IdentityAccessManagement) doesSignatureMatch(hashedPayload string, r *http.Request) (*Identity, ErrorCode) {
// Copy request.
req := *r
// Save authorization header.
v4Auth := req.Header.Get("Authorization")
// Parse signature version '4' header.
signV4Values, err := parseSignV4(v4Auth)
if err != ErrNone {
return nil, err
}
// Extract all the signed headers along with its values.
extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
if errCode != ErrNone {
return nil, errCode
}
// Verify if the access key id matches.
identity, cred, found := iam.lookupByAccessKey(signV4Values.Credential.accessKey)
if !found {
return nil, ErrInvalidAccessKeyID
}
// Extract date, if not present throw error.
var date string
if date = req.Header.Get(http.CanonicalHeaderKey("X-Amz-Date")); date == "" {
if date = r.Header.Get("Date"); date == "" {
return nil, ErrMissingDateHeader
}
}
// Parse date header.
t, e := time.Parse(iso8601Format, date)
if e != nil {
return nil, ErrMalformedDate
}
// Query string.
queryStr := req.URL.Query().Encode()
// Get canonical request.
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, queryStr, req.URL.Path, req.Method)
// Get string to sign from canonical request.
stringToSign := getStringToSign(canonicalRequest, t, signV4Values.Credential.getScope())
// Get hmac signing key.
signingKey := getSigningKey(cred.SecretKey, signV4Values.Credential.scope.date, signV4Values.Credential.scope.region)
// Calculate signature.
newSignature := getSignature(signingKey, stringToSign)
// Verify if signature match.
if !compareSignatureV4(newSignature, signV4Values.Signature) {
return nil, ErrSignatureDoesNotMatch
}
// Return error none.
return identity, ErrNone
}
// credentialHeader data type represents structured form of Credential
// string from authorization header.
type credentialHeader struct {
accessKey string
scope struct {
date time.Time
region string
service string
request string
}
}
// signValues data type represents structured form of AWS Signature V4 header.
type signValues struct {
Credential credentialHeader
SignedHeaders []string
Signature string
}
// Return scope string.
func (c credentialHeader) getScope() string {
return strings.Join([]string{
c.scope.date.Format(yyyymmdd),
c.scope.region,
c.scope.service,
c.scope.request,
}, "/")
}
// Authorization: algorithm Credential=accessKeyID/credScope, \
// SignedHeaders=signedHeaders, Signature=signature
//
func parseSignV4(v4Auth string) (sv signValues, aec ErrorCode) {
// Replace all spaced strings, some clients can send spaced
// parameters and some won't. So we pro-actively remove any spaces
// to make parsing easier.
v4Auth = strings.Replace(v4Auth, " ", "", -1)
if v4Auth == "" {
return sv, ErrAuthHeaderEmpty
}
// Verify if the header algorithm is supported or not.
if !strings.HasPrefix(v4Auth, signV4Algorithm) {
return sv, ErrSignatureVersionNotSupported
}
// Strip off the Algorithm prefix.
v4Auth = strings.TrimPrefix(v4Auth, signV4Algorithm)
authFields := strings.Split(strings.TrimSpace(v4Auth), ",")
if len(authFields) != 3 {
return sv, ErrMissingFields
}
// Initialize signature version '4' structured header.
signV4Values := signValues{}
var err ErrorCode
// Save credentail values.
signV4Values.Credential, err = parseCredentialHeader(authFields[0])
if err != ErrNone {
return sv, err
}
// Save signed headers.
signV4Values.SignedHeaders, err = parseSignedHeader(authFields[1])
if err != ErrNone {
return sv, err
}
// Save signature.
signV4Values.Signature, err = parseSignature(authFields[2])
if err != ErrNone {
return sv, err
}
// Return the structure here.
return signV4Values, ErrNone
}
// parse credentialHeader string into its structured form.
func parseCredentialHeader(credElement string) (ch credentialHeader, aec ErrorCode) {
creds := strings.Split(strings.TrimSpace(credElement), "=")
if len(creds) != 2 {
return ch, ErrMissingFields
}
if creds[0] != "Credential" {
return ch, ErrMissingCredTag
}
credElements := strings.Split(strings.TrimSpace(creds[1]), "/")
if len(credElements) != 5 {
return ch, ErrCredMalformed
}
// Save access key id.
cred := credentialHeader{
accessKey: credElements[0],
}
var e error
cred.scope.date, e = time.Parse(yyyymmdd, credElements[1])
if e != nil {
return ch, ErrMalformedCredentialDate
}
cred.scope.region = credElements[2]
cred.scope.service = credElements[3] // "s3"
cred.scope.request = credElements[4] // "aws4_request"
return cred, ErrNone
}
// Parse slice of signed headers from signed headers tag.
func parseSignedHeader(signedHdrElement string) ([]string, ErrorCode) {
signedHdrFields := strings.Split(strings.TrimSpace(signedHdrElement), "=")
if len(signedHdrFields) != 2 {
return nil, ErrMissingFields
}
if signedHdrFields[0] != "SignedHeaders" {
return nil, ErrMissingSignHeadersTag
}
if signedHdrFields[1] == "" {
return nil, ErrMissingFields
}
signedHeaders := strings.Split(signedHdrFields[1], ";")
return signedHeaders, ErrNone
}
// Parse signature from signature tag.
func parseSignature(signElement string) (string, ErrorCode) {
signFields := strings.Split(strings.TrimSpace(signElement), "=")
if len(signFields) != 2 {
return "", ErrMissingFields
}
if signFields[0] != "Signature" {
return "", ErrMissingSignTag
}
if signFields[1] == "" {
return "", ErrMissingFields
}
signature := signFields[1]
return signature, ErrNone
}
// check query headers with presigned signature
// - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
func (iam *IdentityAccessManagement) doesPresignedSignatureMatch(hashedPayload string, r *http.Request) (*Identity, ErrorCode) {
// Copy request
req := *r
// Parse request query string.
pSignValues, err := parsePreSignV4(req.URL.Query())
if err != ErrNone {
return nil, err
}
// Verify if the access key id matches.
identity, cred, found := iam.lookupByAccessKey(pSignValues.Credential.accessKey)
if !found {
return nil, ErrInvalidAccessKeyID
}
// Extract all the signed headers along with its values.
extractedSignedHeaders, errCode := extractSignedHeaders(pSignValues.SignedHeaders, r)
if errCode != ErrNone {
return nil, errCode
}
// Construct new query.
query := make(url.Values)
if req.URL.Query().Get("X-Amz-Content-Sha256") != "" {
query.Set("X-Amz-Content-Sha256", hashedPayload)
}
query.Set("X-Amz-Algorithm", signV4Algorithm)
now := time.Now().UTC()
// If the host which signed the request is slightly ahead in time (by less than globalMaxSkewTime) the
// request should still be allowed.
if pSignValues.Date.After(now.Add(15 * time.Minute)) {
return nil, ErrRequestNotReadyYet
}
if now.Sub(pSignValues.Date) > pSignValues.Expires {
return nil, ErrExpiredPresignRequest
}
// Save the date and expires.
t := pSignValues.Date
expireSeconds := int(pSignValues.Expires / time.Second)
// Construct the query.
query.Set("X-Amz-Date", t.Format(iso8601Format))
query.Set("X-Amz-Expires", strconv.Itoa(expireSeconds))
query.Set("X-Amz-SignedHeaders", getSignedHeaders(extractedSignedHeaders))
query.Set("X-Amz-Credential", cred.AccessKey+"/"+getScope(t, pSignValues.Credential.scope.region))
// Save other headers available in the request parameters.
for k, v := range req.URL.Query() {
// Handle the metadata in presigned put query string
if strings.Contains(strings.ToLower(k), "x-amz-meta-") {
query.Set(k, v[0])
}
if strings.HasPrefix(strings.ToLower(k), "x-amz") {
continue
}
query[k] = v
}
// Get the encoded query.
encodedQuery := query.Encode()
// Verify if date query is same.
if req.URL.Query().Get("X-Amz-Date") != query.Get("X-Amz-Date") {
return nil, ErrSignatureDoesNotMatch
}
// Verify if expires query is same.
if req.URL.Query().Get("X-Amz-Expires") != query.Get("X-Amz-Expires") {
return nil, ErrSignatureDoesNotMatch
}
// Verify if signed headers query is same.
if req.URL.Query().Get("X-Amz-SignedHeaders") != query.Get("X-Amz-SignedHeaders") {
return nil, ErrSignatureDoesNotMatch
}
// Verify if credential query is same.
if req.URL.Query().Get("X-Amz-Credential") != query.Get("X-Amz-Credential") {
return nil, ErrSignatureDoesNotMatch
}
// Verify if sha256 payload query is same.
if req.URL.Query().Get("X-Amz-Content-Sha256") != "" {
if req.URL.Query().Get("X-Amz-Content-Sha256") != query.Get("X-Amz-Content-Sha256") {
return nil, ErrContentSHA256Mismatch
}
}
/// Verify finally if signature is same.
// Get canonical request.
presignedCanonicalReq := getCanonicalRequest(extractedSignedHeaders, hashedPayload, encodedQuery, req.URL.Path, req.Method)
// Get string to sign from canonical request.
presignedStringToSign := getStringToSign(presignedCanonicalReq, t, pSignValues.Credential.getScope())
// Get hmac presigned signing key.
presignedSigningKey := getSigningKey(cred.SecretKey, pSignValues.Credential.scope.date, pSignValues.Credential.scope.region)
// Get new signature.
newSignature := getSignature(presignedSigningKey, presignedStringToSign)
// Verify signature.
if !compareSignatureV4(req.URL.Query().Get("X-Amz-Signature"), newSignature) {
return nil, ErrSignatureDoesNotMatch
}
return identity, ErrNone
}
func contains(list []string, elem string) bool {
for _, t := range list {
if t == elem {
return true
}
}
return false
}
// preSignValues data type represents structued form of AWS Signature V4 query string.
type preSignValues struct {
signValues
Date time.Time
Expires time.Duration
}
// Parses signature version '4' query string of the following form.
//
// querystring = X-Amz-Algorithm=algorithm
// querystring += &X-Amz-Credential= urlencode(accessKey + '/' + credential_scope)
// querystring += &X-Amz-Date=date
// querystring += &X-Amz-Expires=timeout interval
// querystring += &X-Amz-SignedHeaders=signed_headers
// querystring += &X-Amz-Signature=signature
//
// verifies if any of the necessary query params are missing in the presigned request.
func doesV4PresignParamsExist(query url.Values) ErrorCode {
v4PresignQueryParams := []string{"X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Signature", "X-Amz-Date", "X-Amz-SignedHeaders", "X-Amz-Expires"}
for _, v4PresignQueryParam := range v4PresignQueryParams {
if _, ok := query[v4PresignQueryParam]; !ok {
return ErrInvalidQueryParams
}
}
return ErrNone
}
// Parses all the presigned signature values into separate elements.
func parsePreSignV4(query url.Values) (psv preSignValues, aec ErrorCode) {
var err ErrorCode
// verify whether the required query params exist.
err = doesV4PresignParamsExist(query)
if err != ErrNone {
return psv, err
}
// Verify if the query algorithm is supported or not.
if query.Get("X-Amz-Algorithm") != signV4Algorithm {
return psv, ErrInvalidQuerySignatureAlgo
}
// Initialize signature version '4' structured header.
preSignV4Values := preSignValues{}
// Save credential.
preSignV4Values.Credential, err = parseCredentialHeader("Credential=" + query.Get("X-Amz-Credential"))
if err != ErrNone {
return psv, err
}
var e error
// Save date in native time.Time.
preSignV4Values.Date, e = time.Parse(iso8601Format, query.Get("X-Amz-Date"))
if e != nil {
return psv, ErrMalformedPresignedDate
}
// Save expires in native time.Duration.
preSignV4Values.Expires, e = time.ParseDuration(query.Get("X-Amz-Expires") + "s")
if e != nil {
return psv, ErrMalformedExpires
}
if preSignV4Values.Expires < 0 {
return psv, ErrNegativeExpires
}
// Check if Expiry time is less than 7 days (value in seconds).
if preSignV4Values.Expires.Seconds() > 604800 {
return psv, ErrMaximumExpires
}
// Save signed headers.
preSignV4Values.SignedHeaders, err = parseSignedHeader("SignedHeaders=" + query.Get("X-Amz-SignedHeaders"))
if err != ErrNone {
return psv, err
}
// Save signature.
preSignV4Values.Signature, err = parseSignature("Signature=" + query.Get("X-Amz-Signature"))
if err != ErrNone {
return psv, err
}
// Return structed form of signature query string.
return preSignV4Values, ErrNone
}
// extractSignedHeaders extract signed headers from Authorization header
func extractSignedHeaders(signedHeaders []string, r *http.Request) (http.Header, ErrorCode) {
reqHeaders := r.Header
// find whether "host" is part of list of signed headers.
// if not return ErrUnsignedHeaders. "host" is mandatory.
if !contains(signedHeaders, "host") {
return nil, ErrUnsignedHeaders
}
extractedSignedHeaders := make(http.Header)
for _, header := range signedHeaders {
// `host` will not be found in the headers, can be found in r.Host.
// but its alway necessary that the list of signed headers containing host in it.
val, ok := reqHeaders[http.CanonicalHeaderKey(header)]
if ok {
for _, enc := range val {
extractedSignedHeaders.Add(header, enc)
}
continue
}
switch header {
case "expect":
// Golang http server strips off 'Expect' header, if the
// client sent this as part of signed headers we need to
// handle otherwise we would see a signature mismatch.
// `aws-cli` sets this as part of signed headers.
//
// According to
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20
// Expect header is always of form:
//
// Expect = "Expect" ":" 1#expectation
// expectation = "100-continue" | expectation-extension
//
// So it safe to assume that '100-continue' is what would
// be sent, for the time being keep this work around.
// Adding a *TODO* to remove this later when Golang server
// doesn't filter out the 'Expect' header.
extractedSignedHeaders.Set(header, "100-continue")
case "host":
// Go http server removes "host" from Request.Header
extractedSignedHeaders.Set(header, r.Host)
case "transfer-encoding":
for _, enc := range r.TransferEncoding {
extractedSignedHeaders.Add(header, enc)
}
case "content-length":
// Signature-V4 spec excludes Content-Length from signed headers list for signature calculation.
// But some clients deviate from this rule. Hence we consider Content-Length for signature
// calculation to be compatible with such clients.
extractedSignedHeaders.Set(header, strconv.FormatInt(r.ContentLength, 10))
default:
return nil, ErrUnsignedHeaders
}
}
return extractedSignedHeaders, ErrNone
}
// getSignedHeaders generate a string i.e alphabetically sorted, semicolon-separated list of lowercase request header names
func getSignedHeaders(signedHeaders http.Header) string {
var headers []string
for k := range signedHeaders {
headers = append(headers, strings.ToLower(k))
}
sort.Strings(headers)
return strings.Join(headers, ";")
}
// getScope generate a string of a specific date, an AWS region, and a service.
func getScope(t time.Time, region string) string {
scope := strings.Join([]string{
t.Format(yyyymmdd),
region,
"s3",
"aws4_request",
}, "/")
return scope
}
// getCanonicalRequest generate a canonical request of style
//
// canonicalRequest =
// <HTTPMethod>\n
// <CanonicalURI>\n
// <CanonicalQueryString>\n
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
//
func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string) string {
rawQuery := strings.Replace(queryStr, "+", "%20", -1)
encodedPath := encodePath(urlPath)
canonicalRequest := strings.Join([]string{
method,
encodedPath,
rawQuery,
getCanonicalHeaders(extractedSignedHeaders),
getSignedHeaders(extractedSignedHeaders),
payload,
}, "\n")
return canonicalRequest
}
// getStringToSign a string based on selected query values.
func getStringToSign(canonicalRequest string, t time.Time, scope string) string {
stringToSign := signV4Algorithm + "\n" + t.Format(iso8601Format) + "\n"
stringToSign = stringToSign + scope + "\n"
canonicalRequestBytes := sha256.Sum256([]byte(canonicalRequest))
stringToSign = stringToSign + hex.EncodeToString(canonicalRequestBytes[:])
return stringToSign
}
// sumHMAC calculate hmac between two input byte array.
func sumHMAC(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}
// getSigningKey hmac seed to calculate final signature.
func getSigningKey(secretKey string, t time.Time, region string) []byte {
date := sumHMAC([]byte("AWS4"+secretKey), []byte(t.Format(yyyymmdd)))
regionBytes := sumHMAC(date, []byte(region))
service := sumHMAC(regionBytes, []byte("s3"))
signingKey := sumHMAC(service, []byte("aws4_request"))
return signingKey
}
// getSignature final signature in hexadecimal form.
func getSignature(signingKey []byte, stringToSign string) string {
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
}
// getCanonicalHeaders generate a list of request headers with their values
func getCanonicalHeaders(signedHeaders http.Header) string {
var headers []string
vals := make(http.Header)
for k, vv := range signedHeaders {
headers = append(headers, strings.ToLower(k))
vals[strings.ToLower(k)] = vv
}
sort.Strings(headers)
var buf bytes.Buffer
for _, k := range headers {
buf.WriteString(k)
buf.WriteByte(':')
for idx, v := range vals[k] {
if idx > 0 {
buf.WriteByte(',')
}
buf.WriteString(signV4TrimAll(v))
}
buf.WriteByte('\n')
}
return buf.String()
}
// Trim leading and trailing spaces and replace sequential spaces with one space, following Trimall()
// in http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
func signV4TrimAll(input string) string {
// Compress adjacent spaces (a space is determined by
// unicode.IsSpace() internally here) to one space and return
return strings.Join(strings.Fields(input), " ")
}
// if object matches reserved string, no need to encode them
var reservedObjectNames = regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$")
// EncodePath 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 encodePath(pathName string) string {
if reservedObjectNames.MatchString(pathName) {
return pathName
}
var encodedPathname string
for _, s := range pathName {
if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
encodedPathname = encodedPathname + string(s)
continue
}
switch s {
case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
encodedPathname = encodedPathname + string(s)
continue
default:
len := utf8.RuneLen(s)
if len < 0 {
// if utf8 cannot convert return the same string as is
return pathName
}
u := make([]byte, len)
utf8.EncodeRune(u, s)
for _, r := range u {
hex := hex.EncodeToString([]byte{r})
encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
}
}
}
return encodedPathname
}
// compareSignatureV4 returns true if and only if both signatures
// are equal. The signatures are expected to be HEX encoded strings
// according to the AWS S3 signature V4 spec.
func compareSignatureV4(sig1, sig2 string) bool {
// The CTC using []byte(str) works because the hex encoding
// is unique for a sequence of bytes. See also compareSignatureV2.
return subtle.ConstantTimeCompare([]byte(sig1), []byte(sig2)) == 1
}
+419
View File
@@ -0,0 +1,419 @@
package s3api
import (
"bytes"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"testing"
"time"
"unicode/utf8"
)
// TestIsRequestPresignedSignatureV4 - Test validates the logic for presign signature verision v4 detection.
func TestIsRequestPresignedSignatureV4(t *testing.T) {
testCases := []struct {
inputQueryKey string
inputQueryValue string
expectedResult bool
}{
// Test case - 1.
// Test case with query key ""X-Amz-Credential" set.
{"", "", false},
// Test case - 2.
{"X-Amz-Credential", "", true},
// Test case - 3.
{"X-Amz-Content-Sha256", "", false},
}
for i, testCase := range testCases {
// creating an input HTTP request.
// Only the query parameters are relevant for this particular test.
inputReq, err := http.NewRequest("GET", "http://example.com", nil)
if err != nil {
t.Fatalf("Error initializing input HTTP request: %v", err)
}
q := inputReq.URL.Query()
q.Add(testCase.inputQueryKey, testCase.inputQueryValue)
inputReq.URL.RawQuery = q.Encode()
actualResult := isRequestPresignedSignatureV4(inputReq)
if testCase.expectedResult != actualResult {
t.Errorf("Test %d: Expected the result to `%v`, but instead got `%v`", i+1, testCase.expectedResult, actualResult)
}
}
}
// Tests is requested authenticated function, tests replies for s3 errors.
func TestIsReqAuthenticated(t *testing.T) {
iam := NewIdentityAccessManagement("", "")
iam.identities = []*Identity{
{
Name: "someone",
Credentials: []*Credential{
{
AccessKey: "access_key_1",
SecretKey: "secret_key_1",
},
},
Actions: nil,
},
}
// List of test cases for validating http request authentication.
testCases := []struct {
req *http.Request
s3Error ErrorCode
}{
// When request is unsigned, access denied is returned.
{mustNewRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrAccessDenied},
// When request is properly signed, error is none.
{mustNewSignedRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrNone},
}
// Validates all testcases.
for i, testCase := range testCases {
if _, s3Error := iam.reqSignatureV4Verify(testCase.req); s3Error != testCase.s3Error {
ioutil.ReadAll(testCase.req.Body)
t.Fatalf("Test %d: Unexpected S3 error: want %d - got %d", i, testCase.s3Error, s3Error)
}
}
}
func TestCheckAdminRequestAuthType(t *testing.T) {
iam := NewIdentityAccessManagement("", "")
iam.identities = []*Identity{
{
Name: "someone",
Credentials: []*Credential{
{
AccessKey: "access_key_1",
SecretKey: "secret_key_1",
},
},
Actions: nil,
},
}
testCases := []struct {
Request *http.Request
ErrCode ErrorCode
}{
{Request: mustNewRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrCode: ErrAccessDenied},
{Request: mustNewSignedRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrCode: ErrNone},
{Request: mustNewPresignedRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrCode: ErrNone},
}
for i, testCase := range testCases {
if _, s3Error := iam.reqSignatureV4Verify(testCase.Request); s3Error != testCase.ErrCode {
t.Errorf("Test %d: Unexpected s3error returned wanted %d, got %d", i, testCase.ErrCode, s3Error)
}
}
}
// Provides a fully populated http request instance, fails otherwise.
func mustNewRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
req, err := newTestRequest(method, urlStr, contentLength, body)
if err != nil {
t.Fatalf("Unable to initialize new http request %s", err)
}
return req
}
// This is similar to mustNewRequest but additionally the request
// is signed with AWS Signature V4, fails if not able to do so.
func mustNewSignedRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
req := mustNewRequest(method, urlStr, contentLength, body, t)
cred := &Credential{"access_key_1", "secret_key_1"}
if err := signRequestV4(req, cred.AccessKey, cred.SecretKey); err != nil {
t.Fatalf("Unable to inititalized new signed http request %s", err)
}
return req
}
// This is similar to mustNewRequest but additionally the request
// is presigned with AWS Signature V4, fails if not able to do so.
func mustNewPresignedRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
req := mustNewRequest(method, urlStr, contentLength, body, t)
cred := &Credential{"access_key_1", "secret_key_1"}
if err := preSignV4(req, cred.AccessKey, cred.SecretKey, int64(10*time.Minute.Seconds())); err != nil {
t.Fatalf("Unable to inititalized new signed http request %s", err)
}
return req
}
// Returns new HTTP request object.
func newTestRequest(method, urlStr string, contentLength int64, body io.ReadSeeker) (*http.Request, error) {
if method == "" {
method = "POST"
}
// Save for subsequent use
var hashedPayload string
var md5Base64 string
switch {
case body == nil:
hashedPayload = getSHA256Hash([]byte{})
default:
payloadBytes, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
hashedPayload = getSHA256Hash(payloadBytes)
md5Base64 = getMD5HashBase64(payloadBytes)
}
// Seek back to beginning.
if body != nil {
body.Seek(0, 0)
} else {
body = bytes.NewReader([]byte(""))
}
req, err := http.NewRequest(method, urlStr, body)
if err != nil {
return nil, err
}
if md5Base64 != "" {
req.Header.Set("Content-Md5", md5Base64)
}
req.Header.Set("x-amz-content-sha256", hashedPayload)
// Add Content-Length
req.ContentLength = contentLength
return req, nil
}
// getSHA256Hash returns SHA-256 hash in hex encoding of given data.
func getSHA256Hash(data []byte) string {
return hex.EncodeToString(getSHA256Sum(data))
}
// getMD5HashBase64 returns MD5 hash in base64 encoding of given data.
func getMD5HashBase64(data []byte) string {
return base64.StdEncoding.EncodeToString(getMD5Sum(data))
}
// getSHA256Hash returns SHA-256 sum of given data.
func getSHA256Sum(data []byte) []byte {
hash := sha256.New()
hash.Write(data)
return hash.Sum(nil)
}
// getMD5Sum returns MD5 sum of given data.
func getMD5Sum(data []byte) []byte {
hash := md5.New()
hash.Write(data)
return hash.Sum(nil)
}
// getMD5Hash returns MD5 hash in hex encoding of given data.
func getMD5Hash(data []byte) string {
return hex.EncodeToString(getMD5Sum(data))
}
var ignoredHeaders = map[string]bool{
"Authorization": true,
"Content-Type": true,
"Content-Length": true,
"User-Agent": true,
}
// Sign given request using Signature V4.
func signRequestV4(req *http.Request, accessKey, secretKey string) error {
// Get hashed payload.
hashedPayload := req.Header.Get("x-amz-content-sha256")
if hashedPayload == "" {
return fmt.Errorf("Invalid hashed payload")
}
currTime := time.Now()
// Set x-amz-date.
req.Header.Set("x-amz-date", currTime.Format(iso8601Format))
// Get header map.
headerMap := make(map[string][]string)
for k, vv := range req.Header {
// If request header key is not in ignored headers, then add it.
if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; !ok {
headerMap[strings.ToLower(k)] = vv
}
}
// Get header keys.
headers := []string{"host"}
for k := range headerMap {
headers = append(headers, k)
}
sort.Strings(headers)
region := "us-east-1"
// Get canonical headers.
var buf bytes.Buffer
for _, k := range headers {
buf.WriteString(k)
buf.WriteByte(':')
switch {
case k == "host":
buf.WriteString(req.URL.Host)
fallthrough
default:
for idx, v := range headerMap[k] {
if idx > 0 {
buf.WriteByte(',')
}
buf.WriteString(v)
}
buf.WriteByte('\n')
}
}
canonicalHeaders := buf.String()
// Get signed headers.
signedHeaders := strings.Join(headers, ";")
// Get canonical query string.
req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1)
// Get canonical URI.
canonicalURI := EncodePath(req.URL.Path)
// Get canonical request.
// canonicalRequest =
// <HTTPMethod>\n
// <CanonicalURI>\n
// <CanonicalQueryString>\n
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
//
canonicalRequest := strings.Join([]string{
req.Method,
canonicalURI,
req.URL.RawQuery,
canonicalHeaders,
signedHeaders,
hashedPayload,
}, "\n")
// Get scope.
scope := strings.Join([]string{
currTime.Format(yyyymmdd),
region,
"s3",
"aws4_request",
}, "/")
stringToSign := "AWS4-HMAC-SHA256" + "\n" + currTime.Format(iso8601Format) + "\n"
stringToSign = stringToSign + scope + "\n"
stringToSign = stringToSign + getSHA256Hash([]byte(canonicalRequest))
date := sumHMAC([]byte("AWS4"+secretKey), []byte(currTime.Format(yyyymmdd)))
regionHMAC := sumHMAC(date, []byte(region))
service := sumHMAC(regionHMAC, []byte("s3"))
signingKey := sumHMAC(service, []byte("aws4_request"))
signature := hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
// final Authorization header
parts := []string{
"AWS4-HMAC-SHA256" + " Credential=" + accessKey + "/" + scope,
"SignedHeaders=" + signedHeaders,
"Signature=" + signature,
}
auth := strings.Join(parts, ", ")
req.Header.Set("Authorization", auth)
return nil
}
// preSignV4 presign the request, in accordance with
// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html.
func preSignV4(req *http.Request, accessKeyID, secretAccessKey string, expires int64) error {
// Presign is not needed for anonymous credentials.
if accessKeyID == "" || secretAccessKey == "" {
return errors.New("Presign cannot be generated without access and secret keys")
}
region := "us-east-1"
date := time.Now().UTC()
scope := getScope(date, region)
credential := fmt.Sprintf("%s/%s", accessKeyID, scope)
// Set URL query.
query := req.URL.Query()
query.Set("X-Amz-Algorithm", signV4Algorithm)
query.Set("X-Amz-Date", date.Format(iso8601Format))
query.Set("X-Amz-Expires", strconv.FormatInt(expires, 10))
query.Set("X-Amz-SignedHeaders", "host")
query.Set("X-Amz-Credential", credential)
query.Set("X-Amz-Content-Sha256", unsignedPayload)
// "host" is the only header required to be signed for Presigned URLs.
extractedSignedHeaders := make(http.Header)
extractedSignedHeaders.Set("host", req.Host)
queryStr := strings.Replace(query.Encode(), "+", "%20", -1)
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, unsignedPayload, queryStr, req.URL.Path, req.Method)
stringToSign := getStringToSign(canonicalRequest, date, scope)
signingKey := getSigningKey(secretAccessKey, date, region)
signature := getSignature(signingKey, stringToSign)
req.URL.RawQuery = query.Encode()
// Add signature header to RawQuery.
req.URL.RawQuery += "&X-Amz-Signature=" + url.QueryEscape(signature)
// Construct the final presigned URL.
return nil
}
// EncodePath 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 EncodePath(pathName string) string {
if reservedObjectNames.MatchString(pathName) {
return pathName
}
var encodedPathname string
for _, s := range pathName {
if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
encodedPathname = encodedPathname + string(s)
continue
}
switch s {
case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
encodedPathname = encodedPathname + string(s)
continue
default:
len := utf8.RuneLen(s)
if len < 0 {
// if utf8 cannot convert return the same string as is
return pathName
}
u := make([]byte, len)
utf8.EncodeRune(u, s)
for _, r := range u {
hex := hex.EncodeToString([]byte{r})
encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
}
}
}
return encodedPathname
}
+143 -15
View File
@@ -21,16 +21,114 @@ package s3api
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"github.com/dustin/go-humanize"
"hash"
"io"
"net/http"
"time"
"github.com/dustin/go-humanize"
)
// Streaming AWS Signature Version '4' constants.
const (
streamingContentSHA256 = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
)
// getChunkSignature - get chunk signature.
func getChunkSignature(secretKey string, seedSignature string, region string, date time.Time, hashedChunk string) string {
// Calculate string to sign.
stringToSign := signV4ChunkedAlgorithm + "\n" +
date.Format(iso8601Format) + "\n" +
getScope(date, region) + "\n" +
seedSignature + "\n" +
emptySHA256 + "\n" +
hashedChunk
// Get hmac signing key.
signingKey := getSigningKey(secretKey, date, region)
// Calculate signature.
newSignature := getSignature(signingKey, stringToSign)
return newSignature
}
// calculateSeedSignature - Calculate seed signature in accordance with
// - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
// returns signature, error otherwise if the signature mismatches or any other
// error while parsing and validating.
func (iam *IdentityAccessManagement) calculateSeedSignature(r *http.Request) (cred *Credential, signature string, region string, date time.Time, errCode ErrorCode) {
// Copy request.
req := *r
// Save authorization header.
v4Auth := req.Header.Get("Authorization")
// Parse signature version '4' header.
signV4Values, errCode := parseSignV4(v4Auth)
if errCode != ErrNone {
return nil, "", "", time.Time{}, errCode
}
// Payload streaming.
payload := streamingContentSHA256
// Payload for STREAMING signature should be 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD'
if payload != req.Header.Get("X-Amz-Content-Sha256") {
return nil, "", "", time.Time{}, ErrContentSHA256Mismatch
}
// Extract all the signed headers along with its values.
extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
if errCode != ErrNone {
return nil, "", "", time.Time{}, errCode
}
// Verify if the access key id matches.
_, cred, found := iam.lookupByAccessKey(signV4Values.Credential.accessKey)
if !found {
return nil, "", "", time.Time{}, ErrInvalidAccessKeyID
}
// Verify if region is valid.
region = signV4Values.Credential.scope.region
// Extract date, if not present throw error.
var dateStr string
if dateStr = req.Header.Get(http.CanonicalHeaderKey("x-amz-date")); dateStr == "" {
if dateStr = r.Header.Get("Date"); dateStr == "" {
return nil, "", "", time.Time{}, ErrMissingDateHeader
}
}
// Parse date header.
var err error
date, err = time.Parse(iso8601Format, dateStr)
if err != nil {
return nil, "", "", time.Time{}, ErrMalformedDate
}
// Query string.
queryStr := req.URL.Query().Encode()
// Get canonical request.
canonicalRequest := getCanonicalRequest(extractedSignedHeaders, payload, queryStr, req.URL.Path, req.Method)
// Get string to sign from canonical request.
stringToSign := getStringToSign(canonicalRequest, date, signV4Values.Credential.getScope())
// Get hmac signing key.
signingKey := getSigningKey(cred.SecretKey, signV4Values.Credential.scope.date, region)
// Calculate signature.
newSignature := getSignature(signingKey, stringToSign)
// Verify if signature match.
if !compareSignatureV4(newSignature, signV4Values.Signature) {
return nil, "", "", time.Time{}, ErrSignatureDoesNotMatch
}
// Return caculated signature.
return cred, newSignature, region, date, ErrNone
}
const maxLineLength = 4 * humanize.KiByte // assumed <= bufio.defaultBufSize 4KiB
@@ -43,22 +141,36 @@ var errMalformedEncoding = errors.New("malformed chunked encoding")
// newSignV4ChunkedReader returns a new s3ChunkedReader that translates the data read from r
// out of HTTP "chunked" format before returning it.
// The s3ChunkedReader returns io.EOF when the final 0-length chunk is read.
func newSignV4ChunkedReader(req *http.Request) io.ReadCloser {
return &s3ChunkedReader{
reader: bufio.NewReader(req.Body),
state: readChunkHeader,
func (iam *IdentityAccessManagement) newSignV4ChunkedReader(req *http.Request) (io.ReadCloser, ErrorCode) {
ident, seedSignature, region, seedDate, errCode := iam.calculateSeedSignature(req)
if errCode != ErrNone {
return nil, errCode
}
return &s3ChunkedReader{
cred: ident,
reader: bufio.NewReader(req.Body),
seedSignature: seedSignature,
seedDate: seedDate,
region: region,
chunkSHA256Writer: sha256.New(),
state: readChunkHeader,
}, ErrNone
}
// Represents the overall state that is required for decoding a
// AWS Signature V4 chunked reader.
type s3ChunkedReader struct {
reader *bufio.Reader
state chunkState
lastChunk bool
chunkSignature string
n uint64 // Unread bytes in chunk
err error
cred *Credential
reader *bufio.Reader
seedSignature string
seedDate time.Time
region string
state chunkState
lastChunk bool
chunkSignature string
chunkSHA256Writer hash.Hash // Calculates sha256 of chunk data.
n uint64 // Unread bytes in chunk
err error
}
// Read chunk reads the chunk token signature portion.
@@ -157,6 +269,9 @@ func (cr *s3ChunkedReader) Read(buf []byte) (n int, err error) {
return 0, cr.err
}
// Calculate sha256.
cr.chunkSHA256Writer.Write(rbuf[:n0])
// Update the bytes read into request buffer so far.
n += n0
buf = buf[n0:]
@@ -169,6 +284,19 @@ func (cr *s3ChunkedReader) Read(buf []byte) (n int, err error) {
continue
}
case verifyChunk:
// Calculate the hashed chunk.
hashedChunk := hex.EncodeToString(cr.chunkSHA256Writer.Sum(nil))
// Calculate the chunk signature.
newSignature := getChunkSignature(cr.cred.SecretKey, cr.seedSignature, cr.region, cr.seedDate, hashedChunk)
if !compareSignatureV4(cr.chunkSignature, newSignature) {
// Chunk signature doesn't match we return signature does not match.
cr.err = errors.New("chunk signature does not match")
return 0, cr.err
}
// Newly calculated signature becomes the seed for the next chunk
// this follows the chaining.
cr.seedSignature = newSignature
cr.chunkSHA256Writer.Reset()
if cr.lastChunk {
cr.state = eofChunk
} else {
+4 -2
View File
@@ -9,6 +9,8 @@ import (
const (
signV4Algorithm = "AWS4-HMAC-SHA256"
signV2Algorithm = "AWS"
iso8601Format = "20060102T150405Z"
yyyymmdd = "20060102"
)
// Verify if request has JWT.
@@ -23,8 +25,8 @@ func isRequestSignatureV4(r *http.Request) bool {
// Verify if request has AWS Signature Version '2'.
func isRequestSignatureV2(r *http.Request) bool {
return (!strings.HasPrefix(r.Header.Get("Authorization"), signV4Algorithm) &&
strings.HasPrefix(r.Header.Get("Authorization"), signV2Algorithm))
return !strings.HasPrefix(r.Header.Get("Authorization"), signV4Algorithm) &&
strings.HasPrefix(r.Header.Get("Authorization"), signV2Algorithm)
}
// Verify if request has AWS PreSign Version '4'.
+144
View File
@@ -27,6 +27,7 @@ type ErrorCode int
// Error codes, see full list at http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
const (
ErrNone ErrorCode = iota
ErrAccessDenied
ErrMethodNotAllowed
ErrBucketNotEmpty
ErrBucketAlreadyExists
@@ -43,12 +44,40 @@ const (
ErrInternalError
ErrInvalidCopyDest
ErrInvalidCopySource
ErrAuthHeaderEmpty
ErrSignatureVersionNotSupported
ErrMissingFields
ErrMissingCredTag
ErrCredMalformed
ErrMalformedDate
ErrMalformedPresignedDate
ErrMalformedCredentialDate
ErrMissingSignHeadersTag
ErrMissingSignTag
ErrUnsignedHeaders
ErrInvalidQueryParams
ErrInvalidQuerySignatureAlgo
ErrExpiredPresignRequest
ErrMalformedExpires
ErrNegativeExpires
ErrMaximumExpires
ErrSignatureDoesNotMatch
ErrContentSHA256Mismatch
ErrInvalidAccessKeyID
ErrRequestNotReadyYet
ErrMissingDateHeader
ErrInvalidRequest
ErrNotImplemented
)
// error code to APIError structure, these fields carry respective
// descriptions for all the error responses.
var errorCodeResponse = map[ErrorCode]APIError{
ErrAccessDenied: {
Code: "AccessDenied",
Description: "Access Denied.",
HTTPStatusCode: http.StatusForbidden,
},
ErrMethodNotAllowed: {
Code: "MethodNotAllowed",
Description: "The specified method is not allowed against this resource.",
@@ -132,6 +161,121 @@ var errorCodeResponse = map[ErrorCode]APIError{
HTTPStatusCode: http.StatusBadRequest,
},
ErrAuthHeaderEmpty: {
Code: "InvalidArgument",
Description: "Authorization header is invalid -- one and only one ' ' (space) required.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrSignatureVersionNotSupported: {
Code: "InvalidRequest",
Description: "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMissingFields: {
Code: "MissingFields",
Description: "Missing fields in request.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMissingCredTag: {
Code: "InvalidRequest",
Description: "Missing Credential field for this request.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrCredMalformed: {
Code: "AuthorizationQueryParametersError",
Description: "Error parsing the X-Amz-Credential parameter; the Credential is mal-formed; expecting \"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMalformedDate: {
Code: "MalformedDate",
Description: "Invalid date format header, expected to be in ISO8601, RFC1123 or RFC1123Z time format.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMalformedPresignedDate: {
Code: "AuthorizationQueryParametersError",
Description: "X-Amz-Date must be in the ISO8601 Long Format \"yyyyMMdd'T'HHmmss'Z'\"",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMissingSignHeadersTag: {
Code: "InvalidArgument",
Description: "Signature header missing SignedHeaders field.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMissingSignTag: {
Code: "AccessDenied",
Description: "Signature header missing Signature field.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrUnsignedHeaders: {
Code: "AccessDenied",
Description: "There were headers present in the request which were not signed",
HTTPStatusCode: http.StatusBadRequest,
},
ErrInvalidQueryParams: {
Code: "AuthorizationQueryParametersError",
Description: "Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrInvalidQuerySignatureAlgo: {
Code: "AuthorizationQueryParametersError",
Description: "X-Amz-Algorithm only supports \"AWS4-HMAC-SHA256\".",
HTTPStatusCode: http.StatusBadRequest,
},
ErrExpiredPresignRequest: {
Code: "AccessDenied",
Description: "Request has expired",
HTTPStatusCode: http.StatusForbidden,
},
ErrMalformedExpires: {
Code: "AuthorizationQueryParametersError",
Description: "X-Amz-Expires should be a number",
HTTPStatusCode: http.StatusBadRequest,
},
ErrNegativeExpires: {
Code: "AuthorizationQueryParametersError",
Description: "X-Amz-Expires must be non-negative",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMaximumExpires: {
Code: "AuthorizationQueryParametersError",
Description: "X-Amz-Expires must be less than a week (in seconds); that is, the given X-Amz-Expires must be less than 604800 seconds",
HTTPStatusCode: http.StatusBadRequest,
},
ErrInvalidAccessKeyID: {
Code: "InvalidAccessKeyId",
Description: "The access key ID you provided does not exist in our records.",
HTTPStatusCode: http.StatusForbidden,
},
ErrRequestNotReadyYet: {
Code: "AccessDenied",
Description: "Request is not valid yet",
HTTPStatusCode: http.StatusForbidden,
},
ErrSignatureDoesNotMatch: {
Code: "SignatureDoesNotMatch",
Description: "The request signature we calculated does not match the signature you provided. Check your key and signing method.",
HTTPStatusCode: http.StatusForbidden,
},
ErrContentSHA256Mismatch: {
Code: "XAmzContentSHA256Mismatch",
Description: "The provided 'x-amz-content-sha256' header does not match what was computed.",
HTTPStatusCode: http.StatusBadRequest,
},
ErrMissingDateHeader: {
Code: "AccessDenied",
Description: "AWS authentication requires a valid Date or x-amz-date header",
HTTPStatusCode: http.StatusBadRequest,
},
ErrInvalidRequest: {
Code: "InvalidRequest",
Description: "Invalid Request",
HTTPStatusCode: http.StatusBadRequest,
},
ErrNotImplemented: {
Code: "NotImplemented",
Description: "A header you provided implies functionality that is not implemented",
+2
View File
@@ -48,6 +48,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request
writeErrorResponse(w, ErrInvalidCopySource, r.URL)
return
}
defer dataReader.Close()
etag, errCode := s3a.putToFiler(r, dstUrl, dataReader)
@@ -129,6 +130,7 @@ func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Req
writeErrorResponse(w, ErrInvalidCopySource, r.URL)
return
}
defer dataReader.Close()
etag, errCode := s3a.putToFiler(r, dstUrl, dataReader)
+11 -5
View File
@@ -13,6 +13,7 @@ import (
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/server"
"github.com/chrislusf/seaweedfs/weed/util"
)
var (
@@ -41,9 +42,15 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request)
rAuthType := getRequestAuthType(r)
dataReader := r.Body
var s3ErrCode ErrorCode
if rAuthType == authTypeStreamingSigned {
dataReader = newSignV4ChunkedReader(r)
dataReader, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
}
if s3ErrCode != ErrNone {
writeErrorResponse(w, s3ErrCode, r.URL)
return
}
defer dataReader.Close()
uploadUrl := fmt.Sprintf("http://%s%s/%s%s?collection=%s",
s3a.option.Filer, s3a.option.BucketsPath, bucket, object, bucket)
@@ -144,9 +151,10 @@ func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, des
writeErrorResponse(w, ErrInternalError, r.URL)
return
}
defer resp.Body.Close()
defer util.CloseResponse(resp)
responseFn(resp, w)
}
func passThroughResponse(proxyResonse *http.Response, w http.ResponseWriter) {
for k, v := range proxyResonse.Header {
@@ -156,7 +164,7 @@ func passThroughResponse(proxyResonse *http.Response, w http.ResponseWriter) {
io.Copy(w, proxyResonse.Body)
}
func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.ReadCloser) (etag string, code ErrorCode) {
func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code ErrorCode) {
hash := md5.New()
var body io.Reader = io.TeeReader(dataReader, hash)
@@ -179,8 +187,6 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader
resp, postErr := client.Do(proxyReq)
dataReader.Close()
if postErr != nil {
glog.Errorf("post to filer: %v", postErr)
return "", ErrInternalError
+11 -4
View File
@@ -3,13 +3,14 @@ package s3api
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gorilla/mux"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gorilla/mux"
)
const (
@@ -195,10 +196,16 @@ func (s3a *S3ApiServer) PutObjectPartHandler(w http.ResponseWriter, r *http.Requ
return
}
var s3ErrCode ErrorCode
dataReader := r.Body
if rAuthType == authTypeStreamingSigned {
dataReader = newSignV4ChunkedReader(r)
dataReader, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
}
if s3ErrCode != ErrNone {
writeErrorResponse(w, s3ErrCode, r.URL)
return
}
defer dataReader.Close()
uploadUrl := fmt.Sprintf("http://%s%s/%s/%04d.part?collection=%s",
s3a.option.Filer, s3a.genUploadsFolder(bucket), uploadID, partID-1, bucket)
+24 -20
View File
@@ -1,14 +1,16 @@
package s3api
import (
"net/http"
"github.com/gorilla/mux"
"google.golang.org/grpc"
"net/http"
)
type S3ApiServerOption struct {
Filer string
FilerGrpcAddress string
Config string
DomainName string
BucketsPath string
GrpcDialOption grpc.DialOption
@@ -16,11 +18,13 @@ type S3ApiServerOption struct {
type S3ApiServer struct {
option *S3ApiServerOption
iam *IdentityAccessManagement
}
func NewS3ApiServer(router *mux.Router, option *S3ApiServerOption) (s3ApiServer *S3ApiServer, err error) {
s3ApiServer = &S3ApiServer{
option: option,
iam: NewIdentityAccessManagement(option.Config, option.DomainName),
}
s3ApiServer.registerRouter(router)
@@ -40,46 +44,46 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
for _, bucket := range routers {
// HeadObject
bucket.Methods("HEAD").Path("/{object:.+}").HandlerFunc(s3a.HeadObjectHandler)
bucket.Methods("HEAD").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.HeadObjectHandler, ACTION_READ))
// HeadBucket
bucket.Methods("HEAD").HandlerFunc(s3a.HeadBucketHandler)
bucket.Methods("HEAD").HandlerFunc(s3a.iam.Auth(s3a.HeadBucketHandler, ACTION_ADMIN))
// CopyObjectPart
bucket.Methods("PUT").Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(s3a.CopyObjectPartHandler).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
bucket.Methods("PUT").Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(s3a.iam.Auth(s3a.CopyObjectPartHandler, ACTION_WRITE)).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
// PutObjectPart
bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(s3a.PutObjectPartHandler).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.PutObjectPartHandler, ACTION_WRITE)).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
// CompleteMultipartUpload
bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(s3a.CompleteMultipartUploadHandler).Queries("uploadId", "{uploadId:.*}")
bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.CompleteMultipartUploadHandler, ACTION_WRITE)).Queries("uploadId", "{uploadId:.*}")
// NewMultipartUpload
bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(s3a.NewMultipartUploadHandler).Queries("uploads", "")
bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.NewMultipartUploadHandler, ACTION_WRITE)).Queries("uploads", "")
// AbortMultipartUpload
bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(s3a.AbortMultipartUploadHandler).Queries("uploadId", "{uploadId:.*}")
bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.AbortMultipartUploadHandler, ACTION_WRITE)).Queries("uploadId", "{uploadId:.*}")
// ListObjectParts
bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(s3a.ListObjectPartsHandler).Queries("uploadId", "{uploadId:.*}")
bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.ListObjectPartsHandler, ACTION_WRITE)).Queries("uploadId", "{uploadId:.*}")
// ListMultipartUploads
bucket.Methods("GET").HandlerFunc(s3a.ListMultipartUploadsHandler).Queries("uploads", "")
bucket.Methods("GET").HandlerFunc(s3a.iam.Auth(s3a.ListMultipartUploadsHandler, ACTION_WRITE)).Queries("uploads", "")
// CopyObject
bucket.Methods("PUT").Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(s3a.CopyObjectHandler)
bucket.Methods("PUT").Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(s3a.iam.Auth(s3a.CopyObjectHandler, ACTION_WRITE))
// PutObject
bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(s3a.PutObjectHandler)
bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.PutObjectHandler, ACTION_WRITE))
// PutBucket
bucket.Methods("PUT").HandlerFunc(s3a.PutBucketHandler)
bucket.Methods("PUT").HandlerFunc(s3a.iam.Auth(s3a.PutBucketHandler, ACTION_ADMIN))
// DeleteObject
bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(s3a.DeleteObjectHandler)
bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.DeleteObjectHandler, ACTION_WRITE))
// DeleteBucket
bucket.Methods("DELETE").HandlerFunc(s3a.DeleteBucketHandler)
bucket.Methods("DELETE").HandlerFunc(s3a.iam.Auth(s3a.DeleteBucketHandler, ACTION_WRITE))
// ListObjectsV2
bucket.Methods("GET").HandlerFunc(s3a.ListObjectsV2Handler).Queries("list-type", "2")
bucket.Methods("GET").HandlerFunc(s3a.iam.Auth(s3a.ListObjectsV2Handler, ACTION_READ)).Queries("list-type", "2")
// GetObject, but directory listing is not supported
bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(s3a.GetObjectHandler)
bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(s3a.iam.Auth(s3a.GetObjectHandler, ACTION_READ))
// ListObjectsV1 (Legacy)
bucket.Methods("GET").HandlerFunc(s3a.ListObjectsV1Handler)
bucket.Methods("GET").HandlerFunc(s3a.iam.Auth(s3a.ListObjectsV1Handler, ACTION_READ))
// DeleteMultipleObjects
bucket.Methods("POST").HandlerFunc(s3a.DeleteMultipleObjectsHandler).Queries("delete", "")
bucket.Methods("POST").HandlerFunc(s3a.iam.Auth(s3a.DeleteMultipleObjectsHandler, ACTION_WRITE)).Queries("delete", "")
/*
// not implemented
@@ -102,7 +106,7 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
}
// ListBuckets
apiRouter.Methods("GET").Path("/").HandlerFunc(s3a.ListBucketsHandler)
apiRouter.Methods("GET").Path("/").HandlerFunc(s3a.iam.Auth(s3a.ListBucketsHandler, ACTION_ADMIN))
// NotFound
apiRouter.NotFoundHandler = http.HandlerFunc(notFoundHandler)
+1 -70
View File
@@ -1,15 +1,12 @@
package security
import (
"bytes"
"errors"
"fmt"
"net"
"net/http"
"strings"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/glog"
)
@@ -65,7 +62,7 @@ func NewGuard(whiteList []string, signingKey string, expiresAfterSec int, readSi
return g
}
func (g *Guard) OldWhiteList(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
func (g *Guard) WhiteList(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
if !g.isWriteActive {
//if no security needed, just skip all checking
return f
@@ -79,20 +76,6 @@ func (g *Guard) OldWhiteList(f func(w http.ResponseWriter, r *http.Request)) fun
}
}
func (g *Guard) WhiteList(f func(ctx *fasthttp.RequestCtx)) func(ctx *fasthttp.RequestCtx) {
if !g.isWriteActive {
//if no security needed, just skip all checking
return f
}
return func(ctx *fasthttp.RequestCtx) {
if err := g.fastCheckWhiteList(ctx); err != nil {
ctx.SetStatusCode(http.StatusUnauthorized)
return
}
f(ctx)
}
}
func GetActualRemoteHost(r *http.Request) (host string, err error) {
host = r.Header.Get("HTTP_X_FORWARDED_FOR")
if host == "" {
@@ -107,22 +90,6 @@ func GetActualRemoteHost(r *http.Request) (host string, err error) {
return
}
func FastGetActualRemoteHost(ctx *fasthttp.RequestCtx) (theHost string, err error) {
host := ctx.Request.Header.Peek("HTTP_X_FORWARDED_FOR")
if host == nil {
host = ctx.Request.Header.Peek("X-FORWARDED-FOR")
}
commaIndex := bytes.IndexByte(host, ',')
if commaIndex >= 0 {
host = host[0:commaIndex]
}
if host == nil {
shost, _, serr := net.SplitHostPort(ctx.RemoteAddr().String())
return shost, serr
}
return string(host), nil
}
func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
if len(g.whiteList) == 0 {
return nil
@@ -158,39 +125,3 @@ func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
glog.V(0).Infof("Not in whitelist: %s", r.RemoteAddr)
return fmt.Errorf("Not in whitelis: %s", r.RemoteAddr)
}
func (g *Guard) fastCheckWhiteList(ctx *fasthttp.RequestCtx) error {
if len(g.whiteList) == 0 {
return nil
}
host, err := FastGetActualRemoteHost(ctx)
if err == nil {
for _, ip := range g.whiteList {
// If the whitelist entry contains a "/" it
// is a CIDR range, and we should check the
// remote host is within it
if strings.Contains(ip, "/") {
_, cidrnet, err := net.ParseCIDR(ip)
if err != nil {
panic(err)
}
remote := net.ParseIP(host)
if cidrnet.Contains(remote) {
return nil
}
}
//
// Otherwise we're looking for a literal match.
//
if ip == host {
return nil
}
}
}
glog.V(0).Infof("Not in whitelist: %s", ctx.RemoteAddr())
return fmt.Errorf("Not in whitelis: %s", ctx.RemoteAddr())
}
+2 -21
View File
@@ -1,16 +1,13 @@
package security
import (
"bytes"
"fmt"
"net/http"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/glog"
jwt "github.com/dgrijalva/jwt-go"
)
type EncodedJwt string
@@ -42,7 +39,7 @@ func GenJwt(signingKey SigningKey, expiresAfterSec int, fileId string) EncodedJw
return EncodedJwt(encoded)
}
func OldGetJwt(r *http.Request) EncodedJwt {
func GetJwt(r *http.Request) EncodedJwt {
// Get token from query params
tokenStr := r.URL.Query().Get("jwt")
@@ -58,22 +55,6 @@ func OldGetJwt(r *http.Request) EncodedJwt {
return EncodedJwt(tokenStr)
}
func GetJwt(ctx *fasthttp.RequestCtx) EncodedJwt {
// Get token from query params
tokenStr := ctx.FormValue("jwt")
// Get token from authorization header
if tokenStr == nil {
bearer := ctx.Request.Header.Peek("Authorization")
if len(bearer) > 7 && string(bytes.ToUpper(bearer[0:6])) == "BEARER" {
tokenStr = bearer[7:]
}
}
return EncodedJwt(tokenStr)
}
func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
// check exp, nbf
return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
+16 -72
View File
@@ -11,7 +11,6 @@ import (
"strings"
"time"
"github.com/valyala/fasthttp"
"google.golang.org/grpc"
"github.com/chrislusf/seaweedfs/weed/glog"
@@ -36,47 +35,7 @@ func init() {
statikFS, _ = statik.New()
}
func writeJson(ctx *fasthttp.RequestCtx, httpStatus int, obj interface{}) (err error) {
var bytes []byte
if ctx.FormValue("pretty") != nil {
bytes, err = json.MarshalIndent(obj, "", " ")
} else {
bytes, err = json.Marshal(obj)
}
if err != nil {
return
}
callback := ctx.FormValue("callback")
if callback == nil {
ctx.Response.Header.Set("Content-Type", "application/json")
ctx.SetStatusCode(httpStatus)
if httpStatus == http.StatusNotModified {
return
}
_, err = ctx.Response.BodyWriter().Write(bytes)
} else {
ctx.Response.Header.Set("Content-Type", "application/javascript")
ctx.SetStatusCode(httpStatus)
if httpStatus == http.StatusNotModified {
return
}
if _, err = ctx.Response.BodyWriter().Write([]uint8(callback)); err != nil {
return
}
if _, err = ctx.Response.BodyWriter().Write([]uint8("(")); err != nil {
return
}
fmt.Fprint(ctx.Response.BodyWriter(), string(bytes))
if _, err = ctx.Response.BodyWriter().Write([]uint8(")")); err != nil {
return
}
}
return
}
func oldWriteJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
func writeJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
var bytes []byte
if r.FormValue("pretty") != "" {
bytes, err = json.MarshalIndent(obj, "", " ")
@@ -115,32 +74,17 @@ func oldWriteJson(w http.ResponseWriter, r *http.Request, httpStatus int, obj in
return
}
// wrapper for oldWriteJson - just logs errors
func oldWriteJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
if err := oldWriteJson(w, r, httpStatus, obj); err != nil {
// wrapper for writeJson - just logs errors
func writeJsonQuiet(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) {
if err := writeJson(w, r, httpStatus, obj); err != nil {
glog.V(0).Infof("error writing JSON status %d: %v", httpStatus, err)
glog.V(1).Infof("JSON content: %+v", obj)
}
}
// wrapper for oldWriteJson - just logs errors
func writeJsonQuiet(ctx *fasthttp.RequestCtx, httpStatus int, obj interface{}) {
if err := writeJson(ctx, httpStatus, obj); err != nil {
glog.V(0).Infof("error writing JSON status %d: %v", httpStatus, err)
glog.V(1).Infof("JSON content: %+v", obj)
}
}
func oldWriteJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
func writeJsonError(w http.ResponseWriter, r *http.Request, httpStatus int, err error) {
m := make(map[string]interface{})
m["error"] = err.Error()
oldWriteJsonQuiet(w, r, httpStatus, m)
}
func writeJsonError(ctx *fasthttp.RequestCtx, httpStatus int, err error) {
m := make(map[string]interface{})
m["error"] = err.Error()
writeJsonQuiet(ctx, httpStatus, m)
writeJsonQuiet(w, r, httpStatus, m)
}
func debug(params ...interface{}) {
@@ -150,14 +94,14 @@ func debug(params ...interface{}) {
func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl string, grpcDialOption grpc.DialOption) {
m := make(map[string]interface{})
if r.Method != "POST" {
oldWriteJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
writeJsonError(w, r, http.StatusMethodNotAllowed, errors.New("Only submit via POST!"))
return
}
debug("parsing upload file...")
fname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := needle.OldParseUpload(r, 256*1024*1024)
fname, data, mimeType, pairMap, isGzipped, originalDataSize, lastModified, _, _, pe := needle.ParseUpload(r, 256*1024*1024)
if pe != nil {
oldWriteJsonError(w, r, http.StatusBadRequest, pe)
writeJsonError(w, r, http.StatusBadRequest, pe)
return
}
@@ -167,7 +111,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st
if r.FormValue("count") != "" {
count, pe = strconv.ParseUint(r.FormValue("count"), 10, 32)
if pe != nil {
oldWriteJsonError(w, r, http.StatusBadRequest, pe)
writeJsonError(w, r, http.StatusBadRequest, pe)
return
}
}
@@ -180,7 +124,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st
}
assignResult, ae := operation.Assign(masterUrl, grpcDialOption, ar)
if ae != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, ae)
writeJsonError(w, r, http.StatusInternalServerError, ae)
return
}
@@ -192,7 +136,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st
debug("upload file to store", url)
uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, assignResult.Auth)
if err != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, err)
writeJsonError(w, r, http.StatusInternalServerError, err)
return
}
@@ -201,7 +145,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st
m["fileUrl"] = assignResult.PublicUrl + "/" + assignResult.Fid
m["size"] = originalDataSize
m["eTag"] = uploadResult.ETag
oldWriteJsonQuiet(w, r, http.StatusCreated, m)
writeJsonQuiet(w, r, http.StatusCreated, m)
return
}
@@ -241,20 +185,20 @@ func parseURLPath(path string) (vid, fid, filename, ext string, isVolumeIdOnly b
func statsHealthHandler(w http.ResponseWriter, r *http.Request) {
m := make(map[string]interface{})
m["Version"] = util.VERSION
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
func statsCounterHandler(w http.ResponseWriter, r *http.Request) {
m := make(map[string]interface{})
m["Version"] = util.VERSION
m["Counters"] = serverStats
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
func statsMemoryHandler(w http.ResponseWriter, r *http.Request) {
m := make(map[string]interface{})
m["Version"] = util.VERSION
m["Memory"] = stats.MemStat()
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
func handleStaticResources(defaultMux *http.ServeMux) {
+3 -3
View File
@@ -69,7 +69,7 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request,
if r.Method == "HEAD" {
w.Header().Set("Content-Length", strconv.FormatInt(int64(filer2.TotalSize(entry.Chunks)), 10))
w.Header().Set("Last-Modified", entry.Attr.Mtime.Format(http.TimeFormat))
oldSetEtag(w, filer2.ETag(entry.Chunks))
setEtag(w, filer2.ETag(entry.Chunks))
return
}
@@ -122,7 +122,7 @@ func (fs *FilerServer) handleSingleChunk(w http.ResponseWriter, r *http.Request,
resp, do_err := util.Do(request)
if do_err != nil {
glog.V(0).Infoln("failing to connect to volume server", do_err.Error())
oldWriteJsonError(w, r, http.StatusInternalServerError, do_err)
writeJsonError(w, r, http.StatusInternalServerError, do_err)
return
}
defer func() {
@@ -150,7 +150,7 @@ func (fs *FilerServer) handleMultipleChunks(w http.ResponseWriter, r *http.Reque
if mimeType != "" {
w.Header().Set("Content-Type", mimeType)
}
oldSetEtag(w, filer2.ETag(entry.Chunks))
setEtag(w, filer2.ETag(entry.Chunks))
totalSize := int64(filer2.TotalSize(entry.Chunks))
@@ -52,7 +52,7 @@ func (fs *FilerServer) listDirectoryHandler(w http.ResponseWriter, r *http.Reque
glog.V(4).Infof("listDirectory %s, last file %s, limit %d: %d items", path, lastFileName, limit, len(entries))
if r.Header.Get("Accept") == "application/json" {
oldWriteJsonQuiet(w, r, http.StatusOK, struct {
writeJsonQuiet(w, r, http.StatusOK, struct {
Path string
Entries interface{}
Limit int
+10 -10
View File
@@ -65,7 +65,7 @@ func (fs *FilerServer) assignNewFileInfo(w http.ResponseWriter, r *http.Request,
assignResult, ae := operation.Assign(fs.filer.GetMaster(), fs.grpcDialOption, ar, altRequest)
if ae != nil {
glog.Errorf("failing to assign a file id: %v", ae)
oldWriteJsonError(w, r, http.StatusInternalServerError, ae)
writeJsonError(w, r, http.StatusInternalServerError, ae)
err = ae
return
}
@@ -135,8 +135,8 @@ func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request) {
Fid: fileId,
Url: urlLocation,
}
oldSetEtag(w, ret.ETag)
oldWriteJsonQuiet(w, r, http.StatusCreated, reply)
setEtag(w, ret.ETag)
writeJsonQuiet(w, r, http.StatusCreated, reply)
}
// update metadata in filer store
@@ -196,7 +196,7 @@ func (fs *FilerServer) updateFilerStore(ctx context.Context, r *http.Request, w
if dbErr := fs.filer.CreateEntry(ctx, entry, false); dbErr != nil {
fs.filer.DeleteChunks(entry.Chunks)
glog.V(0).Infof("failing to write %s to filer server : %v", path, dbErr)
oldWriteJsonError(w, r, http.StatusInternalServerError, dbErr)
writeJsonError(w, r, http.StatusInternalServerError, dbErr)
err = dbErr
return
}
@@ -228,7 +228,7 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se
resp, doErr := util.Do(request)
if doErr != nil {
glog.Errorf("failing to connect to volume server %s: %v, %+v", r.RequestURI, doErr, r.Method)
oldWriteJsonError(w, r, http.StatusInternalServerError, doErr)
writeJsonError(w, r, http.StatusInternalServerError, doErr)
err = doErr
return
}
@@ -240,7 +240,7 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se
respBody, raErr := ioutil.ReadAll(resp.Body)
if raErr != nil {
glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, raErr.Error())
oldWriteJsonError(w, r, http.StatusInternalServerError, raErr)
writeJsonError(w, r, http.StatusInternalServerError, raErr)
err = raErr
return
}
@@ -248,14 +248,14 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se
unmarshalErr := json.Unmarshal(respBody, &ret)
if unmarshalErr != nil {
glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(respBody))
oldWriteJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
writeJsonError(w, r, http.StatusInternalServerError, unmarshalErr)
err = unmarshalErr
return
}
if ret.Error != "" {
err = errors.New(ret.Error)
glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
oldWriteJsonError(w, r, http.StatusInternalServerError, err)
writeJsonError(w, r, http.StatusInternalServerError, err)
return
}
// find correct final path
@@ -267,7 +267,7 @@ func (fs *FilerServer) uploadToVolumeServer(r *http.Request, u *url.URL, auth se
err = fmt.Errorf("can not to write to folder %s without a file name", path)
fs.filer.DeleteFileByFileId(fileId)
glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
oldWriteJsonError(w, r, http.StatusInternalServerError, err)
writeJsonError(w, r, http.StatusInternalServerError, err)
return
}
}
@@ -299,7 +299,7 @@ func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
if err == filer2.ErrNotFound {
httpStatus = http.StatusNotFound
}
oldWriteJsonError(w, r, httpStatus, err)
writeJsonError(w, r, httpStatus, err)
return
}
@@ -57,9 +57,9 @@ func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r *
reply, err := fs.doAutoChunk(ctx, w, r, contentLength, chunkSize, replication, collection, dataCenter)
if err != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, err)
writeJsonError(w, r, http.StatusInternalServerError, err)
} else if reply != nil {
oldWriteJsonQuiet(w, r, http.StatusCreated, reply)
writeJsonQuiet(w, r, http.StatusCreated, reply)
}
return true
}
+13 -13
View File
@@ -107,17 +107,17 @@ func NewMasterServer(r *mux.Router, option *MasterOption, peers []string) *Maste
handleStaticResources2(r)
r.HandleFunc("/", ms.proxyToLeader(ms.uiStatusHandler))
r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.OldWhiteList(ms.dirAssignHandler)))
r.HandleFunc("/dir/lookup", ms.guard.OldWhiteList(ms.dirLookupHandler))
r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.OldWhiteList(ms.dirStatusHandler)))
r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.OldWhiteList(ms.collectionDeleteHandler)))
r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.OldWhiteList(ms.volumeGrowHandler)))
r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.OldWhiteList(ms.volumeStatusHandler)))
r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.OldWhiteList(ms.volumeVacuumHandler)))
r.HandleFunc("/submit", ms.guard.OldWhiteList(ms.submitFromMasterServerHandler))
r.HandleFunc("/stats/health", ms.guard.OldWhiteList(statsHealthHandler))
r.HandleFunc("/stats/counter", ms.guard.OldWhiteList(statsCounterHandler))
r.HandleFunc("/stats/memory", ms.guard.OldWhiteList(statsMemoryHandler))
r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
r.HandleFunc("/dir/lookup", ms.guard.WhiteList(ms.dirLookupHandler))
r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
r.HandleFunc("/vol/grow", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeGrowHandler)))
r.HandleFunc("/vol/status", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeStatusHandler)))
r.HandleFunc("/vol/vacuum", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeVacuumHandler)))
r.HandleFunc("/submit", ms.guard.WhiteList(ms.submitFromMasterServerHandler))
r.HandleFunc("/stats/health", ms.guard.WhiteList(statsHealthHandler))
r.HandleFunc("/stats/counter", ms.guard.WhiteList(statsCounterHandler))
r.HandleFunc("/stats/memory", ms.guard.WhiteList(statsMemoryHandler))
r.HandleFunc("/{fileId}", ms.redirectHandler)
}
@@ -157,7 +157,7 @@ func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Requ
defer func() { <-ms.bounedLeaderChan }()
targetUrl, err := url.Parse("http://" + ms.Topo.RaftServer.Leader())
if err != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError,
writeJsonError(w, r, http.StatusInternalServerError,
fmt.Errorf("Leader URL http://%s Parse Error: %v", ms.Topo.RaftServer.Leader(), err))
return
}
@@ -175,7 +175,7 @@ func (ms *MasterServer) proxyToLeader(f func(w http.ResponseWriter, r *http.Requ
proxy.ServeHTTP(w, r)
} else {
// drop it to the floor
// oldWriteJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader()))
// writeJsonError(w, r, errors.New(ms.Topo.RaftServer.Name()+" does not know Leader yet:"+ms.Topo.RaftServer.Leader()))
}
}
}
+6 -6
View File
@@ -55,7 +55,7 @@ func (ms *MasterServer) dirLookupHandler(w http.ResponseWriter, r *http.Request)
isRead := forRead == "yes"
ms.maybeAddJwtAuthorization(w, fileId, !isRead)
}
oldWriteJsonQuiet(w, r, httpStatus, location)
writeJsonQuiet(w, r, httpStatus, location)
}
// findVolumeLocation finds the volume location from master topo if it is leader,
@@ -107,20 +107,20 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request)
option, err := ms.getVolumeGrowOption(r)
if err != nil {
oldWriteJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()})
writeJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()})
return
}
if !ms.Topo.HasWritableVolume(option) {
if ms.Topo.FreeSpace() <= 0 {
oldWriteJsonQuiet(w, r, http.StatusNotFound, operation.AssignResult{Error: "No free volumes left!"})
writeJsonQuiet(w, r, http.StatusNotFound, operation.AssignResult{Error: "No free volumes left!"})
return
}
ms.vgLock.Lock()
defer ms.vgLock.Unlock()
if !ms.Topo.HasWritableVolume(option) {
if _, err = ms.vg.AutomaticGrowByType(option, ms.grpcDialOption, ms.Topo, writableVolumeCount); err != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError,
writeJsonError(w, r, http.StatusInternalServerError,
fmt.Errorf("Cannot grow volume group! %v", err))
return
}
@@ -129,9 +129,9 @@ func (ms *MasterServer) dirAssignHandler(w http.ResponseWriter, r *http.Request)
fid, count, dn, err := ms.Topo.PickForWrite(requestedCount, option)
if err == nil {
ms.maybeAddJwtAuthorization(w, fid, true)
oldWriteJsonQuiet(w, r, http.StatusOK, operation.AssignResult{Fid: fid, Url: dn.Url(), PublicUrl: dn.PublicUrl, Count: count})
writeJsonQuiet(w, r, http.StatusOK, operation.AssignResult{Fid: fid, Url: dn.Url(), PublicUrl: dn.PublicUrl, Count: count})
} else {
oldWriteJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()})
writeJsonQuiet(w, r, http.StatusNotAcceptable, operation.AssignResult{Error: err.Error()})
}
}
+10 -10
View File
@@ -21,7 +21,7 @@ func (ms *MasterServer) collectionDeleteHandler(w http.ResponseWriter, r *http.R
collectionName := r.FormValue("collection")
collection, ok := ms.Topo.FindCollection(collectionName)
if !ok {
oldWriteJsonError(w, r, http.StatusBadRequest, fmt.Errorf("collection %s does not exist", collectionName))
writeJsonError(w, r, http.StatusBadRequest, fmt.Errorf("collection %s does not exist", collectionName))
return
}
for _, server := range collection.ListVolumeServers() {
@@ -32,7 +32,7 @@ func (ms *MasterServer) collectionDeleteHandler(w http.ResponseWriter, r *http.R
return deleteErr
})
if err != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, err)
writeJsonError(w, r, http.StatusInternalServerError, err)
return
}
}
@@ -46,7 +46,7 @@ func (ms *MasterServer) dirStatusHandler(w http.ResponseWriter, r *http.Request)
m := make(map[string]interface{})
m["Version"] = util.VERSION
m["Topology"] = ms.Topo.ToMap()
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Request) {
@@ -57,7 +57,7 @@ func (ms *MasterServer) volumeVacuumHandler(w http.ResponseWriter, r *http.Reque
gcThreshold, err = strconv.ParseFloat(gcString, 32)
if err != nil {
glog.V(0).Infof("garbageThreshold %s is not a valid float number: %v", gcString, err)
oldWriteJsonError(w, r, http.StatusNotAcceptable, fmt.Errorf("garbageThreshold %s is not a valid float number", gcString))
writeJsonError(w, r, http.StatusNotAcceptable, fmt.Errorf("garbageThreshold %s is not a valid float number", gcString))
return
}
}
@@ -70,7 +70,7 @@ func (ms *MasterServer) volumeGrowHandler(w http.ResponseWriter, r *http.Request
count := 0
option, err := ms.getVolumeGrowOption(r)
if err != nil {
oldWriteJsonError(w, r, http.StatusNotAcceptable, err)
writeJsonError(w, r, http.StatusNotAcceptable, err)
return
}
@@ -85,9 +85,9 @@ func (ms *MasterServer) volumeGrowHandler(w http.ResponseWriter, r *http.Request
}
if err != nil {
oldWriteJsonError(w, r, http.StatusNotAcceptable, err)
writeJsonError(w, r, http.StatusNotAcceptable, err)
} else {
oldWriteJsonQuiet(w, r, http.StatusOK, map[string]interface{}{"count": count})
writeJsonQuiet(w, r, http.StatusOK, map[string]interface{}{"count": count})
}
}
@@ -95,7 +95,7 @@ func (ms *MasterServer) volumeStatusHandler(w http.ResponseWriter, r *http.Reque
m := make(map[string]interface{})
m["Version"] = util.VERSION
m["Volumes"] = ms.Topo.ToVolumeMap()
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
func (ms *MasterServer) redirectHandler(w http.ResponseWriter, r *http.Request) {
@@ -112,7 +112,7 @@ func (ms *MasterServer) redirectHandler(w http.ResponseWriter, r *http.Request)
}
http.Redirect(w, r, url, http.StatusMovedPermanently)
} else {
oldWriteJsonError(w, r, http.StatusNotFound, fmt.Errorf("volume id %s not found: %s", vid, location.Error))
writeJsonError(w, r, http.StatusNotFound, fmt.Errorf("volume id %s not found: %s", vid, location.Error))
}
}
@@ -128,7 +128,7 @@ func (ms *MasterServer) submitFromMasterServerHandler(w http.ResponseWriter, r *
} else {
masterUrl, err := ms.Topo.Leader()
if err != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, err)
writeJsonError(w, r, http.StatusInternalServerError, err)
} else {
submitForClientHandler(w, r, masterUrl, ms.grpcDialOption)
}
+1 -1
View File
@@ -18,5 +18,5 @@ func (s *RaftServer) StatusHandler(w http.ResponseWriter, r *http.Request) {
if leader, e := s.topo.Leader(); e == nil {
ret.Leader = leader
}
oldWriteJsonQuiet(w, r, http.StatusOK, ret)
writeJsonQuiet(w, r, http.StatusOK, ret)
}
+130
View File
@@ -0,0 +1,130 @@
package weed_server
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
"github.com/chrislusf/seaweedfs/weed/storage/needle"
"github.com/chrislusf/seaweedfs/weed/util"
)
func (vs *VolumeServer) FileGet(req *volume_server_pb.FileGetRequest, stream volume_server_pb.VolumeServer_FileGetServer) error {
headResponse := &volume_server_pb.FileGetResponse{}
n := new(needle.Needle)
commaIndex := strings.LastIndex(req.FileId, ",")
vid := req.FileId[:commaIndex]
fid := req.FileId[commaIndex+1:]
volumeId, err := needle.NewVolumeId(vid)
if err != nil {
headResponse.ErrorCode = http.StatusBadRequest
return stream.Send(headResponse)
}
err = n.ParsePath(fid)
if err != nil {
headResponse.ErrorCode = http.StatusBadRequest
return stream.Send(headResponse)
}
hasVolume := vs.store.HasVolume(volumeId)
_, hasEcVolume := vs.store.FindEcVolume(volumeId)
if !hasVolume && !hasEcVolume {
headResponse.ErrorCode = http.StatusMovedPermanently
return stream.Send(headResponse)
}
cookie := n.Cookie
var count int
if hasVolume {
count, err = vs.store.ReadVolumeNeedle(volumeId, n)
} else if hasEcVolume {
count, err = vs.store.ReadEcShardNeedle(context.Background(), volumeId, n)
}
if err != nil || count < 0 {
headResponse.ErrorCode = http.StatusNotFound
return stream.Send(headResponse)
}
if n.Cookie != cookie {
headResponse.ErrorCode = http.StatusNotFound
return stream.Send(headResponse)
}
if n.LastModified != 0 {
headResponse.LastModified = n.LastModified
}
headResponse.Etag = n.Etag()
if n.HasPairs() {
pairMap := make(map[string]string)
err = json.Unmarshal(n.Pairs, &pairMap)
if err != nil {
glog.V(0).Infoln("Unmarshal pairs error:", err)
}
headResponse.Headers = pairMap
}
/*
// skip this, no redirection
if vs.tryHandleChunkedFile(n, filename, w, r) {
return
}
*/
if n.NameSize > 0 {
headResponse.Filename = string(n.Name)
}
mtype := ""
if n.MimeSize > 0 {
mt := string(n.Mime)
if !strings.HasPrefix(mt, "application/octet-stream") {
mtype = mt
}
}
headResponse.ContentType = mtype
headResponse.IsGzipped = n.IsGzipped()
if n.IsGzipped() && req.AcceptGzip {
if n.Data, err = util.UnGzipData(n.Data); err != nil {
glog.V(0).Infof("ungzip %s error: %v", req.FileId, err)
}
}
headResponse.ContentLength = uint32(len(n.Data))
bytesToRead := len(n.Data)
bytesRead := 0
t := headResponse
for bytesRead < bytesToRead {
stopIndex := bytesRead + BufferSizeLimit
if stopIndex > bytesToRead {
stopIndex = bytesToRead
}
if t == nil {
t = &volume_server_pb.FileGetResponse{}
}
t.Data = n.Data[bytesRead:stopIndex]
err = stream.Send(t)
t = nil
if err != nil {
return err
}
bytesRead = stopIndex
}
return nil
}
+6 -6
View File
@@ -76,16 +76,16 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string,
if signingKey == "" || enableUiAccess {
// only expose the volume server details for safe environments
adminMux.HandleFunc("/ui/index.html", vs.uiStatusHandler)
adminMux.HandleFunc("/status", vs.guard.OldWhiteList(vs.statusHandler))
adminMux.HandleFunc("/stats/counter", vs.guard.OldWhiteList(statsCounterHandler))
adminMux.HandleFunc("/stats/memory", vs.guard.OldWhiteList(statsMemoryHandler))
adminMux.HandleFunc("/stats/disk", vs.guard.OldWhiteList(vs.statsDiskHandler))
adminMux.HandleFunc("/status", vs.guard.WhiteList(vs.statusHandler))
adminMux.HandleFunc("/stats/counter", vs.guard.WhiteList(statsCounterHandler))
adminMux.HandleFunc("/stats/memory", vs.guard.WhiteList(statsMemoryHandler))
adminMux.HandleFunc("/stats/disk", vs.guard.WhiteList(vs.statsDiskHandler))
}
adminMux.HandleFunc("/", vs.oldPrivateStoreHandler)
adminMux.HandleFunc("/", vs.privateStoreHandler)
if publicMux != adminMux {
// separated admin and public port
handleStaticResources(publicMux)
publicMux.HandleFunc("/", vs.oldPublicReadOnlyHandler)
publicMux.HandleFunc("/", vs.publicReadOnlyHandler)
}
go vs.heartbeat()
@@ -1,81 +0,0 @@
package weed_server
import (
"strings"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/security"
"github.com/chrislusf/seaweedfs/weed/stats"
)
func (vs *VolumeServer) HandleFastHTTP(ctx *fasthttp.RequestCtx) {
switch string(ctx.Method()) {
case "GET", "HEAD":
vs.fastGetOrHeadHandler(ctx)
case "DELETE":
stats.DeleteRequest()
vs.guard.WhiteList(vs.DeleteHandler)(ctx)
case "PUT", "POST":
stats.WriteRequest()
vs.guard.WhiteList(vs.fastPostHandler)(ctx)
}
}
func (vs *VolumeServer) publicReadOnlyHandler(ctx *fasthttp.RequestCtx) {
switch string(ctx.Method()) {
case "GET":
stats.ReadRequest()
vs.fastGetOrHeadHandler(ctx)
case "HEAD":
stats.ReadRequest()
vs.fastGetOrHeadHandler(ctx)
}
}
func (vs *VolumeServer) maybeCheckJwtAuthorization(ctx *fasthttp.RequestCtx, vid, fid string, isWrite bool) bool {
var signingKey security.SigningKey
if isWrite {
if len(vs.guard.SigningKey) == 0 {
return true
} else {
signingKey = vs.guard.SigningKey
}
} else {
if len(vs.guard.ReadSigningKey) == 0 {
return true
} else {
signingKey = vs.guard.ReadSigningKey
}
}
tokenStr := security.GetJwt(ctx)
if tokenStr == "" {
glog.V(1).Infof("missing jwt from %s", ctx.RemoteAddr())
return false
}
token, err := security.DecodeJwt(signingKey, tokenStr)
if err != nil {
glog.V(1).Infof("jwt verification error from %s: %v", ctx.RemoteAddr(), err)
return false
}
if !token.Valid {
glog.V(1).Infof("jwt invalid from %s: %v", ctx.RemoteAddr(), tokenStr)
return false
}
if sc, ok := token.Claims.(*security.SeaweedFileIdClaims); ok {
if sepIndex := strings.LastIndex(fid, "_"); sepIndex > 0 {
fid = fid[:sepIndex]
}
return sc.Fid == vid+","+fid
}
glog.V(1).Infof("unexpected jwt from %s: %v", ctx.RemoteAddr(), tokenStr)
return false
}
@@ -1,366 +0,0 @@
package weed_server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/url"
"path"
"strconv"
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/images"
"github.com/chrislusf/seaweedfs/weed/operation"
"github.com/chrislusf/seaweedfs/weed/stats"
"github.com/chrislusf/seaweedfs/weed/storage/needle"
"github.com/chrislusf/seaweedfs/weed/util"
)
func (vs *VolumeServer) fastGetOrHeadHandler(ctx *fasthttp.RequestCtx) {
stats.VolumeServerRequestCounter.WithLabelValues("get").Inc()
start := time.Now()
defer func() { stats.VolumeServerRequestHistogram.WithLabelValues("get").Observe(time.Since(start).Seconds()) }()
requestPath := string(ctx.Path())
n := new(needle.Needle)
vid, fid, filename, ext, _ := parseURLPath(requestPath)
if !vs.maybeCheckJwtAuthorization(ctx, vid, fid, false) {
writeJsonError(ctx, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
volumeId, err := needle.NewVolumeId(vid)
if err != nil {
glog.V(2).Infof("parsing volumd id %s error: %v", err, requestPath)
ctx.SetStatusCode(http.StatusBadRequest)
return
}
err = n.ParsePath(fid)
if err != nil {
glog.V(2).Infof("parsing fid %s error: %v", err, requestPath)
ctx.SetStatusCode(http.StatusBadRequest)
return
}
// glog.V(4).Infoln("volume", volumeId, "reading", n)
hasVolume := vs.store.HasVolume(volumeId)
_, hasEcVolume := vs.store.FindEcVolume(volumeId)
if !hasVolume && !hasEcVolume {
if !vs.ReadRedirect {
glog.V(2).Infoln("volume is not local:", err, requestPath)
ctx.SetStatusCode(http.StatusNotFound)
return
}
lookupResult, err := operation.Lookup(vs.GetMaster(), volumeId.String())
glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err)
if err == nil && len(lookupResult.Locations) > 0 {
u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations[0].PublicUrl))
u.Path = fmt.Sprintf("%s/%s,%s", u.Path, vid, fid)
arg := url.Values{}
if c := ctx.FormValue("collection"); c != nil {
arg.Set("collection", string(c))
}
u.RawQuery = arg.Encode()
ctx.Redirect(u.String(), http.StatusMovedPermanently)
} else {
glog.V(2).Infof("lookup %s error: %v", requestPath, err)
ctx.SetStatusCode(http.StatusNotFound)
}
return
}
cookie := n.Cookie
var count int
if hasVolume {
count, err = vs.store.ReadVolumeNeedle(volumeId, n)
} else if hasEcVolume {
count, err = vs.store.ReadEcShardNeedle(context.Background(), volumeId, n)
}
// glog.V(4).Infoln("read bytes", count, "error", err)
if err != nil || count < 0 {
glog.V(0).Infof("read %s isNormalVolume %v error: %v", requestPath, hasVolume, err)
ctx.SetStatusCode(http.StatusNotFound)
return
}
if n.Cookie != cookie {
glog.V(0).Infof("request %s with cookie:%x expected:%x agent %s", requestPath, cookie, n.Cookie, string(ctx.UserAgent()))
ctx.SetStatusCode(http.StatusNotFound)
return
}
if n.LastModified != 0 {
ctx.Response.Header.Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
if ctx.Response.Header.Peek("If-Modified-Since") != nil {
if t, parseError := time.Parse(http.TimeFormat, string(ctx.Response.Header.Peek("If-Modified-Since"))); parseError == nil {
if t.Unix() >= int64(n.LastModified) {
ctx.SetStatusCode(http.StatusNotModified)
return
}
}
}
}
if inm := ctx.Response.Header.Peek("If-None-Match"); inm != nil && string(inm) == "\""+n.Etag()+"\"" {
ctx.SetStatusCode(http.StatusNotModified)
return
}
eTagMd5 := ctx.Response.Header.Peek("ETag-MD5")
if eTagMd5 != nil && string(eTagMd5) == "True" {
fastSetEtag(ctx, n.MD5())
} else {
fastSetEtag(ctx, n.Etag())
}
if n.HasPairs() {
pairMap := make(map[string]string)
err = json.Unmarshal(n.Pairs, &pairMap)
if err != nil {
glog.V(0).Infoln("Unmarshal pairs error:", err)
}
for k, v := range pairMap {
ctx.Response.Header.Set(k, v)
}
}
if vs.fastTryHandleChunkedFile(n, filename, ctx) {
return
}
if n.NameSize > 0 && filename == "" {
filename = string(n.Name)
if ext == "" {
ext = path.Ext(filename)
}
}
mtype := ""
if n.MimeSize > 0 {
mt := string(n.Mime)
if !strings.HasPrefix(mt, "application/octet-stream") {
mtype = mt
}
}
if ext != ".gz" {
if n.IsGzipped() {
acceptEncoding := ctx.Request.Header.Peek("Accept-Encoding")
if acceptEncoding != nil && strings.Contains(string(acceptEncoding), "gzip") {
ctx.Response.Header.Set("Content-Encoding", "gzip")
} else {
if n.Data, err = util.UnGzipData(n.Data); err != nil {
glog.V(0).Infoln("ungzip error:", err, requestPath)
}
}
}
}
rs := fastConditionallyResizeImages(bytes.NewReader(n.Data), ext, ctx)
if e := fastWriteResponseContent(filename, mtype, rs, ctx); e != nil {
glog.V(2).Infoln("response write error:", e)
}
}
func (vs *VolumeServer) fastTryHandleChunkedFile(n *needle.Needle, fileName string, ctx *fasthttp.RequestCtx) (processed bool) {
if !n.IsChunkedManifest() || string(ctx.FormValue("cm")) == "false" {
return false
}
chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
if e != nil {
glog.V(0).Infof("load chunked manifest (%s) error: %v", string(ctx.Path()), e)
return false
}
if fileName == "" && chunkManifest.Name != "" {
fileName = chunkManifest.Name
}
ext := path.Ext(fileName)
mType := ""
if chunkManifest.Mime != "" {
mt := chunkManifest.Mime
if !strings.HasPrefix(mt, "application/octet-stream") {
mType = mt
}
}
ctx.Response.Header.Set("X-File-Store", "chunked")
chunkedFileReader := &operation.ChunkedFileReader{
Manifest: chunkManifest,
Master: vs.GetMaster(),
}
defer chunkedFileReader.Close()
rs := fastConditionallyResizeImages(chunkedFileReader, ext, ctx)
if e := fastWriteResponseContent(fileName, mType, rs, ctx); e != nil {
glog.V(2).Infoln("response write error:", e)
}
return true
}
func fastConditionallyResizeImages(originalDataReaderSeeker io.ReadSeeker, ext string, ctx *fasthttp.RequestCtx) io.ReadSeeker {
rs := originalDataReaderSeeker
if len(ext) > 0 {
ext = strings.ToLower(ext)
}
if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".gif" {
width, height := 0, 0
formWidth, formHeight := ctx.FormValue("width"), ctx.FormValue("height")
if formWidth != nil {
width, _ = strconv.Atoi(string(formWidth))
}
if formHeight != nil {
height, _ = strconv.Atoi(string(formHeight))
}
formMode := ctx.FormValue("mode")
rs, _, _ = images.Resized(ext, originalDataReaderSeeker, width, height, string(formMode))
}
return rs
}
func fastWriteResponseContent(filename, mimeType string, rs io.ReadSeeker, ctx *fasthttp.RequestCtx) error {
totalSize, e := rs.Seek(0, 2)
if mimeType == "" {
if ext := path.Ext(filename); ext != "" {
mimeType = mime.TypeByExtension(ext)
}
}
if mimeType != "" {
ctx.Response.Header.Set("Content-Type", mimeType)
}
if filename != "" {
contentDisposition := "inline"
dlFormValue := ctx.FormValue("dl")
if dlFormValue != nil {
if dl, _ := strconv.ParseBool(string(dlFormValue)); dl {
contentDisposition = "attachment"
}
}
ctx.Response.Header.Set("Content-Disposition", contentDisposition+`; filename="`+fileNameEscaper.Replace(filename)+`"`)
}
ctx.Response.Header.Set("Accept-Ranges", "bytes")
if ctx.IsHead() {
ctx.Response.Header.Set("Content-Length", strconv.FormatInt(totalSize, 10))
return nil
}
rangeReq := ctx.FormValue("Range")
if rangeReq == nil {
ctx.Response.Header.Set("Content-Length", strconv.FormatInt(totalSize, 10))
if _, e = rs.Seek(0, 0); e != nil {
return e
}
_, e = io.Copy(ctx.Response.BodyWriter(), rs)
return e
}
//the rest is dealing with partial content request
//mostly copy from src/pkg/net/http/fs.go
ranges, err := parseRange(string(rangeReq), totalSize)
if err != nil {
ctx.Response.SetStatusCode(http.StatusRequestedRangeNotSatisfiable)
ctxError(ctx, err.Error(), http.StatusRequestedRangeNotSatisfiable)
return nil
}
if sumRangesSize(ranges) > totalSize {
// The total number of bytes in all the ranges
// is larger than the size of the file by
// itself, so this is probably an attack, or a
// dumb client. Ignore the range request.
return nil
}
if len(ranges) == 0 {
return nil
}
if len(ranges) == 1 {
// RFC 2616, Section 14.16:
// "When an HTTP message includes the content of a single
// range (for example, a response to a request for a
// single range, or to a request for a set of ranges
// that overlap without any holes), this content is
// transmitted with a Content-Range header, and a
// Content-Length header showing the number of bytes
// actually transferred.
// ...
// A response to a request for a single range MUST NOT
// be sent using the multipart/byteranges media type."
ra := ranges[0]
ctx.Response.Header.Set("Content-Length", strconv.FormatInt(ra.length, 10))
ctx.Response.Header.Set("Content-Range", ra.contentRange(totalSize))
ctx.Response.SetStatusCode(http.StatusPartialContent)
if _, e = rs.Seek(ra.start, 0); e != nil {
return e
}
_, e = io.CopyN(ctx.Response.BodyWriter(), rs, ra.length)
return e
}
// process multiple ranges
for _, ra := range ranges {
if ra.start > totalSize {
ctxError(ctx, "Out of Range", http.StatusRequestedRangeNotSatisfiable)
return nil
}
}
sendSize := rangesMIMESize(ranges, mimeType, totalSize)
pr, pw := io.Pipe()
mw := multipart.NewWriter(pw)
ctx.Response.Header.Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
sendContent := pr
defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
go func() {
for _, ra := range ranges {
part, e := mw.CreatePart(ra.mimeHeader(mimeType, totalSize))
if e != nil {
pw.CloseWithError(e)
return
}
if _, e = rs.Seek(ra.start, 0); e != nil {
pw.CloseWithError(e)
return
}
if _, e = io.CopyN(part, rs, ra.length); e != nil {
pw.CloseWithError(e)
return
}
}
mw.Close()
pw.Close()
}()
if ctx.Response.Header.Peek("Content-Encoding") == nil {
ctx.Response.Header.Set("Content-Length", strconv.FormatInt(sendSize, 10))
}
ctx.Response.Header.SetStatusCode(http.StatusPartialContent)
_, e = io.CopyN(ctx.Response.BodyWriter(), sendContent, sendSize)
return e
}
func fastSetEtag(ctx *fasthttp.RequestCtx, etag string) {
if etag != "" {
if strings.HasPrefix(etag, "\"") {
ctx.Response.Header.Set("ETag", etag)
} else {
ctx.Response.Header.Set("ETag", "\""+etag+"\"")
}
}
}
func ctxError(ctx *fasthttp.RequestCtx, error string, code int) {
ctx.Response.Header.Set("Content-Type", "text/plain; charset=utf-8")
ctx.Response.Header.Set("X-Content-Type-Options", "nosniff")
ctx.Response.SetStatusCode(code)
fmt.Fprintln(ctx.Response.BodyWriter(), error)
}
@@ -1,156 +0,0 @@
package weed_server
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/operation"
"github.com/chrislusf/seaweedfs/weed/stats"
"github.com/chrislusf/seaweedfs/weed/storage/needle"
"github.com/chrislusf/seaweedfs/weed/topology"
)
func (vs *VolumeServer) fastPostHandler(ctx *fasthttp.RequestCtx) {
stats.VolumeServerRequestCounter.WithLabelValues("post").Inc()
start := time.Now()
defer func() {
stats.VolumeServerRequestHistogram.WithLabelValues("post").Observe(time.Since(start).Seconds())
}()
requestPath := string(ctx.Path())
vid, fid, _, _, _ := parseURLPath(requestPath)
volumeId, ve := needle.NewVolumeId(vid)
if ve != nil {
glog.V(0).Infoln("NewVolumeId error:", ve)
writeJsonError(ctx, http.StatusBadRequest, ve)
return
}
if !vs.maybeCheckJwtAuthorization(ctx, vid, fid, true) {
writeJsonError(ctx, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
needle, originalSize, ne := needle.CreateNeedleFromRequest(ctx, vs.FixJpgOrientation, vs.fileSizeLimitBytes)
if ne != nil {
writeJsonError(ctx, http.StatusBadRequest, ne)
return
}
ret := operation.UploadResult{}
_, isUnchanged, writeError := topology.OldReplicatedWrite(vs.GetMaster(), vs.store, volumeId, needle, r)
// http 304 status code does not allow body
if writeError == nil && isUnchanged {
ctx.SetStatusCode(http.StatusNotModified)
return
}
httpStatus := http.StatusCreated
if writeError != nil {
httpStatus = http.StatusInternalServerError
ret.Error = writeError.Error()
}
if needle.HasName() {
ret.Name = string(needle.Name)
}
ret.Size = uint32(originalSize)
ret.ETag = needle.Etag()
fastSetEtag(ctx, ret.ETag)
writeJsonQuiet(ctx, httpStatus, ret)
}
func (vs *VolumeServer) DeleteHandler(ctx *fasthttp.RequestCtx) {
stats.VolumeServerRequestCounter.WithLabelValues("delete").Inc()
start := time.Now()
defer func() {
stats.VolumeServerRequestHistogram.WithLabelValues("delete").Observe(time.Since(start).Seconds())
}()
requestPath := string(ctx.Path())
n := new(needle.Needle)
vid, fid, _, _, _ := parseURLPath(requestPath)
volumeId, _ := needle.NewVolumeId(vid)
n.ParsePath(fid)
if !vs.maybeCheckJwtAuthorization(ctx, vid, fid, true) {
writeJsonError(ctx, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
// glog.V(2).Infof("volume %s deleting %s", vid, n)
cookie := n.Cookie
ecVolume, hasEcVolume := vs.store.FindEcVolume(volumeId)
if hasEcVolume {
count, err := vs.store.DeleteEcShardNeedle(context.Background(), ecVolume, n, cookie)
writeDeleteResult(err, count, ctx)
return
}
_, ok := vs.store.ReadVolumeNeedle(volumeId, n)
if ok != nil {
m := make(map[string]uint32)
m["size"] = 0
writeJsonQuiet(ctx, http.StatusNotFound, m)
return
}
if n.Cookie != cookie {
glog.V(0).Infof("delete %s with unmaching cookie from %s agent %s", requestPath, ctx.RemoteAddr(), ctx.UserAgent())
writeJsonError(ctx, http.StatusBadRequest, errors.New("File Random Cookie does not match."))
return
}
count := int64(n.Size)
if n.IsChunkedManifest() {
chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
if e != nil {
writeJsonError(ctx, http.StatusInternalServerError, fmt.Errorf("Load chunks manifest error: %v", e))
return
}
// make sure all chunks had deleted before delete manifest
if e := chunkManifest.DeleteChunks(vs.GetMaster(), vs.grpcDialOption); e != nil {
writeJsonError(ctx, http.StatusInternalServerError, fmt.Errorf("Delete chunks error: %v", e))
return
}
count = chunkManifest.Size
}
n.LastModified = uint64(time.Now().Unix())
tsValue := ctx.FormValue("ts")
if tsValue != nil {
modifiedTime, err := strconv.ParseInt(string(tsValue), 10, 64)
if err == nil {
n.LastModified = uint64(modifiedTime)
}
}
_, err := topology.ReplicatedDelete(vs.GetMaster(), vs.store, volumeId, n, ctx)
writeDeleteResult(err, count, ctx)
}
func writeDeleteResult(err error, count int64, ctx *fasthttp.RequestCtx) {
if err == nil {
m := make(map[string]int64)
m["size"] = count
writeJsonQuiet(ctx, http.StatusAccepted, m)
} else {
writeJsonQuiet(ctx, http.StatusInternalServerError, fmt.Errorf("Deletion Failed: %v", err))
}
}
+9 -9
View File
@@ -24,32 +24,32 @@ security settings:
*/
func (vs *VolumeServer) oldPrivateStoreHandler(w http.ResponseWriter, r *http.Request) {
func (vs *VolumeServer) privateStoreHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET", "HEAD":
stats.ReadRequest()
vs.OldGetOrHeadHandler(w, r)
vs.GetOrHeadHandler(w, r)
case "DELETE":
stats.DeleteRequest()
vs.guard.OldWhiteList(vs.OldDeleteHandler)(w, r)
vs.guard.WhiteList(vs.DeleteHandler)(w, r)
case "PUT", "POST":
stats.WriteRequest()
vs.guard.OldWhiteList(vs.OldPostHandler)(w, r)
vs.guard.WhiteList(vs.PostHandler)(w, r)
}
}
func (vs *VolumeServer) oldPublicReadOnlyHandler(w http.ResponseWriter, r *http.Request) {
func (vs *VolumeServer) publicReadOnlyHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
stats.ReadRequest()
vs.OldGetOrHeadHandler(w, r)
vs.GetOrHeadHandler(w, r)
case "HEAD":
stats.ReadRequest()
vs.OldGetOrHeadHandler(w, r)
vs.GetOrHeadHandler(w, r)
}
}
func (vs *VolumeServer) oldMaybeCheckJwtAuthorization(r *http.Request, vid, fid string, isWrite bool) bool {
func (vs *VolumeServer) maybeCheckJwtAuthorization(r *http.Request, vid, fid string, isWrite bool) bool {
var signingKey security.SigningKey
@@ -67,7 +67,7 @@ func (vs *VolumeServer) oldMaybeCheckJwtAuthorization(r *http.Request, vid, fid
}
}
tokenStr := security.OldGetJwt(r)
tokenStr := security.GetJwt(r)
if tokenStr == "" {
glog.V(1).Infof("missing jwt from %s", r.RemoteAddr)
return false
+2 -2
View File
@@ -13,7 +13,7 @@ func (vs *VolumeServer) statusHandler(w http.ResponseWriter, r *http.Request) {
m := make(map[string]interface{})
m["Version"] = util.VERSION
m["Volumes"] = vs.store.VolumeInfos()
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
func (vs *VolumeServer) statsDiskHandler(w http.ResponseWriter, r *http.Request) {
@@ -26,5 +26,5 @@ func (vs *VolumeServer) statsDiskHandler(w http.ResponseWriter, r *http.Request)
}
}
m["DiskStatuses"] = ds
oldWriteJsonQuiet(w, r, http.StatusOK, m)
writeJsonQuiet(w, r, http.StatusOK, m)
}
+5 -5
View File
@@ -27,7 +27,7 @@ import (
var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
func (vs *VolumeServer) OldGetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request) {
stats.VolumeServerRequestCounter.WithLabelValues("get").Inc()
start := time.Now()
@@ -36,8 +36,8 @@ func (vs *VolumeServer) OldGetOrHeadHandler(w http.ResponseWriter, r *http.Reque
n := new(needle.Needle)
vid, fid, filename, ext, _ := parseURLPath(r.URL.Path)
if !vs.oldMaybeCheckJwtAuthorization(r, vid, fid, false) {
oldWriteJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
if !vs.maybeCheckJwtAuthorization(r, vid, fid, false) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
@@ -115,9 +115,9 @@ func (vs *VolumeServer) OldGetOrHeadHandler(w http.ResponseWriter, r *http.Reque
return
}
if r.Header.Get("ETag-MD5") == "True" {
oldSetEtag(w, n.MD5())
setEtag(w, n.MD5())
} else {
oldSetEtag(w, n.Etag())
setEtag(w, n.Etag())
}
if n.HasPairs() {
+27 -26
View File
@@ -16,7 +16,7 @@ import (
"github.com/chrislusf/seaweedfs/weed/topology"
)
func (vs *VolumeServer) OldPostHandler(w http.ResponseWriter, r *http.Request) {
func (vs *VolumeServer) PostHandler(w http.ResponseWriter, r *http.Request) {
stats.VolumeServerRequestCounter.WithLabelValues("post").Inc()
start := time.Now()
@@ -26,7 +26,7 @@ func (vs *VolumeServer) OldPostHandler(w http.ResponseWriter, r *http.Request) {
if e := r.ParseForm(); e != nil {
glog.V(0).Infoln("form parse error:", e)
oldWriteJsonError(w, r, http.StatusBadRequest, e)
writeJsonError(w, r, http.StatusBadRequest, e)
return
}
@@ -34,27 +34,28 @@ func (vs *VolumeServer) OldPostHandler(w http.ResponseWriter, r *http.Request) {
volumeId, ve := needle.NewVolumeId(vid)
if ve != nil {
glog.V(0).Infoln("NewVolumeId error:", ve)
oldWriteJsonError(w, r, http.StatusBadRequest, ve)
writeJsonError(w, r, http.StatusBadRequest, ve)
return
}
if !vs.oldMaybeCheckJwtAuthorization(r, vid, fid, true) {
oldWriteJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
if !vs.maybeCheckJwtAuthorization(r, vid, fid, true) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
needle, originalSize, ne := needle.OldCreateNeedleFromRequest(r, vs.FixJpgOrientation, vs.fileSizeLimitBytes)
needle, originalSize, ne := needle.CreateNeedleFromRequest(r, vs.FixJpgOrientation, vs.fileSizeLimitBytes)
if ne != nil {
oldWriteJsonError(w, r, http.StatusBadRequest, ne)
writeJsonError(w, r, http.StatusBadRequest, ne)
return
}
ret := operation.UploadResult{}
_, isUnchanged, writeError := topology.OldReplicatedWrite(vs.GetMaster(), vs.store, volumeId, needle, r)
_, isUnchanged, writeError := topology.ReplicatedWrite(vs.GetMaster(), vs.store, volumeId, needle, r)
// http 304 status code does not allow body
// http 204 status code does not allow body
if writeError == nil && isUnchanged {
w.WriteHeader(http.StatusNotModified)
setEtag(w, needle.Etag())
w.WriteHeader(http.StatusNoContent)
return
}
@@ -68,11 +69,11 @@ func (vs *VolumeServer) OldPostHandler(w http.ResponseWriter, r *http.Request) {
}
ret.Size = uint32(originalSize)
ret.ETag = needle.Etag()
oldSetEtag(w, ret.ETag)
oldWriteJsonQuiet(w, r, httpStatus, ret)
setEtag(w, ret.ETag)
writeJsonQuiet(w, r, httpStatus, ret)
}
func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request) {
func (vs *VolumeServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
stats.VolumeServerRequestCounter.WithLabelValues("delete").Inc()
start := time.Now()
@@ -85,8 +86,8 @@ func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request)
volumeId, _ := needle.NewVolumeId(vid)
n.ParsePath(fid)
if !vs.oldMaybeCheckJwtAuthorization(r, vid, fid, true) {
oldWriteJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
if !vs.maybeCheckJwtAuthorization(r, vid, fid, true) {
writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt"))
return
}
@@ -98,7 +99,7 @@ func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request)
if hasEcVolume {
count, err := vs.store.DeleteEcShardNeedle(context.Background(), ecVolume, n, cookie)
oldWriteDeleteResult(err, count, w, r)
writeDeleteResult(err, count, w, r)
return
}
@@ -106,13 +107,13 @@ func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request)
if ok != nil {
m := make(map[string]uint32)
m["size"] = 0
oldWriteJsonQuiet(w, r, http.StatusNotFound, m)
writeJsonQuiet(w, r, http.StatusNotFound, m)
return
}
if n.Cookie != cookie {
glog.V(0).Infoln("delete", r.URL.Path, "with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
oldWriteJsonError(w, r, http.StatusBadRequest, errors.New("File Random Cookie does not match."))
writeJsonError(w, r, http.StatusBadRequest, errors.New("File Random Cookie does not match."))
return
}
@@ -121,12 +122,12 @@ func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request)
if n.IsChunkedManifest() {
chunkManifest, e := operation.LoadChunkManifest(n.Data, n.IsGzipped())
if e != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Load chunks manifest error: %v", e))
writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Load chunks manifest error: %v", e))
return
}
// make sure all chunks had deleted before delete manifest
if e := chunkManifest.DeleteChunks(vs.GetMaster(), vs.grpcDialOption); e != nil {
oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Delete chunks error: %v", e))
writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Delete chunks error: %v", e))
return
}
count = chunkManifest.Size
@@ -140,23 +141,23 @@ func (vs *VolumeServer) OldDeleteHandler(w http.ResponseWriter, r *http.Request)
}
}
_, err := topology.OldReplicatedDelete(vs.GetMaster(), vs.store, volumeId, n, r)
_, err := topology.ReplicatedDelete(vs.GetMaster(), vs.store, volumeId, n, r)
oldWriteDeleteResult(err, count, w, r)
writeDeleteResult(err, count, w, r)
}
func oldWriteDeleteResult(err error, count int64, w http.ResponseWriter, r *http.Request) {
func writeDeleteResult(err error, count int64, w http.ResponseWriter, r *http.Request) {
if err == nil {
m := make(map[string]int64)
m["size"] = count
oldWriteJsonQuiet(w, r, http.StatusAccepted, m)
writeJsonQuiet(w, r, http.StatusAccepted, m)
} else {
oldWriteJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Deletion Failed: %v", err))
writeJsonError(w, r, http.StatusInternalServerError, fmt.Errorf("Deletion Failed: %v", err))
}
}
func oldSetEtag(w http.ResponseWriter, etag string) {
func setEtag(w http.ResponseWriter, etag string) {
if etag != "" {
if strings.HasPrefix(etag, "\"") {
w.Header().Set("ETag", etag)
+30 -21
View File
@@ -50,29 +50,39 @@ func parseCollectionVolumeId(base string) (collection string, vid needle.VolumeI
return collection, vol, err
}
func (l *DiskLocation) loadExistingVolume(fileInfo os.FileInfo, needleMapKind NeedleMapType) {
func (l *DiskLocation) loadExistingVolume(fileInfo os.FileInfo, needleMapKind NeedleMapType) bool {
name := fileInfo.Name()
if !fileInfo.IsDir() && strings.HasSuffix(name, ".idx") {
vid, collection, err := l.volumeIdFromPath(fileInfo)
if err == nil {
l.volumesLock.RLock()
_, found := l.volumes[vid]
l.volumesLock.RUnlock()
if !found {
if v, e := NewVolume(l.Directory, collection, vid, needleMapKind, nil, nil, 0, 0); e == nil {
l.volumesLock.Lock()
l.volumes[vid] = v
l.volumesLock.Unlock()
size, _, _ := v.FileStat()
glog.V(0).Infof("data file %s, replicaPlacement=%s v=%d size=%d ttl=%s",
l.Directory+"/"+name, v.ReplicaPlacement, v.Version(), size, v.Ttl.String())
// println("volume", vid, "last append at", v.lastAppendAtNs)
} else {
glog.V(0).Infof("new volume %s error %s", name, e)
}
}
if err != nil {
glog.Warningf("get volume id failed, %s, err : %s", name, err)
return false
}
// void loading one volume more than once
l.volumesLock.RLock()
_, found := l.volumes[vid]
l.volumesLock.RUnlock()
if found {
glog.V(1).Infof("loaded volume, %v", vid)
return true
}
v, e := NewVolume(l.Directory, collection, vid, needleMapKind, nil, nil, 0, 0)
if e != nil {
glog.V(0).Infof("new volume %s error %s", name, e)
return false
}
l.volumesLock.Lock()
l.volumes[vid] = v
l.volumesLock.Unlock()
size, _, _ := v.FileStat()
glog.V(0).Infof("data file %s, replicaPlacement=%s v=%d size=%d ttl=%s",
l.Directory+"/"+name, v.ReplicaPlacement, v.Version(), size, v.Ttl.String())
return true
}
return false
}
func (l *DiskLocation) concurrentLoadingVolumes(needleMapKind NeedleMapType, concurrency int) {
@@ -93,7 +103,7 @@ func (l *DiskLocation) concurrentLoadingVolumes(needleMapKind NeedleMapType, con
go func() {
defer wg.Done()
for dir := range task_queue {
l.loadExistingVolume(dir, needleMapKind)
_ = l.loadExistingVolume(dir, needleMapKind)
}
}()
}
@@ -172,8 +182,7 @@ func (l *DiskLocation) deleteVolumeById(vid needle.VolumeId) (e error) {
func (l *DiskLocation) LoadVolume(vid needle.VolumeId, needleMapKind NeedleMapType) bool {
if fileInfo, found := l.LocateVolume(vid); found {
l.loadExistingVolume(fileInfo, needleMapKind)
return true
return l.loadExistingVolume(fileInfo, needleMapKind)
}
return false
}
+5 -111
View File
@@ -1,7 +1,6 @@
package needle
import (
"bytes"
"encoding/json"
"fmt"
"io"
@@ -11,18 +10,13 @@ import (
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/images"
. "github.com/chrislusf/seaweedfs/weed/storage/types"
)
const (
NeedleChecksumSize = 4
PairNamePrefix = "Seaweed-"
)
var (
PairNamePrefixBytes = []byte("Seaweed-")
NeedleChecksumSize = 4
PairNamePrefix = "Seaweed-"
)
/*
@@ -56,7 +50,7 @@ func (n *Needle) String() (str string) {
return
}
func OldParseUpload(r *http.Request, sizeLimit int64) (
func ParseUpload(r *http.Request, sizeLimit int64) (
fileName string, data []byte, mimeType string, pairMap map[string]string, isGzipped bool, originalDataSize int,
modifiedTime uint64, ttl *TTL, isChunkedFile bool, e error) {
pairMap = make(map[string]string)
@@ -88,45 +82,11 @@ func OldParseUpload(r *http.Request, sizeLimit int64) (
return
}
func ParseUpload(ctx *fasthttp.RequestCtx, sizeLimit int64) (
fileName string, data []byte, mimeType string, pairMap map[string]string, isGzipped bool, originalDataSize int,
modifiedTime uint64, ttl *TTL, isChunkedFile bool, e error) {
pairMap = make(map[string]string)
ctx.Request.Header.VisitAll(func(k, v []byte) {
if len(v) > 0 && bytes.HasPrefix(k, PairNamePrefixBytes) {
pairMap[string(k)] = string(v)
}
})
if ctx.IsPost() {
fileName, data, mimeType, isGzipped, originalDataSize, isChunkedFile, e = parseMultipart(r, sizeLimit)
} else {
isGzipped = false
mimeType = string(ctx.Request.Header.Peek("Content-Type"))
fileName = ""
data, e = ioutil.ReadAll(io.LimitReader(ctx.PostBody(), sizeLimit+1))
originalDataSize = len(data)
if e == io.EOF || int64(originalDataSize) == sizeLimit+1 {
io.Copy(ioutil.Discard, r.Body)
}
r.Body.Close()
}
if e != nil {
return
}
modifiedTime, _ = strconv.ParseUint(r.FormValue("ts"), 10, 64)
ttl, _ = ReadTTL(r.FormValue("ttl"))
return
}
func OldCreateNeedleFromRequest(r *http.Request, fixJpgOrientation bool, sizeLimit int64) (n *Needle, originalSize int, e error) {
func CreateNeedleFromRequest(r *http.Request, fixJpgOrientation bool, sizeLimit int64) (n *Needle, originalSize int, e error) {
var pairMap map[string]string
fname, mimeType, isGzipped, isChunkedFile := "", "", false, false
n = new(Needle)
fname, n.Data, mimeType, pairMap, isGzipped, originalSize, n.LastModified, n.Ttl, isChunkedFile, e = OldParseUpload(r, sizeLimit)
fname, n.Data, mimeType, pairMap, isGzipped, originalSize, n.LastModified, n.Ttl, isChunkedFile, e = ParseUpload(r, sizeLimit)
if e != nil {
return
}
@@ -186,72 +146,6 @@ func OldCreateNeedleFromRequest(r *http.Request, fixJpgOrientation bool, sizeLim
return
}
func CreateNeedleFromRequest(ctx *fasthttp.RequestCtx, fixJpgOrientation bool, sizeLimit int64) (n *Needle, originalSize int, e error) {
var pairMap map[string]string
fname, mimeType, isGzipped, isChunkedFile := "", "", false, false
n = new(Needle)
fname, n.Data, mimeType, pairMap, isGzipped, originalSize, n.LastModified, n.Ttl, isChunkedFile, e = OldParseUpload(r, sizeLimit)
if e != nil {
return
}
if len(fname) < 256 {
n.Name = []byte(fname)
n.SetHasName()
}
if len(mimeType) < 256 {
n.Mime = []byte(mimeType)
n.SetHasMime()
}
if len(pairMap) != 0 {
trimmedPairMap := make(map[string]string)
for k, v := range pairMap {
trimmedPairMap[k[len(PairNamePrefix):]] = v
}
pairs, _ := json.Marshal(trimmedPairMap)
if len(pairs) < 65536 {
n.Pairs = pairs
n.PairsSize = uint16(len(pairs))
n.SetHasPairs()
}
}
if isGzipped {
n.SetGzipped()
}
if n.LastModified == 0 {
n.LastModified = uint64(time.Now().Unix())
}
n.SetHasLastModifiedDate()
if n.Ttl != EMPTY_TTL {
n.SetHasTtl()
}
if isChunkedFile {
n.SetIsChunkManifest()
}
if fixJpgOrientation {
loweredName := strings.ToLower(fname)
if mimeType == "image/jpeg" || strings.HasSuffix(loweredName, ".jpg") || strings.HasSuffix(loweredName, ".jpeg") {
n.Data = images.FixJpgOrientation(n.Data)
}
}
n.Checksum = NewCRC(n.Data)
commaSep := strings.LastIndex(r.URL.Path, ",")
dotSep := strings.LastIndex(r.URL.Path, ".")
fid := r.URL.Path[commaSep+1:]
if dotSep > 0 {
fid = r.URL.Path[commaSep+1 : dotSep]
}
e = n.ParsePath(fid)
return
}
func (n *Needle) ParsePath(fid string) (err error) {
length := len(fid)
if length <= CookieSize*2 {
+4 -105
View File
@@ -10,8 +10,6 @@ import (
"strconv"
"strings"
"github.com/valyala/fasthttp"
"github.com/chrislusf/seaweedfs/weed/glog"
"github.com/chrislusf/seaweedfs/weed/operation"
"github.com/chrislusf/seaweedfs/weed/security"
@@ -20,12 +18,12 @@ import (
"github.com/chrislusf/seaweedfs/weed/util"
)
func OldReplicatedWrite(masterNode string, s *storage.Store,
func ReplicatedWrite(masterNode string, s *storage.Store,
volumeId needle.VolumeId, n *needle.Needle,
r *http.Request) (size uint32, isUnchanged bool, err error) {
//check JWT
jwt := security.OldGetJwt(r)
jwt := security.GetJwt(r)
var remoteLocations []operation.Location
if r.FormValue("type") != "replicate" {
@@ -87,79 +85,12 @@ func OldReplicatedWrite(masterNode string, s *storage.Store,
return
}
func ReplicatedWrite(masterNode string, s *storage.Store,
volumeId needle.VolumeId, n *needle.Needle,
ctx *fasthttp.RequestCtx) (size uint32, isUnchanged bool, err error) {
//check JWT
jwt := security.GetJwt(ctx)
var remoteLocations []operation.Location
if string(ctx.FormValue("type")) != "replicate" {
remoteLocations, err = getWritableRemoteReplications(s, volumeId, masterNode)
if err != nil {
glog.V(0).Infoln(err)
return
}
}
size, isUnchanged, err = s.WriteVolumeNeedle(volumeId, n)
if err != nil {
err = fmt.Errorf("failed to write to local disk: %v", err)
glog.V(0).Infoln(err)
return
}
if len(remoteLocations) > 0 { //send to other replica locations
if err = distributedOperation(remoteLocations, s, func(location operation.Location) error {
u := url.URL{
Scheme: "http",
Host: location.Url,
Path: string(ctx.Path()),
}
q := url.Values{
"type": {"replicate"},
"ttl": {n.Ttl.String()},
}
if n.LastModified > 0 {
q.Set("ts", strconv.FormatUint(n.LastModified, 10))
}
if n.IsChunkedManifest() {
q.Set("cm", "true")
}
u.RawQuery = q.Encode()
pairMap := make(map[string]string)
if n.HasPairs() {
tmpMap := make(map[string]string)
err := json.Unmarshal(n.Pairs, &tmpMap)
if err != nil {
glog.V(0).Infoln("Unmarshal pairs error:", err)
}
for k, v := range tmpMap {
pairMap[needle.PairNamePrefix+k] = v
}
}
_, err := operation.Upload(u.String(),
string(n.Name), bytes.NewReader(n.Data), n.IsGzipped(), string(n.Mime),
pairMap, jwt)
return err
}); err != nil {
size = 0
err = fmt.Errorf("failed to write to replicas for volume %d: %v", volumeId, err)
glog.V(0).Infoln(err)
}
}
return
}
func OldReplicatedDelete(masterNode string, store *storage.Store,
func ReplicatedDelete(masterNode string, store *storage.Store,
volumeId needle.VolumeId, n *needle.Needle,
r *http.Request) (size uint32, err error) {
//check JWT
jwt := security.OldGetJwt(r)
jwt := security.GetJwt(r)
var remoteLocations []operation.Location
if r.FormValue("type") != "replicate" {
@@ -186,38 +117,6 @@ func OldReplicatedDelete(masterNode string, store *storage.Store,
return
}
func ReplicatedDelete(masterNode string, store *storage.Store,
volumeId needle.VolumeId, n *needle.Needle,
ctx *fasthttp.RequestCtx) (size uint32, err error) {
//check JWT
jwt := security.GetJwt(ctx)
var remoteLocations []operation.Location
if string(ctx.FormValue("type")) != "replicate" {
remoteLocations, err = getWritableRemoteReplications(store, volumeId, masterNode)
if err != nil {
glog.V(0).Infoln(err)
return
}
}
size, err = store.DeleteVolumeNeedle(volumeId, n)
if err != nil {
glog.V(0).Infoln("delete error:", err)
return
}
if len(remoteLocations) > 0 { //send to other replica locations
if err = distributedOperation(remoteLocations, store, func(location operation.Location) error {
return util.Delete("http://"+location.Url+string(ctx.Path())+"?type=replicate", string(jwt))
}); err != nil {
size = 0
}
}
return
}
type DistributedOperationResult map[string]error
func (dr DistributedOperationResult) Error() error {
+1 -1
View File
@@ -5,5 +5,5 @@ import (
)
var (
VERSION = fmt.Sprintf("%s %d.%d", sizeLimit, 1, 54)
VERSION = fmt.Sprintf("%s %d.%d", sizeLimit, 1, 56)
)
+12 -7
View File
@@ -35,13 +35,13 @@ func PostBytes(url string, body []byte) ([]byte, error) {
return nil, fmt.Errorf("Post to %s: %v", url, err)
}
defer r.Body.Close()
if r.StatusCode >= 400 {
return nil, fmt.Errorf("%s: %s", url, r.Status)
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("Read response body: %v", err)
}
if r.StatusCode >= 400 {
return nil, fmt.Errorf("%s: %s", url, r.Status)
}
return b, nil
}
@@ -88,7 +88,7 @@ func Head(url string) (http.Header, error) {
if err != nil {
return nil, err
}
defer r.Body.Close()
defer CloseResponse(r)
if r.StatusCode >= 400 {
return nil, fmt.Errorf("%s: %s", url, r.Status)
}
@@ -130,7 +130,7 @@ func GetBufferStream(url string, values url.Values, allocatedBytes []byte, eachB
if err != nil {
return err
}
defer r.Body.Close()
defer CloseResponse(r)
if r.StatusCode != 200 {
return fmt.Errorf("%s: %s", url, r.Status)
}
@@ -153,7 +153,7 @@ func GetUrlStream(url string, values url.Values, readFn func(io.Reader) error) e
if err != nil {
return err
}
defer r.Body.Close()
defer CloseResponse(r)
if r.StatusCode != 200 {
return fmt.Errorf("%s: %s", url, r.Status)
}
@@ -262,7 +262,7 @@ func ReadUrlAsStream(fileUrl string, offset int64, size int, fn func(data []byte
if err != nil {
return 0, err
}
defer r.Body.Close()
defer CloseResponse(r)
if r.StatusCode >= 400 {
return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
}
@@ -307,3 +307,8 @@ func ReadUrlAsReaderCloser(fileUrl string, rangeHeader string) (io.ReadCloser, e
return r.Body, nil
}
func CloseResponse(resp *http.Response) {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
+2 -5
View File
@@ -66,11 +66,8 @@ func (c *Conn) Write(b []byte) (count int, e error) {
}
func (c *Conn) Close() error {
err := c.Conn.Close()
if err == nil {
stats.ConnectionClose()
}
return err
stats.ConnectionClose()
return c.Conn.Close()
}
func NewListener(addr string, timeout time.Duration) (net.Listener, error) {