1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
|
/*
Copyright (c) 2017 VMware, Inc. All Rights Reserved.
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 hgfs
import (
"archive/tar"
"bufio"
"bytes"
"compress/gzip"
"io"
"io/ioutil"
"log"
"math"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/vmware/govmomi/toolbox/vix"
)
// ArchiveScheme is the default scheme used to register the archive FileHandler
var ArchiveScheme = "archive"
// ArchiveHandler implements a FileHandler for transferring directories.
type ArchiveHandler struct {
Read func(*url.URL, *tar.Reader) error
Write func(*url.URL, *tar.Writer) error
}
// NewArchiveHandler returns a FileHandler implementation for transferring directories using gzip'd tar files.
func NewArchiveHandler() FileHandler {
return &ArchiveHandler{
Read: archiveRead,
Write: archiveWrite,
}
}
// Stat implements FileHandler.Stat
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error) {
switch u.Query().Get("format") {
case "", "tar", "tgz":
// ok
default:
log.Printf("unknown archive format: %q", u)
return nil, vix.Error(vix.InvalidArg)
}
return &archive{
name: u.Path,
size: math.MaxInt64,
}, nil
}
// Open implements FileHandler.Open
func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error) {
switch mode {
case OpenModeReadOnly:
return h.newArchiveFromGuest(u)
case OpenModeWriteOnly:
return h.newArchiveToGuest(u)
default:
return nil, os.ErrNotExist
}
}
// archive implements the hgfs.File and os.FileInfo interfaces.
type archive struct {
name string
size int64
done func() error
io.Reader
io.Writer
}
// Name implementation of the os.FileInfo interface method.
func (a *archive) Name() string {
return a.name
}
// Size implementation of the os.FileInfo interface method.
func (a *archive) Size() int64 {
return a.size
}
// Mode implementation of the os.FileInfo interface method.
func (a *archive) Mode() os.FileMode {
return 0600
}
// ModTime implementation of the os.FileInfo interface method.
func (a *archive) ModTime() time.Time {
return time.Now()
}
// IsDir implementation of the os.FileInfo interface method.
func (a *archive) IsDir() bool {
return false
}
// Sys implementation of the os.FileInfo interface method.
func (a *archive) Sys() interface{} {
return nil
}
// The trailer is required since TransferFromGuest requires a Content-Length,
// which toolbox doesn't know ahead of time as the gzip'd tarball never touches the disk.
// HTTP clients need to be aware of this and stop reading when they see the 2nd gzip header.
var gzipHeader = []byte{0x1f, 0x8b, 0x08} // rfc1952 {ID1, ID2, CM}
var gzipTrailer = true
// newArchiveFromGuest returns an hgfs.File implementation to read a directory as a gzip'd tar.
func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error) {
r, w := io.Pipe()
a := &archive{
name: u.Path,
done: r.Close,
Reader: r,
Writer: w,
}
var z io.Writer = w
var c io.Closer = ioutil.NopCloser(nil)
switch u.Query().Get("format") {
case "tgz":
gz := gzip.NewWriter(w)
z = gz
c = gz
}
tw := tar.NewWriter(z)
go func() {
err := h.Write(u, tw)
_ = tw.Close()
_ = c.Close()
if gzipTrailer {
_, _ = w.Write(gzipHeader)
}
_ = w.CloseWithError(err)
}()
return a, nil
}
// newArchiveToGuest returns an hgfs.File implementation to expand a gzip'd tar into a directory.
func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error) {
r, w := io.Pipe()
buf := bufio.NewReader(r)
a := &archive{
name: u.Path,
Reader: buf,
Writer: w,
}
var cerr error
var wg sync.WaitGroup
a.done = func() error {
_ = w.Close()
// We need to wait for unpack to finish to complete its work
// and to propagate the error if any to Close.
wg.Wait()
return cerr
}
wg.Add(1)
go func() {
defer wg.Done()
c := func() error {
// Drain the pipe of tar trailer data (two null blocks)
if cerr == nil {
_, _ = io.Copy(ioutil.Discard, a.Reader)
}
return nil
}
header, _ := buf.Peek(len(gzipHeader))
if bytes.Equal(header, gzipHeader) {
gz, err := gzip.NewReader(a.Reader)
if err != nil {
_ = r.CloseWithError(err)
cerr = err
return
}
c = gz.Close
a.Reader = gz
}
tr := tar.NewReader(a.Reader)
cerr = h.Read(u, tr)
_ = c()
_ = r.CloseWithError(cerr)
}()
return a, nil
}
func (a *archive) Close() error {
return a.done()
}
// archiveRead writes the contents of the given tar.Reader to the given directory.
func archiveRead(u *url.URL, tr *tar.Reader) error {
for {
header, err := tr.Next()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
name := filepath.Join(u.Path, header.Name)
mode := os.FileMode(header.Mode)
switch header.Typeflag {
case tar.TypeDir:
err = os.MkdirAll(name, mode)
case tar.TypeReg:
_ = os.MkdirAll(filepath.Dir(name), 0750)
var f *os.File
f, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode)
if err == nil {
_, cerr := io.Copy(f, tr)
err = f.Close()
if cerr != nil {
err = cerr
}
}
case tar.TypeSymlink:
err = os.Symlink(header.Linkname, name)
}
// TODO: Uid/Gid may not be meaningful here without some mapping.
// The other option to consider would be making use of the guest auth user ID.
// os.Lchown(name, header.Uid, header.Gid)
if err != nil {
return err
}
}
}
// archiveWrite writes the contents of the given source directory to the given tar.Writer.
func archiveWrite(u *url.URL, tw *tar.Writer) error {
info, err := os.Stat(u.Path)
if err != nil {
return err
}
// Note that the VMX will trim any trailing slash. For example:
// "/foo/bar/?prefix=bar/" will end up here as "/foo/bar/?prefix=bar"
// Escape to avoid this: "/for/bar/?prefix=bar%2F"
prefix := u.Query().Get("prefix")
dir := u.Path
f := func(file string, fi os.FileInfo, err error) error {
if err != nil {
return filepath.SkipDir
}
name := strings.TrimPrefix(file, dir)
name = strings.TrimPrefix(name, "/")
if name == "" {
return nil // this is u.Path itself (which may or may not have a trailing "/")
}
if prefix != "" {
name = prefix + name
}
header, _ := tar.FileInfoHeader(fi, name)
header.Name = name
if header.Typeflag == tar.TypeDir {
header.Name += "/"
}
var f *os.File
if header.Typeflag == tar.TypeReg && fi.Size() != 0 {
f, err = os.Open(filepath.Clean(file))
if err != nil {
if os.IsPermission(err) {
return nil
}
return err
}
}
_ = tw.WriteHeader(header)
if f != nil {
_, err = io.Copy(tw, f)
_ = f.Close()
}
return err
}
if info.IsDir() {
return filepath.Walk(u.Path, f)
}
dir = filepath.Dir(dir)
return f(u.Path, info, nil)
}
|