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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
|
/*
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 (
"errors"
"flag"
"fmt"
"io"
"log"
"math/rand"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
)
// See: https://github.com/vmware/open-vm-tools/blob/master/open-vm-tools/lib/hgfsServer/hgfsServer.c
var (
// Trace enables hgfs packet tracing
Trace = false
)
// Server provides an HGFS protocol implementation to support guest tools VmxiHgfsSendPacketCommand
type Server struct {
Capabilities []Capability
handlers map[int32]func(*Packet) (interface{}, error)
schemes map[string]FileHandler
sessions map[uint64]*session
mu sync.Mutex
handle uint32
chmod func(string, os.FileMode) error
chown func(string, int, int) error
}
// NewServer creates a new Server instance with the default handlers
func NewServer() *Server {
if f := flag.Lookup("toolbox.trace"); f != nil {
Trace, _ = strconv.ParseBool(f.Value.String())
}
s := &Server{
sessions: make(map[uint64]*session),
schemes: make(map[string]FileHandler),
chmod: os.Chmod,
chown: os.Chown,
}
s.handlers = map[int32]func(*Packet) (interface{}, error){
OpCreateSessionV4: s.CreateSessionV4,
OpDestroySessionV4: s.DestroySessionV4,
OpGetattrV2: s.GetattrV2,
OpSetattrV2: s.SetattrV2,
OpOpen: s.Open,
OpClose: s.Close,
OpOpenV3: s.OpenV3,
OpReadV3: s.ReadV3,
OpWriteV3: s.WriteV3,
}
for op := range s.handlers {
s.Capabilities = append(s.Capabilities, Capability{Op: op, Flags: 0x1})
}
return s
}
// RegisterFileHandler enables dispatch to handler for the given scheme.
func (s *Server) RegisterFileHandler(scheme string, handler FileHandler) {
if handler == nil {
delete(s.schemes, scheme)
return
}
s.schemes[scheme] = handler
}
// Dispatch unpacks the given request packet and dispatches to the appropriate handler
func (s *Server) Dispatch(packet []byte) ([]byte, error) {
req := &Packet{}
err := req.UnmarshalBinary(packet)
if err != nil {
return nil, err
}
if Trace {
fmt.Fprintf(os.Stderr, "[hgfs] request %#v\n", req.Header)
}
var res interface{}
handler, ok := s.handlers[req.Op]
if ok {
res, err = handler(req)
} else {
err = &Status{
Code: StatusOperationNotSupported,
Err: fmt.Errorf("unsupported Op(%d)", req.Op),
}
}
return req.Reply(res, err)
}
// File interface abstracts standard i/o methods to support transfer
// of regular files and archives of directories.
type File interface {
io.Reader
io.Writer
io.Closer
Name() string
}
// FileHandler is the plugin interface for hgfs file transport.
type FileHandler interface {
Stat(*url.URL) (os.FileInfo, error)
Open(*url.URL, int32) (File, error)
}
// urlParse attempts to convert the given name to a URL with scheme for use as FileHandler dispatch.
func urlParse(name string) *url.URL {
var info os.FileInfo
u, err := url.Parse(name)
if err == nil && u.Scheme == "" {
info, err = os.Stat(u.Path)
if err == nil && info.IsDir() {
u.Scheme = ArchiveScheme // special case for IsDir()
return u
}
}
u, err = url.Parse(strings.TrimPrefix(name, "/")) // must appear to be an absolute path or hgfs errors
if err != nil {
u = &url.URL{Path: name}
}
if u.Scheme == "" {
ix := strings.Index(u.Path, "/")
if ix > 0 {
u.Scheme = u.Path[:ix]
u.Path = u.Path[ix:]
}
}
return u
}
// OpenFile selects the File implementation based on file type and mode.
func (s *Server) OpenFile(name string, mode int32) (File, error) {
u := urlParse(name)
if h, ok := s.schemes[u.Scheme]; ok {
f, serr := h.Open(u, mode)
if serr != os.ErrNotExist {
return f, serr
}
}
switch mode {
case OpenModeReadOnly:
return os.Open(filepath.Clean(name))
case OpenModeWriteOnly:
flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
return os.OpenFile(name, flag, 0600)
default:
return nil, &Status{
Err: fmt.Errorf("open mode(%d) not supported for file %q", mode, name),
Code: StatusAccessDenied,
}
}
}
// Stat wraps os.Stat such that we can report directory types as regular files to support archive streaming.
// In the case of standard vmware-tools, attempts to transfer directories result
// with a VIX_E_NOT_A_FILE (see InitiateFileTransfer{To,From}Guest).
// Note that callers on the VMX side that reach this path are only concerned with:
// - does the file exist?
// - size:
// + used for UI progress with desktop Drag-N-Drop operations, which toolbox does not support.
// + sent to as Content-Length header in response to GET of FileTransferInformation.Url,
// if the first ReadV3 size is > HGFS_LARGE_PACKET_MAX
func (s *Server) Stat(name string) (os.FileInfo, error) {
u := urlParse(name)
if h, ok := s.schemes[u.Scheme]; ok {
sinfo, serr := h.Stat(u)
if serr != os.ErrNotExist {
return sinfo, serr
}
}
return os.Stat(name)
}
type session struct {
files map[uint32]File
mu sync.Mutex
}
// TODO: we currently depend on the VMX to close files and remove sessions,
// which it does provided it can communicate with the toolbox. Let's look at
// adding session expiration when implementing OpenModeWriteOnly support.
func newSession() *session {
return &session{
files: make(map[uint32]File),
}
}
func (s *Server) getSession(p *Packet) (*session, error) {
s.mu.Lock()
session, ok := s.sessions[p.SessionID]
s.mu.Unlock()
if !ok {
return nil, &Status{
Code: StatusStaleSession,
Err: errors.New("session not found"),
}
}
return session, nil
}
func (s *Server) removeSession(id uint64) bool {
s.mu.Lock()
session, ok := s.sessions[id]
delete(s.sessions, id)
s.mu.Unlock()
if !ok {
return false
}
session.mu.Lock()
defer session.mu.Unlock()
for _, f := range session.files {
log.Printf("[hgfs] session %X removed with open file: %s", id, f.Name())
_ = f.Close()
}
return true
}
// open-vm-tools' session max is 1024, there shouldn't be more than a handful at a given time in our use cases
const maxSessions = 24
// CreateSessionV4 handls OpCreateSessionV4 requests
func (s *Server) CreateSessionV4(p *Packet) (interface{}, error) {
const SessionMaxPacketSizeValid = 0x1
req := new(RequestCreateSessionV4)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
res := &ReplyCreateSessionV4{
SessionID: uint64(rand.Int63()),
NumCapabilities: uint32(len(s.Capabilities)),
MaxPacketSize: LargePacketMax,
Flags: SessionMaxPacketSizeValid,
Capabilities: s.Capabilities,
}
s.mu.Lock()
defer s.mu.Unlock()
if len(s.sessions) > maxSessions {
return nil, &Status{Code: StatusTooManySessions}
}
s.sessions[res.SessionID] = newSession()
return res, nil
}
// DestroySessionV4 handls OpDestroySessionV4 requests
func (s *Server) DestroySessionV4(p *Packet) (interface{}, error) {
if s.removeSession(p.SessionID) {
return &ReplyDestroySessionV4{}, nil
}
return nil, &Status{Code: StatusStaleSession}
}
// Stat maps os.FileInfo to AttrV2
func (a *AttrV2) Stat(info os.FileInfo) {
switch {
case info.IsDir():
a.Type = FileTypeDirectory
case info.Mode()&os.ModeSymlink == os.ModeSymlink:
a.Type = FileTypeSymlink
default:
a.Type = FileTypeRegular
}
a.Size = uint64(info.Size())
a.Mask = AttrValidType | AttrValidSize
a.sysStat(info)
}
// GetattrV2 handles OpGetattrV2 requests
func (s *Server) GetattrV2(p *Packet) (interface{}, error) {
res := &ReplyGetattrV2{}
req := new(RequestGetattrV2)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
name := req.FileName.Path()
info, err := s.Stat(name)
if err != nil {
return nil, err
}
res.Attr.Stat(info)
return res, nil
}
// SetattrV2 handles OpSetattrV2 requests
func (s *Server) SetattrV2(p *Packet) (interface{}, error) {
res := &ReplySetattrV2{}
req := new(RequestSetattrV2)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
name := req.FileName.Path()
_, err = os.Stat(name)
if err != nil && os.IsNotExist(err) {
// assuming this is a virtual file
return res, nil
}
uid := -1
if req.Attr.Mask&AttrValidUserID == AttrValidUserID {
uid = int(req.Attr.UserID)
}
gid := -1
if req.Attr.Mask&AttrValidGroupID == AttrValidGroupID {
gid = int(req.Attr.GroupID)
}
err = s.chown(name, uid, gid)
if err != nil {
return nil, err
}
var perm os.FileMode
if req.Attr.Mask&AttrValidOwnerPerms == AttrValidOwnerPerms {
perm |= os.FileMode(req.Attr.OwnerPerms) << 6
}
if req.Attr.Mask&AttrValidGroupPerms == AttrValidGroupPerms {
perm |= os.FileMode(req.Attr.GroupPerms) << 3
}
if req.Attr.Mask&AttrValidOtherPerms == AttrValidOtherPerms {
perm |= os.FileMode(req.Attr.OtherPerms)
}
if perm != 0 {
err = s.chmod(name, perm)
if err != nil {
return nil, err
}
}
return res, nil
}
func (s *Server) newHandle() uint32 {
return atomic.AddUint32(&s.handle, 1)
}
// Open handles OpOpen requests
func (s *Server) Open(p *Packet) (interface{}, error) {
req := new(RequestOpen)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
session, err := s.getSession(p)
if err != nil {
return nil, err
}
name := req.FileName.Path()
mode := req.OpenMode
if mode != OpenModeReadOnly {
return nil, &Status{
Err: fmt.Errorf("open mode(%d) not supported for file %q", mode, name),
Code: StatusAccessDenied,
}
}
file, err := s.OpenFile(name, mode)
if err != nil {
return nil, err
}
res := &ReplyOpen{
Handle: s.newHandle(),
}
session.mu.Lock()
session.files[res.Handle] = file
session.mu.Unlock()
return res, nil
}
// Close handles OpClose requests
func (s *Server) Close(p *Packet) (interface{}, error) {
req := new(RequestClose)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
session, err := s.getSession(p)
if err != nil {
return nil, err
}
session.mu.Lock()
file, ok := session.files[req.Handle]
if ok {
delete(session.files, req.Handle)
}
session.mu.Unlock()
if ok {
err = file.Close()
} else {
return nil, &Status{Code: StatusInvalidHandle}
}
return &ReplyClose{}, err
}
// OpenV3 handles OpOpenV3 requests
func (s *Server) OpenV3(p *Packet) (interface{}, error) {
req := new(RequestOpenV3)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
session, err := s.getSession(p)
if err != nil {
return nil, err
}
name := req.FileName.Path()
if req.DesiredLock != LockNone {
return nil, &Status{
Err: fmt.Errorf("open lock type=%d not supported for file %q", req.DesiredLock, name),
Code: StatusOperationNotSupported,
}
}
file, err := s.OpenFile(name, req.OpenMode)
if err != nil {
return nil, err
}
res := &ReplyOpenV3{
Handle: s.newHandle(),
}
session.mu.Lock()
session.files[res.Handle] = file
session.mu.Unlock()
return res, nil
}
// ReadV3 handles OpReadV3 requests
func (s *Server) ReadV3(p *Packet) (interface{}, error) {
req := new(RequestReadV3)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
session, err := s.getSession(p)
if err != nil {
return nil, err
}
session.mu.Lock()
file, ok := session.files[req.Handle]
session.mu.Unlock()
if !ok {
return nil, &Status{Code: StatusInvalidHandle}
}
buf := make([]byte, req.RequiredSize)
// Use ReadFull as Read() of an archive io.Pipe may return much smaller chunks,
// such as when we've read a tar header.
n, err := io.ReadFull(file, buf)
if err != nil && n == 0 {
if err != io.EOF {
return nil, err
}
}
res := &ReplyReadV3{
ActualSize: uint32(n),
Payload: buf[:n],
}
return res, nil
}
// WriteV3 handles OpWriteV3 requests
func (s *Server) WriteV3(p *Packet) (interface{}, error) {
req := new(RequestWriteV3)
err := UnmarshalBinary(p.Payload, req)
if err != nil {
return nil, err
}
session, err := s.getSession(p)
if err != nil {
return nil, err
}
session.mu.Lock()
file, ok := session.files[req.Handle]
session.mu.Unlock()
if !ok {
return nil, &Status{Code: StatusInvalidHandle}
}
n, err := file.Write(req.Payload)
if err != nil {
return nil, err
}
res := &ReplyWriteV3{
ActualSize: uint32(n),
}
return res, nil
}
|