diff --git a/cmd/client-fs.go b/cmd/client-fs.go index d00b1694..dec74b61 100644 --- a/cmd/client-fs.go +++ b/cmd/client-fs.go @@ -965,7 +965,7 @@ func (f *fsClient) SetAccess(access string) *probe.Error { } // Stat - get metadata from path. -func (f *fsClient) Stat(isIncomplete bool) (content *clientContent, err *probe.Error) { +func (f *fsClient) Stat(isIncomplete, isFetchMeta bool) (content *clientContent, err *probe.Error) { st, err := f.fsStat(isIncomplete) if err != nil { return nil, err.Trace(f.PathURL.String()) @@ -975,9 +975,15 @@ func (f *fsClient) Stat(isIncomplete bool) (content *clientContent, err *probe.E content.Size = st.Size() content.Time = st.ModTime() content.Type = st.Mode() - content.Metadata = map[string][]string{ - "Content-Type": {guessURLContentType(f.PathURL.Path)}, + content.Metadata = map[string]string{ + "Content-Type": guessURLContentType(f.PathURL.Path), } + path := f.PathURL.String() + metaData, pErr := getAllXattrs(path) + if pErr != nil { + return content, nil + } + content.Metadata = metaData return content, nil } diff --git a/cmd/client-fs_darwin.go b/cmd/client-fs_darwin.go new file mode 100644 index 00000000..b0ec4498 --- /dev/null +++ b/cmd/client-fs_darwin.go @@ -0,0 +1,84 @@ +// +build darwin + +/* + * Minio Client (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this fs 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 cmd + +import ( + "github.com/pkg/xattr" + "github.com/rjeczalik/notify" +) + +var ( + // EventTypePut contains the notify events that will cause a put (writer) + EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename} + // EventTypeDelete contains the notify events that will cause a delete (remove) + EventTypeDelete = []notify.Event{notify.Remove} + // EventTypeGet contains the notify events that will cause a get (read) + EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available. +) + +// IsGetEvent checks if the event return is a get event. +func IsGetEvent(event notify.Event) bool { + return false +} + +// IsPutEvent checks if the event returned is a put event +func IsPutEvent(event notify.Event) bool { + for _, ev := range EventTypePut { + if event&ev != 0 { + return true + } + } + return false +} + +// IsDeleteEvent checks if the event returned is a delete event +func IsDeleteEvent(event notify.Event) bool { + return event¬ify.Remove != 0 +} + +// getXAttr fetches the extended attribute for a particular key on +// file +func getXAttr(path, key string) (string, error) { + data, e := xattr.Get(path, key) + if e != nil { + return "", e + } + return string(data), nil +} + +// getAllXattrs returns the extended attributes for a file if supported +// by the OS +func getAllXattrs(path string) (map[string]string, error) { + if !xattr.Supported(path) { + return nil, nil + } + xMetadata := make(map[string]string) + list, e := xattr.List(path) + if e != nil { + return nil, e + } + for _, key := range list { + xMetadata[key], e = getXAttr(path, key) + if e != nil { + return nil, e + } + + } + return xMetadata, nil +} diff --git a/cmd/client-fs_freebsd.go b/cmd/client-fs_freebsd.go new file mode 100644 index 00000000..06d35a76 --- /dev/null +++ b/cmd/client-fs_freebsd.go @@ -0,0 +1,84 @@ +// +build freebsd + +/* + * Minio Client (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this fs 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 cmd + +import ( + "github.com/pkg/xattr" + "github.com/rjeczalik/notify" +) + +var ( + // EventTypePut contains the notify events that will cause a put (writer) + EventTypePut = []notify.Event{notify.Create, notify.Write, notify.Rename} + // EventTypeDelete contains the notify events that will cause a delete (remove) + EventTypeDelete = []notify.Event{notify.Remove} + // EventTypeGet contains the notify events that will cause a get (read) + EventTypeGet = []notify.Event{} // On macOS, FreeBSD, Solaris this is not available. +) + +// IsGetEvent checks if the event return is a get event. +func IsGetEvent(event notify.Event) bool { + return false +} + +// IsPutEvent checks if the event returned is a put event +func IsPutEvent(event notify.Event) bool { + for _, ev := range EventTypePut { + if event&ev != 0 { + return true + } + } + return false +} + +// IsDeleteEvent checks if the event returned is a delete event +func IsDeleteEvent(event notify.Event) bool { + return event¬ify.Remove != 0 +} + +// getXAttr fetches the extended attribute for a particular key on +// file +func getXAttr(path, key string) (string, error) { + data, e := xattr.Get(path, key) + if e != nil { + return "", e + } + return string(data), nil +} + +// getAllXattrs returns the extended attributes for a file if supported +// by the OS +func getAllXattrs(path string) (map[string]string, error) { + if !xattr.Supported(path) { + return nil, nil + } + xMetadata := make(map[string]string) + list, e := xattr.List(path) + if e != nil { + return nil, e + } + for _, key := range list { + xMetadata[key], e = getXAttr(path, key) + if e != nil { + return nil, e + } + + } + return xMetadata, nil +} diff --git a/cmd/client-fs_linux.go b/cmd/client-fs_linux.go index cf734062..200e2456 100644 --- a/cmd/client-fs_linux.go +++ b/cmd/client-fs_linux.go @@ -19,7 +19,13 @@ package cmd import ( + "encoding/hex" + "strings" + + "github.com/pkg/xattr" "github.com/rjeczalik/notify" + + "unicode/utf8" ) var ( @@ -60,3 +66,40 @@ func IsDeleteEvent(event notify.Event) bool { } return false } + +// getXAttr fetches the extended attribute for a particular key on +// file +func getXAttr(path, key string) (string, error) { + data, e := xattr.Get(path, key) + if e != nil { + return "", e + } + if utf8.ValidString(string(data)) { + return string(data), nil + } + return hex.EncodeToString(data), nil +} + +// getAllXattrs returns the extended attributes for a file if supported +// by the OS +func getAllXattrs(path string) (map[string]string, error) { + if !xattr.Supported(path) { + return nil, nil + } + xMetadata := make(map[string]string) + list, e := xattr.List(path) + if e != nil { + return nil, e + } + for _, key := range list { + // filter out system specific xattr + if strings.HasPrefix(key, "system.") { + continue + } + xMetadata[key], e = getXAttr(path, key) + if e != nil { + return nil, e + } + } + return xMetadata, nil +} diff --git a/cmd/client-fs_other.go b/cmd/client-fs_other.go index fd2cbb1f..cdfffe94 100644 --- a/cmd/client-fs_other.go +++ b/cmd/client-fs_other.go @@ -1,4 +1,4 @@ -// +build darwin freebsd solaris +// +build solaris /* * Minio Client (C) 2015, 2016, 2017 Minio, Inc. @@ -48,3 +48,9 @@ func IsPutEvent(event notify.Event) bool { func IsDeleteEvent(event notify.Event) bool { return event¬ify.Remove != 0 } + +// getAtllXAttrs returns the extended attributes for a file if supported +// by the OS +func getAllXattrs(path string) (map[string]string, error) { + return nil, nil +} diff --git a/cmd/client-fs_test.go b/cmd/client-fs_test.go index 21cb5897..2fc30a27 100644 --- a/cmd/client-fs_test.go +++ b/cmd/client-fs_test.go @@ -210,7 +210,7 @@ func (s *TestSuite) TestStatBucket(c *C) { c.Assert(err, IsNil) err = fsClient.MakeBucket("us-east-1", true) c.Assert(err, IsNil) - _, err = fsClient.Stat(false) + _, err = fsClient.Stat(false, false) c.Assert(err, IsNil) } @@ -334,7 +334,7 @@ func (s *TestSuite) TestStatObject(c *C) { c.Assert(err, IsNil) c.Assert(n, Equals, int64(len(data))) - content, err := fsClient.Stat(false) + content, err := fsClient.Stat(false, false) c.Assert(err, IsNil) c.Assert(content.Size, Equals, int64(dataLen)) } diff --git a/cmd/client-fs_windows.go b/cmd/client-fs_windows.go index b7784538..ac48474e 100644 --- a/cmd/client-fs_windows.go +++ b/cmd/client-fs_windows.go @@ -48,3 +48,9 @@ func IsPutEvent(event notify.Event) bool { func IsDeleteEvent(event notify.Event) bool { return event¬ify.Remove != 0 } + +// getAllXattrs returns the extended attributes for a file if supported +// by the OS +func getAllXattrs(path string) (map[string]string, error) { + return nil, nil +} diff --git a/cmd/client-s3.go b/cmd/client-s3.go index 479cce40..f9aa886f 100644 --- a/cmd/client-s3.go +++ b/cmd/client-s3.go @@ -54,9 +54,17 @@ const ( amazonHostName = "s3.amazonaws.com" amazonHostNameAccelerated = "s3-accelerate.amazonaws.com" - googleHostName = "storage.googleapis.com" + googleHostName = "storage.googleapis.com" + serverEncryptionKeyPrefix = "x-amz-server-side-encryption" ) +// cseHeaders is list of client side encryption headers +var cseHeaders = []string{ + "X-Amz-Meta-X-Amz-Iv", + "X-Amz-Meta-X-Amz-Key", + "X-Amz-Meta-X-Amz-Matdesc", +} + // getNumMultiPartThreads gets the number of multipart threads to be used for mc cp/mirror functions // If not set, default to 4. func getNumMultiPartThreads() uint { @@ -814,7 +822,7 @@ func (c *s3Client) listObjectWrapper(bucket, object string, isRecursive bool, do } // Stat - send a 'HEAD' on a bucket or object to fetch its metadata. -func (c *s3Client) Stat(isIncomplete bool) (*clientContent, *probe.Error) { +func (c *s3Client) Stat(isIncomplete, isFetchMeta bool) (*clientContent, *probe.Error) { c.mutex.Lock() defer c.mutex.Unlock() bucket, object := c.url2BucketAndObject() @@ -831,12 +839,8 @@ func (c *s3Client) Stat(isIncomplete bool) (*clientContent, *probe.Error) { if !exists { return nil, probe.NewError(BucketDoesNotExist{Bucket: bucket}) } - bucketMetadata := &clientContent{} - bucketMetadata.URL = *c.targetURL - bucketMetadata.Type = os.ModeDir - bucketMetadata.Metadata = map[string][]string{} - - return bucketMetadata, nil + bucketMetadata := c.bucketStat() + return &bucketMetadata, nil } // Remove trailing slashes needed for the following ListObjects call. @@ -858,14 +862,17 @@ func (c *s3Client) Stat(isIncomplete bool) (*clientContent, *probe.Error) { objectMetadata.Time = objectMultipartInfo.Initiated objectMetadata.Size = objectMultipartInfo.Size objectMetadata.Type = os.FileMode(0664) - objectMetadata.Metadata = map[string][]string{} + objectMetadata.Metadata = map[string]string{} + objectMetadata.EncryptionHeaders = map[string]string{} return objectMetadata, nil } if strings.HasSuffix(objectMultipartInfo.Key, string(c.targetURL.Separator)) { objectMetadata.URL = *c.targetURL objectMetadata.Type = os.ModeDir - objectMetadata.Metadata = map[string][]string{} + objectMetadata.Metadata = map[string]string{} + objectMetadata.EncryptionHeaders = map[string]string{} + return objectMetadata, nil } } @@ -876,24 +883,48 @@ func (c *s3Client) Stat(isIncomplete bool) (*clientContent, *probe.Error) { if objectStat.Err != nil { return nil, probe.NewError(objectStat.Err) } - if objectStat.Key == object { objectMetadata.URL = *c.targetURL objectMetadata.Time = objectStat.LastModified objectMetadata.Size = objectStat.Size objectMetadata.ETag = objectStat.ETag objectMetadata.Type = os.FileMode(0664) - objectMetadata.Metadata = map[string][]string{} + objectMetadata.Metadata = map[string]string{} + objectMetadata.EncryptionHeaders = map[string]string{} + if isFetchMeta { + stat, err := c.getObjectStat(bucket, object) + if err != nil { + return nil, err + } + objectMetadata.Metadata = stat.Metadata + objectMetadata.EncryptionHeaders = stat.EncryptionHeaders + } return objectMetadata, nil } if strings.HasSuffix(objectStat.Key, string(c.targetURL.Separator)) { objectMetadata.URL = *c.targetURL objectMetadata.Type = os.ModeDir - objectMetadata.Metadata = map[string][]string{} + + if isFetchMeta { + stat, err := c.getObjectStat(bucket, object) + if err != nil { + return nil, err + } + objectMetadata.ETag = stat.ETag + objectMetadata.Metadata = stat.Metadata + objectMetadata.EncryptionHeaders = stat.EncryptionHeaders + } return objectMetadata, nil } } + return c.getObjectStat(bucket, object) +} + +// getObjectStat returns the metadata of an object from a HEAD call. +func (c *s3Client) getObjectStat(bucket, object string) (*clientContent, *probe.Error) { + objectMetadata := &clientContent{} + objectStat, e := c.api.StatObject(bucket, object, minio.StatObjectOptions{}) if e != nil { errResponse := minio.ToErrorResponse(e) @@ -920,11 +951,28 @@ func (c *s3Client) Stat(isIncomplete bool) (*clientContent, *probe.Error) { objectMetadata.Size = objectStat.Size objectMetadata.ETag = objectStat.ETag objectMetadata.Type = os.FileMode(0664) - - metadata := objectStat.Metadata - metadata.Set("Content-Type", objectStat.ContentType) - objectMetadata.Metadata = metadata - + objectMetadata.Metadata = map[string]string{} + objectMetadata.EncryptionHeaders = map[string]string{} + objectMetadata.Metadata["Content-Type"] = objectStat.ContentType + for k, v := range objectStat.Metadata { + isCSEHeader := false + for _, header := range cseHeaders { + if (strings.Compare(strings.ToLower(header), strings.ToLower(k)) == 0) || + strings.HasPrefix(strings.ToLower(serverEncryptionKeyPrefix), strings.ToLower(k)) { + if len(v) > 0 { + objectMetadata.EncryptionHeaders[k] = v[0] + } + isCSEHeader = true + break + } + } + if !isCSEHeader { + if len(v) > 0 { + objectMetadata.Metadata[k] = v[0] + } + } + } + objectMetadata.ETag = objectStat.ETag return objectMetadata, nil } @@ -1346,7 +1394,8 @@ func (c *s3Client) listRecursiveInRoutineDirOpt(contentCh chan *clientContent, d } else if strings.HasSuffix(object, string(c.targetURL.Separator)) { // Get stat of given object is a directory. isIncomplete := false - content, perr := c.Stat(isIncomplete) + isFetchMeta := false + content, perr := c.Stat(isIncomplete, isFetchMeta) cContent = content if perr != nil { contentCh <- &clientContent{URL: *c.targetURL, Err: perr} diff --git a/cmd/client-url.go b/cmd/client-url.go index ff6d7dfc..c8824f9c 100644 --- a/cmd/client-url.go +++ b/cmd/client-url.go @@ -172,11 +172,16 @@ func urlJoinPath(url1, url2 string) string { // url2Stat returns stat info for URL. func url2Stat(urlStr string) (client Client, content *clientContent, err *probe.Error) { + return url2StatWithMetadata(urlStr, false) +} + +// url2Stat returns stat info for URL. +func url2StatWithMetadata(urlStr string, isFetchMeta bool) (client Client, content *clientContent, err *probe.Error) { client, err = newClient(urlStr) if err != nil { return nil, nil, err.Trace(urlStr) } - content, err = client.Stat(false) + content, err = client.Stat(false, isFetchMeta) if err != nil { return nil, nil, err.Trace(urlStr) } diff --git a/cmd/client.go b/cmd/client.go index 9b7f0ade..4563b06b 100644 --- a/cmd/client.go +++ b/cmd/client.go @@ -43,7 +43,7 @@ const defaultMultipartThreadsNum = 4 // Client - client interface type Client interface { // Common operations - Stat(isIncomplete bool) (content *clientContent, err *probe.Error) + Stat(isIncomplete, isFetchMeta bool) (content *clientContent, err *probe.Error) List(isRecursive, isIncomplete bool, showDir DirOpt) <-chan *clientContent // Bucket operations @@ -77,13 +77,14 @@ type Client interface { // Content container for content metadata type clientContent struct { - URL clientURL - Time time.Time - Size int64 - Type os.FileMode - ETag string - Metadata map[string][]string - Err *probe.Error + URL clientURL + Time time.Time + Size int64 + Type os.FileMode + Metadata map[string]string + ETag string + EncryptionHeaders map[string]string + Err *probe.Error } // Config - see http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?RESTAuthentication.html diff --git a/cmd/common-methods.go b/cmd/common-methods.go index 3f51b760..c51cf211 100644 --- a/cmd/common-methods.go +++ b/cmd/common-methods.go @@ -87,14 +87,12 @@ func getSourceStream(alias string, urlStr string, fetchStat bool) (reader io.Rea } metadata = map[string]string{} if fetchStat { - st, err := sourceClnt.Stat(false) + st, err := sourceClnt.Stat(false, false) if err != nil { return nil, nil, err.Trace(alias, urlStr) } for k, v := range st.Metadata { - if len(v) > 0 { - metadata[k] = v[0] - } + metadata[k] = v } } return reader, metadata, nil diff --git a/cmd/config-host-add.go b/cmd/config-host-add.go index 6e226417..b34355f0 100644 --- a/cmd/config-host-add.go +++ b/cmd/config-host-add.go @@ -154,7 +154,7 @@ func newS3Config(args cli.Args) (*Config, *probe.Error) { return nil, err.Trace(args...) } - if _, err = s3Client.Stat(false); err != nil { + if _, err = s3Client.Stat(false, false); err != nil { switch err.ToGoError().(type) { case BucketDoesNotExist: // Bucket doesn't exist, means signature probing worked V4. @@ -165,7 +165,7 @@ func newS3Config(args cli.Args) (*Config, *probe.Error) { if err != nil { return nil, err.Trace(args...) } - if _, err = s3Client.Stat(false); err != nil { + if _, err = s3Client.Stat(false, false); err != nil { switch err.ToGoError().(type) { case BucketDoesNotExist: // Bucket doesn't exist, means signature probing worked with V2. diff --git a/cmd/find.go b/cmd/find.go index 17967f69..90536664 100644 --- a/cmd/find.go +++ b/cmd/find.go @@ -430,7 +430,7 @@ func getShareURL(path string) string { clnt, err := newClientFromAlias(targetAlias, targetURLFull) fatalIf(err.Trace(targetAlias, targetURLFull), "Unable to initialize client instance from alias.") - content, err := clnt.Stat(false) + content, err := clnt.Stat(false, false) fatalIf(err.Trace(targetURLFull, targetAlias), "Unable to lookup file/object.") // Skip if its a directory. diff --git a/cmd/ls-main.go b/cmd/ls-main.go index f7e96857..469e5ae9 100644 --- a/cmd/ls-main.go +++ b/cmd/ls-main.go @@ -132,7 +132,7 @@ func mainList(ctx *cli.Context) error { fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") var st *clientContent - if st, err = clnt.Stat(isIncomplete); err != nil { + if st, err = clnt.Stat(isIncomplete, false); err != nil { switch err.ToGoError().(type) { case BucketNameEmpty: // For aliases like ``mc ls s3`` it's acceptable to receive BucketNameEmpty error. diff --git a/cmd/ls.go b/cmd/ls.go index 778b1534..438d1097 100644 --- a/cmd/ls.go +++ b/cmd/ls.go @@ -84,27 +84,30 @@ func parseContent(c *clientContent) contentMessage { md5sum = strings.TrimSuffix(md5sum, "\"") content.ETag = md5sum // Convert OS Type to match console file printing style. - content.Key = func() string { + content.Key = getKey(c) + return content +} + +// get content key +func getKey(c *clientContent) string { + switch { + // for windows make sure to print in 'windows' specific style. + case runtime.GOOS == "windows": + c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1) + c.URL.Path = strings.TrimSuffix(c.URL.Path, "\\") + default: + c.URL.Path = strings.TrimSuffix(c.URL.Path, "/") + } + if c.Type.IsDir() { switch { // for windows make sure to print in 'windows' specific style. case runtime.GOOS == "windows": - c.URL.Path = strings.Replace(c.URL.Path, "/", "\\", -1) - c.URL.Path = strings.TrimSuffix(c.URL.Path, "\\") + return fmt.Sprintf("%s\\", c.URL.Path) default: - c.URL.Path = strings.TrimSuffix(c.URL.Path, "/") + return fmt.Sprintf("%s/", c.URL.Path) } - if c.Type.IsDir() { - switch { - // for windows make sure to print in 'windows' specific style. - case runtime.GOOS == "windows": - return fmt.Sprintf("%s\\", c.URL.Path) - default: - return fmt.Sprintf("%s/", c.URL.Path) - } - } - return c.URL.Path - }() - return content + } + return c.URL.Path } // doList - list all entities inside a folder. diff --git a/cmd/main.go b/cmd/main.go index b0f3f994..5c5e0cb0 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -277,6 +277,7 @@ func registerApp() *cli.App { registerCmd(cpCmd) // Copy objects and files from multiple sources to single destination. registerCmd(mirrorCmd) // Mirror objects and files from single source to multiple destinations. registerCmd(findCmd) // Find specific String patterns + registerCmd(statCmd) // Stat contents of a bucket/object registerCmd(diffCmd) // Computer differences between two files or folders. registerCmd(rmCmd) // Remove a file or bucket registerCmd(eventsCmd) // Add events cmd diff --git a/cmd/mirror-main.go b/cmd/mirror-main.go index 7f5a24ad..5f0cc1cf 100644 --- a/cmd/mirror-main.go +++ b/cmd/mirror-main.go @@ -331,7 +331,7 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance mj.statusCh <- mirrorURL.WithError(err) continue } - sourceContent, err := sourceClient.Stat(false) + sourceContent, err := sourceClient.Stat(false, false) if err != nil { // source doesn't exist anymore mj.statusCh <- mirrorURL.WithError(err) @@ -345,7 +345,7 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance } shouldQueue := false if !mj.isForce { - _, err = targetClient.Stat(false) + _, err = targetClient.Stat(false, false) if err == nil { continue } // doesn't exist @@ -368,7 +368,7 @@ func (mj *mirrorJob) watchMirror(ctx context.Context, cancelMirror context.Cance mj.statusCh <- mirrorURL.WithError(err) return } - _, err = targetClient.Stat(false) + _, err = targetClient.Stat(false, false) if err == nil { continue } // doesn't exist diff --git a/cmd/rm-main.go b/cmd/rm-main.go index 7597fe05..b1b8f1a3 100644 --- a/cmd/rm-main.go +++ b/cmd/rm-main.go @@ -141,8 +141,8 @@ func removeSingle(url string, isIncomplete bool, isFake bool, older int) error { errorIf(pErr.Trace(url), "Invalid argument `"+url+"`.") return exitStatus(globalErrorExitStatus) // End of journey. } - - content, pErr := clnt.Stat(isIncomplete) + isFetchMeta := false + content, pErr := clnt.Stat(isIncomplete, isFetchMeta) if pErr != nil { errorIf(pErr.Trace(url), "Failed to remove `"+url+"`.") return exitStatus(globalErrorExitStatus) diff --git a/cmd/share-download-main.go b/cmd/share-download-main.go index 6bbca26d..31f83def 100644 --- a/cmd/share-download-main.go +++ b/cmd/share-download-main.go @@ -123,11 +123,11 @@ func doShareDownloadURL(targetURL string, isRecursive bool, expiry time.Duration // Generate share URL for each target. isIncomplete := false - + isFetchMeta := false // Channel which will receive objects whose URLs need to be shared objectsCh := make(chan *clientContent) - content, err := clnt.Stat(isIncomplete) + content, err := clnt.Stat(isIncomplete, isFetchMeta) if err != nil { return err.Trace(clnt.GetURL().String()) } diff --git a/cmd/stat-main.go b/cmd/stat-main.go new file mode 100644 index 00000000..5a5f0b4e --- /dev/null +++ b/cmd/stat-main.go @@ -0,0 +1,123 @@ +/* + * Minio Client (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "strings" + + "github.com/fatih/color" + "github.com/minio/cli" + "github.com/minio/mc/pkg/console" +) + +// stat specific flags. +var ( + statFlags = []cli.Flag{ + cli.BoolFlag{ + Name: "recursive, r", + Usage: "Stat recursively.", + }, + } +) + +// stat files and folders. +var statCmd = cli.Command{ + Name: "stat", + Usage: "Stat contents of objects.", + Action: mainStat, + Before: setGlobalsFromContext, + Flags: append(statFlags, globalFlags...), + CustomHelpTemplate: `NAME: + {{.HelpName}} - {{.Usage}} + +USAGE: + {{.HelpName}} [FLAGS] TARGET [TARGET ...] + +FLAGS: + {{range .VisibleFlags}}{{.}} + {{end}} +EXAMPLES: + 1. Stat all contents of mybucket on Amazon S3 cloud storage. + $ {{.HelpName}} s3/mybucket/ + + 2. Stat all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows. + $ {{.HelpName}} s3\mybucket\ + + 3. Stat files recursively on a local filesystem on Microsoft Windows. + $ {{.HelpName}} --recursive C:\Users\Worf\ +`, +} + +// checkStatSyntax - validate all the passed arguments +func checkStatSyntax(ctx *cli.Context) { + if !ctx.Args().Present() { + cli.ShowCommandHelpAndExit(ctx, "stat", 1) // last argument is exit code + } + + args := ctx.Args() + for _, arg := range args { + if strings.TrimSpace(arg) == "" { + fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.") + } + } + // extract URLs. + URLs := ctx.Args() + isIncomplete := false + + for _, url := range URLs { + _, _, err := url2Stat(url) + if err != nil && !isURLPrefixExists(url, isIncomplete) { + fatalIf(err.Trace(url), "Unable to stat `"+url+"`.") + } + } +} + +// mainStat - is a handler for mc stat command +func mainStat(ctx *cli.Context) error { + // Additional command specific theme customization. + console.SetColor("Name", color.New(color.Bold, color.FgCyan)) + console.SetColor("Date", color.New(color.FgWhite)) + console.SetColor("Size", color.New(color.FgWhite)) + console.SetColor("ETag", color.New(color.FgWhite)) + + console.SetColor("EncryptionHeaders", color.New(color.FgWhite)) + console.SetColor("Metadata", color.New(color.FgWhite)) + + // check 'stat' cli arguments. + checkStatSyntax(ctx) + + // Set command flags from context. + isRecursive := ctx.Bool("recursive") + + args := ctx.Args() + // mimic operating system tool behavior. + if !ctx.Args().Present() { + args = []string{"."} + } + + var cErr error + for _, targetURL := range args { + var clnt Client + clnt, err := newClient(targetURL) + fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") + + targetAlias, _, _ := mustExpandAlias(targetURL) + return doStat(clnt, isRecursive, targetAlias, targetURL) + } + return cErr + +} diff --git a/cmd/stat.go b/cmd/stat.go new file mode 100644 index 00000000..f21b69d2 --- /dev/null +++ b/cmd/stat.go @@ -0,0 +1,192 @@ +/* + * Minio Client (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "encoding/json" + "fmt" + "path/filepath" + "strings" + "time" + + humanize "github.com/dustin/go-humanize" + "github.com/minio/mc/pkg/console" + "github.com/minio/mc/pkg/probe" +) + +// contentMessage container for content message structure. +type statMessage struct { + Status string `json:"status"` + Key string `json:"name"` + Date time.Time `json:"lastModified"` + Size int64 `json:"size"` + ETag string `json:"etag"` + Type string `json:"type"` + EncryptionHeaders map[string]string `json:"encryption,omitempty"` + Metadata map[string]string `json:"metadata"` +} + +// String colorized string message. +func printStat(stat statMessage) { + // Format properly for alignment based on maxKey length + stat.Key = fmt.Sprintf("%-10s: %s", "Name", stat.Key) + console.Println(console.Colorize("Name", stat.Key)) + console.Println(fmt.Sprintf("%-10s: %s ", "Date", stat.Date.Format(printDate))) + console.Println(fmt.Sprintf("%-10s: %-6s ", "Size", humanize.IBytes(uint64(stat.Size)))) + if stat.ETag != "" { + console.Println(fmt.Sprintf("%-10s: %s ", "ETag", stat.ETag)) + } + console.Println(fmt.Sprintf("%-10s: %s ", "Type", stat.Type)) + + var maxKey = 0 + for k := range stat.Metadata { + if len(k) > maxKey { + maxKey = len(k) + } + } + if len(stat.Metadata) > 0 { + console.Println(fmt.Sprintf("%-10s:", "Metadata")) + for k, v := range stat.Metadata { + console.Println(fmt.Sprintf(" %-*.*s: %s ", maxKey, maxKey, k, v)) + } + } + maxKey = 0 + for k := range stat.EncryptionHeaders { + if len(k) > maxKey { + maxKey = len(k) + } + } + if len(stat.EncryptionHeaders) > 0 { + console.Println(fmt.Sprintf("%-10s:", "Encrypted")) + for k, v := range stat.EncryptionHeaders { + console.Println(fmt.Sprintf(" %-*.*s: %s ", maxKey, maxKey, k, v)) + } + } + console.Println() +} + +// JSON jsonified content message. +func (c statMessage) JSON() string { + c.Status = "success" + jsonMessageBytes, e := json.Marshal(c) + fatalIf(probe.NewError(e), "Unable to marshal into JSON.") + + return string(jsonMessageBytes) +} + +// parseStat parses client Content container into statMessage struct. +func parseStat(targetAlias string, c *clientContent) statMessage { + content := statMessage{} + content.Date = c.Time.Local() + // guess file type. + content.Type = func() string { + if c.Type.IsDir() { + return "folder" + } + return "file" + }() + content.Size = c.Size + content.Key = targetAlias + getKey(c) + content.Metadata = c.Metadata + content.ETag = strings.TrimPrefix(c.ETag, "\"") + content.ETag = strings.TrimSuffix(content.ETag, "\"") + + content.EncryptionHeaders = c.EncryptionHeaders + return content +} + +// doStat - list all entities inside a folder. +func doStat(clnt Client, isRecursive bool, targetAlias, targetURL string) error { + if !isRecursive || !isAliasURLDir(targetURL) { + isIncomplete := false + fetchMeta := true + if st, err := clnt.Stat(isIncomplete, fetchMeta); err != nil { + switch err.ToGoError().(type) { + default: + fatalIf(err.Trace(targetURL), "Unable to initialize `"+targetURL+"`.") + } + } else { + st := parseStat(targetAlias, st) + if !globalJSON { + printStat(st) + } else { + console.Println(st.JSON()) + } + return nil + } + } + if !strings.HasSuffix(targetURL, string(clnt.GetURL().Separator)) { + targetURL = targetURL + string(clnt.GetURL().Separator) + } + clnt, err := newClient(targetURL) + fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.") + + prefixPath := clnt.GetURL().Path + separator := string(clnt.GetURL().Separator) + if !strings.HasSuffix(prefixPath, separator) { + prefixPath = prefixPath[:strings.LastIndex(prefixPath, separator)+1] + } + var cErr error + isIncomplete := false + var prevStat *clientContent + for content := range clnt.List(isRecursive, isIncomplete, DirNone) { + if content.Err != nil { + switch content.Err.ToGoError().(type) { + // handle this specifically for filesystem related errors. + case BrokenSymlink: + errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list broken link.") + continue + case TooManyLevelsSymlink: + errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list too many levels link.") + continue + case PathNotFound: + errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + continue + case PathInsufficientPermission: + errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + continue + case ObjectOnGlacier: + errorIf(content.Err.Trace(clnt.GetURL().String()), "") + continue + } + errorIf(content.Err.Trace(clnt.GetURL().String()), "Unable to list folder.") + cErr = exitStatus(globalErrorExitStatus) // Set the exit status. + continue + } + // Convert any os specific delimiters to "/". + contentURL := filepath.ToSlash(content.URL.Path) + prefixPath = filepath.ToSlash(prefixPath) + // Trim prefix path from the content path. + contentURL = strings.TrimPrefix(contentURL, prefixPath) + content.URL.Path = contentURL + _, stat, err := url2StatWithMetadata(targetURL+getKey(content), true) + if err != nil { + continue + } + if stat != prevStat { + st := parseStat(targetAlias, stat) + if !globalJSON { + printStat(st) + } else { + console.Println(st.JSON()) + } + } else { + } + prevStat = stat + } + return cErr +} diff --git a/cmd/stat_test.go b/cmd/stat_test.go new file mode 100644 index 00000000..e9d5bd02 --- /dev/null +++ b/cmd/stat_test.go @@ -0,0 +1,57 @@ +/* + * Minio Client (C) 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package cmd + +import ( + "os" + "strings" + "time" + + . "gopkg.in/check.v1" +) + +func (s *TestSuite) TestParseStat(c *C) { + localTime := time.Unix(12001, 0).UTC() + testCases := []struct { + content clientContent + targetAlias string + }{ + {clientContent{URL: *newClientURL("https://play.minio.io:9000/abc"), Size: 0, Time: localTime, Type: os.ModeDir, ETag: "blahblah", Metadata: map[string]string{"cusom-key": "custom-value"}, EncryptionHeaders: map[string]string{}}, + "play"}, + {clientContent{URL: *newClientURL("https://play.minio.io:9000/testbucket"), Size: 500, Time: localTime, Type: os.ModeDir, ETag: "blahblah", Metadata: map[string]string{"cusom-key": "custom-value"}, EncryptionHeaders: map[string]string{}}, + "play"}, + {clientContent{URL: *newClientURL("https://s3.amazonaws.com/yrdy"), Size: 0, Time: localTime, Type: 0644, ETag: "abcdefasaas", Metadata: map[string]string{}, EncryptionHeaders: map[string]string{}}, + "s3"}, + {clientContent{URL: *newClientURL("https://play.minio.io:9000/yrdy"), Size: 10000, Time: localTime, Type: 0644, ETag: "blahblah", Metadata: map[string]string{"cusom-key": "custom-value"}, EncryptionHeaders: map[string]string{"X-Amz-Iv": "test", "X-Amz-Matdesc": "abcd"}}, + "play"}, + } + for _, testCase := range testCases { + statMsg := parseStat(testCase.targetAlias, &testCase.content) + c.Assert(testCase.content.Metadata, DeepEquals, statMsg.Metadata) + c.Assert(testCase.content.EncryptionHeaders, DeepEquals, statMsg.EncryptionHeaders) + c.Assert(testCase.content.Size, Equals, statMsg.Size) + c.Log(statMsg.Type) + if testCase.content.Type.IsRegular() { + c.Assert(statMsg.Type, Equals, "file") + } else { + c.Assert(statMsg.Type, Equals, "folder") + } + etag := strings.TrimPrefix(testCase.content.ETag, "\"") + etag = strings.TrimSuffix(etag, "\"") + c.Assert(etag, Equals, statMsg.ETag) + } +} diff --git a/vendor/github.com/pkg/xattr/LICENSE b/vendor/github.com/pkg/xattr/LICENSE new file mode 100644 index 00000000..99d2e9dc --- /dev/null +++ b/vendor/github.com/pkg/xattr/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2012 Dave Cheney. All rights reserved. +Copyright (c) 2014 Kuba Podgórski. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/xattr/README.md b/vendor/github.com/pkg/xattr/README.md new file mode 100644 index 00000000..bf370d25 --- /dev/null +++ b/vendor/github.com/pkg/xattr/README.md @@ -0,0 +1,34 @@ +[![GoDoc](https://godoc.org/github.com/pkg/xattr?status.svg)](http://godoc.org/github.com/pkg/xattr) +[![Go Report Card](https://goreportcard.com/badge/github.com/pkg/xattr)](https://goreportcard.com/report/github.com/pkg/xattr) +[![Build Status](https://travis-ci.org/pkg/xattr.svg?branch=master)](https://travis-ci.org/pkg/xattr) + +xattr +===== +Extended attribute support for Go (linux + darwin + freebsd). + +"Extended attributes are name:value pairs associated permanently with files and directories, similar to the environment strings associated with a process. An attribute may be defined or undefined. If it is defined, its value may be empty or non-empty." [See more...](https://en.wikipedia.org/wiki/Extended_file_attributes) + + +### Example +``` + const path = "/tmp/myfile" + const prefix = "user." + + if err := xattr.Set(path, prefix+"test", []byte("test-attr-value")); err != nil { + log.Fatal(err) + } + + var list []string + if list, err = xattr.List(path); err != nil { + log.Fatal(err) + } + + var data []byte + if data, err = xattr.Get(path, prefix+"test"); err != nil { + log.Fatal(err) + } + + if err = xattr.Remove(path, prefix+"test"); err != nil { + log.Fatal(err) + } +``` diff --git a/vendor/github.com/pkg/xattr/syscall_darwin.go b/vendor/github.com/pkg/xattr/syscall_darwin.go new file mode 100644 index 00000000..6fe1f6c1 --- /dev/null +++ b/vendor/github.com/pkg/xattr/syscall_darwin.go @@ -0,0 +1,39 @@ +// +build darwin + +package xattr + +import ( + "syscall" + "unsafe" +) + +func getxattr(path string, name string, value *byte, size int, pos int, options int) (int, error) { + + r0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), uintptr(unsafe.Pointer(syscall.StringBytePtr(name))), uintptr(unsafe.Pointer(value)), uintptr(size), uintptr(pos), uintptr(options)) + if e1 != syscall.Errno(0) { + return int(r0), e1 + } + return int(r0), nil +} + +func listxattr(path string, namebuf *byte, size int, options int) (int, error) { + r0, _, e1 := syscall.Syscall6(syscall.SYS_LISTXATTR, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), uintptr(unsafe.Pointer(namebuf)), uintptr(size), uintptr(options), 0, 0) + if e1 != syscall.Errno(0) { + return int(r0), e1 + } + return int(r0), nil +} + +func setxattr(path string, name string, value *byte, size int, pos int, options int) error { + if _, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), uintptr(unsafe.Pointer(syscall.StringBytePtr(name))), uintptr(unsafe.Pointer(value)), uintptr(size), uintptr(pos), uintptr(options)); e1 != syscall.Errno(0) { + return e1 + } + return nil +} + +func removexattr(path string, name string, options int) error { + if _, _, e1 := syscall.Syscall(syscall.SYS_REMOVEXATTR, uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), uintptr(unsafe.Pointer(syscall.StringBytePtr(name))), uintptr(options)); e1 != syscall.Errno(0) { + return e1 + } + return nil +} diff --git a/vendor/github.com/pkg/xattr/syscall_freebsd.go b/vendor/github.com/pkg/xattr/syscall_freebsd.go new file mode 100644 index 00000000..fda12c2b --- /dev/null +++ b/vendor/github.com/pkg/xattr/syscall_freebsd.go @@ -0,0 +1,91 @@ +// +build freebsd + +package xattr + +import ( + "syscall" + "unsafe" +) + +/* + ssize_t + extattr_get_file(const char *path, int attrnamespace, + const char *attrname, void *data, size_t nbytes); + + ssize_t + extattr_set_file(const char *path, int attrnamespace, + const char *attrname, const void *data, size_t nbytes); + + int + extattr_delete_file(const char *path, int attrnamespace, + const char *attrname); + + ssize_t + extattr_list_file(const char *path, int attrnamespace, void *data, + size_t nbytes); +*/ + +func extattr_get_file(path string, attrnamespace int, attrname string, data *byte, nbytes int) (int, error) { + r, _, e := syscall.Syscall6( + syscall.SYS_EXTATTR_GET_FILE, + uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), + uintptr(attrnamespace), + uintptr(unsafe.Pointer(syscall.StringBytePtr(attrname))), + uintptr(unsafe.Pointer(data)), + uintptr(nbytes), + 0, + ) + var err error + if e != 0 { + err = e + } + return int(r), err +} + +func extattr_set_file(path string, attrnamespace int, attrname string, data *byte, nbytes int) (int, error) { + r, _, e := syscall.Syscall6( + syscall.SYS_EXTATTR_SET_FILE, + uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), + uintptr(attrnamespace), + uintptr(unsafe.Pointer(syscall.StringBytePtr(attrname))), + uintptr(unsafe.Pointer(data)), + uintptr(nbytes), + 0, + ) + var err error + if e != 0 { + err = e + } + return int(r), err +} + +func extattr_delete_file(path string, attrnamespace int, attrname string) error { + _, _, e := syscall.Syscall( + syscall.SYS_EXTATTR_DELETE_FILE, + uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), + uintptr(attrnamespace), + uintptr(unsafe.Pointer(syscall.StringBytePtr(attrname))), + ) + var err error + if e != 0 { + err = e + } + return err +} + +func extattr_list_file(path string, attrnamespace int, data *byte, nbytes int) (int, error) { + r, _, e := syscall.Syscall6( + syscall.SYS_EXTATTR_LIST_FILE, + uintptr(unsafe.Pointer(syscall.StringBytePtr(path))), + uintptr(attrnamespace), + uintptr(unsafe.Pointer(data)), + uintptr(nbytes), + 0, + 0, + ) + var err error + if e != 0 { + err = e + } + return int(r), err +} diff --git a/vendor/github.com/pkg/xattr/xattr.go b/vendor/github.com/pkg/xattr/xattr.go new file mode 100644 index 00000000..ef1a0a3b --- /dev/null +++ b/vendor/github.com/pkg/xattr/xattr.go @@ -0,0 +1,32 @@ +/* +Package xattr provides support for extended attributes on linux, darwin and freebsd. +Extended attributes are name:value pairs associated permanently with files and directories, +similar to the environment strings associated with a process. +An attribute may be defined or undefined. If it is defined, its value may be empty or non-empty. +More details you can find here: https://en.wikipedia.org/wiki/Extended_file_attributes +*/ +package xattr + +// Error records an error and the operation, file path and attribute that caused it. +type Error struct { + Op string + Path string + Name string + Err error +} + +func (e *Error) Error() string { + return e.Op + " " + e.Path + " " + e.Name + ": " + e.Err.Error() +} + +// nullTermToStrings converts an array of NULL terminated UTF-8 strings to a []string. +func nullTermToStrings(buf []byte) (result []string) { + offset := 0 + for index, b := range buf { + if b == 0 { + result = append(result, string(buf[offset:index])) + offset = index + 1 + } + } + return +} diff --git a/vendor/github.com/pkg/xattr/xattr_darwin.go b/vendor/github.com/pkg/xattr/xattr_darwin.go new file mode 100644 index 00000000..e859ac9f --- /dev/null +++ b/vendor/github.com/pkg/xattr/xattr_darwin.go @@ -0,0 +1,74 @@ +// +build darwin + +package xattr + +import "syscall" + +// Get retrieves extended attribute data associated with path. +func Get(path, name string) ([]byte, error) { + // find size. + size, err := getxattr(path, name, nil, 0, 0, 0) + if err != nil { + return nil, &Error{"xattr.Get", path, name, err} + } + if size > 0 { + buf := make([]byte, size) + // Read into buffer of that size. + read, err := getxattr(path, name, &buf[0], size, 0, 0) + if err != nil { + return nil, &Error{"xattr.Get", path, name, err} + } + return buf[:read], nil + } + return []byte{}, nil +} + +// List retrieves a list of names of extended attributes associated +// with the given path in the file system. +func List(path string) ([]string, error) { + // find size. + size, err := listxattr(path, nil, 0, 0) + if err != nil { + return nil, &Error{"xattr.List", path, "", err} + } + if size > 0 { + + buf := make([]byte, size) + // Read into buffer of that size. + read, err := listxattr(path, &buf[0], size, 0) + if err != nil { + return nil, &Error{"xattr.List", path, "", err} + } + return nullTermToStrings(buf[:read]), nil + } + return []string{}, nil +} + +// Set associates name and data together as an attribute of path. +func Set(path, name string, data []byte) error { + var dataval *byte = nil + datalen := len(data) + if datalen > 0 { + dataval = &data[0] + } + if err := setxattr(path, name, dataval, datalen, 0, 0); err != nil { + return &Error{"xattr.Set", path, name, err} + } + return nil +} + +// Remove removes the attribute associated with the given path. +func Remove(path, name string) error { + if err := removexattr(path, name, 0); err != nil { + return &Error{"xattr.Remove", path, name, err} + } + return nil +} + +// Supported checks if filesystem supports extended attributes +func Supported(path string) bool { + if _, err := listxattr(path, nil, 0, 0); err != nil { + return err != syscall.ENOTSUP + } + return true +} diff --git a/vendor/github.com/pkg/xattr/xattr_freebsd.go b/vendor/github.com/pkg/xattr/xattr_freebsd.go new file mode 100644 index 00000000..79b3ba09 --- /dev/null +++ b/vendor/github.com/pkg/xattr/xattr_freebsd.go @@ -0,0 +1,98 @@ +// +build freebsd + +package xattr + +import ( + "syscall" +) + +const ( + EXTATTR_NAMESPACE_USER = 1 +) + +// Get retrieves extended attribute data associated with path. +func Get(path, name string) ([]byte, error) { + // find size. + size, err := extattr_get_file(path, EXTATTR_NAMESPACE_USER, name, nil, 0) + if err != nil { + return nil, &Error{"xattr.Get", path, name, err} + } + if size > 0 { + buf := make([]byte, size) + // Read into buffer of that size. + read, err := extattr_get_file(path, EXTATTR_NAMESPACE_USER, name, &buf[0], size) + if err != nil { + return nil, &Error{"xattr.Get", path, name, err} + } + return buf[:read], nil + } + return []byte{}, nil +} + +// List retrieves a list of names of extended attributes associated +// with the given path in the file system. +func List(path string) ([]string, error) { + // find size. + size, err := extattr_list_file(path, EXTATTR_NAMESPACE_USER, nil, 0) + if err != nil { + return nil, &Error{"xattr.List", path, "", err} + } + if size > 0 { + buf := make([]byte, size) + // Read into buffer of that size. + read, err := extattr_list_file(path, EXTATTR_NAMESPACE_USER, &buf[0], size) + if err != nil { + return nil, &Error{"xattr.List", path, "", err} + } + return attrListToStrings(buf[:read]), nil + } + return []string{}, nil +} + +// Set associates name and data together as an attribute of path. +func Set(path, name string, data []byte) error { + var dataval *byte = nil + datalen := len(data) + if datalen > 0 { + dataval = &data[0] + } + written, err := extattr_set_file(path, EXTATTR_NAMESPACE_USER, name, dataval, datalen) + if err != nil { + return &Error{"xattr.Set", path, name, err} + } + if written != datalen { + return &Error{"xattr.Set", path, name, syscall.E2BIG} + } + return nil +} + +// Remove removes the attribute associated with the given path. +func Remove(path, name string) error { + if err := extattr_delete_file(path, EXTATTR_NAMESPACE_USER, name); err != nil { + return &Error{"xattr.Remove", path, name, err} + } + return nil +} + +// Supported checks if filesystem supports extended attributes +func Supported(path string) bool { + if _, err := extattr_list_file(path, EXTATTR_NAMESPACE_USER, nil, 0); err != nil { + return err != syscall.ENOTSUP + } + return true +} + +// attrListToStrings converts a sequnce of attribute name entries to a []string. +// Each entry consists of a single byte containing the length +// of the attribute name, followed by the attribute name. +// The name is _not_ terminated by NUL. +func attrListToStrings(buf []byte) []string { + var result []string + index := 0 + for index < len(buf) { + next := index + 1 + int(buf[index]) + result = append(result, string(buf[index+1:next])) + index = next + } + return result +} diff --git a/vendor/github.com/pkg/xattr/xattr_linux.go b/vendor/github.com/pkg/xattr/xattr_linux.go new file mode 100644 index 00000000..5abdd327 --- /dev/null +++ b/vendor/github.com/pkg/xattr/xattr_linux.go @@ -0,0 +1,69 @@ +// +build linux + +package xattr + +import "syscall" + +// Get retrieves extended attribute data associated with path. +func Get(path, name string) ([]byte, error) { + // find size. + size, err := syscall.Getxattr(path, name, nil) + if err != nil { + return nil, &Error{"xattr.Get", path, name, err} + } + if size > 0 { + data := make([]byte, size) + // Read into buffer of that size. + read, err := syscall.Getxattr(path, name, data) + if err != nil { + return nil, &Error{"xattr.Get", path, name, err} + } + return data[:read], nil + } + return []byte{}, nil +} + +// List retrieves a list of names of extended attributes associated +// with the given path in the file system. +func List(path string) ([]string, error) { + // find size. + size, err := syscall.Listxattr(path, nil) + if err != nil { + return nil, &Error{"xattr.List", path, "", err} + } + if size > 0 { + buf := make([]byte, size) + // Read into buffer of that size. + read, err := syscall.Listxattr(path, buf) + if err != nil { + return nil, &Error{"xattr.List", path, "", err} + } + return nullTermToStrings(buf[:read]), nil + } + return []string{}, nil +} + +// Set associates name and data together as an attribute of path. +func Set(path, name string, data []byte) error { + if err := syscall.Setxattr(path, name, data, 0); err != nil { + return &Error{"xattr.Set", path, name, err} + } + return nil +} + +// Remove removes the attribute associated +// with the given path. +func Remove(path, name string) error { + if err := syscall.Removexattr(path, name); err != nil { + return &Error{"xattr.Remove", path, name, err} + } + return nil +} + +// Supported checks if filesystem supports extended attributes +func Supported(path string) bool { + if _, err := syscall.Listxattr(path, nil); err != nil { + return err != syscall.ENOTSUP + } + return true +} diff --git a/vendor/vendor.json b/vendor/vendor.json index cf9cd5f8..c05b2aac 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -138,6 +138,12 @@ "revision": "19396ecfda37c1c9ddaa52019adca59d582e4832", "revisionTime": "2016-03-15T12:21:13+11:00" }, + { + "checksumSHA1": "Z/05vaKyPtED9YR98YqJZAZgWTQ=", + "path": "github.com/pkg/xattr", + "revision": "56ed87199ebaabcb1b3bfae3c1fb0affaabc3287", + "revisionTime": "2017-08-08T19:02:11Z" + }, { "checksumSHA1": "ZYLNe3yInOcxTtzu7ERLL2hoQxE=", "path": "github.com/rjeczalik/notify",