File: protocol.go

package info (click to toggle)
golang-github-vmware-govmomi 0.24.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,848 kB
  • sloc: sh: 2,285; lisp: 1,560; ruby: 948; xml: 139; makefile: 54
file content (847 lines) | stat: -rw-r--r-- 18,675 bytes parent folder | download | duplicates (3)
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
/*
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 vix

import (
	"bytes"
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"os"
	"os/exec"
	"syscall"
)

const (
	CommandMagicWord = 0xd00d0001

	CommandGetToolsState = 62

	CommandStartProgram     = 185
	CommandListProcessesEx  = 186
	CommandReadEnvVariables = 187
	CommandTerminateProcess = 193

	CommandCreateDirectoryEx        = 178
	CommandMoveGuestFileEx          = 179
	CommandMoveGuestDirectory       = 180
	CommandCreateTemporaryFileEx    = 181
	CommandCreateTemporaryDirectory = 182
	CommandSetGuestFileAttributes   = 183
	CommandDeleteGuestFileEx        = 194
	CommandDeleteGuestDirectoryEx   = 195

	CommandListFiles                     = 177
	HgfsSendPacketCommand                = 84
	CommandInitiateFileTransferFromGuest = 188
	CommandInitiateFileTransferToGuest   = 189

	// VIX_USER_CREDENTIAL_NAME_PASSWORD
	UserCredentialTypeNamePassword = 1

	// VIX_E_* constants from vix.h
	OK                 = 0
	Fail               = 1
	InvalidArg         = 3
	FileNotFound       = 4
	FileAlreadyExists  = 12
	FileAccessError    = 13
	AuthenticationFail = 35

	UnrecognizedCommandInGuest = 3025
	InvalidMessageHeader       = 10000
	InvalidMessageBody         = 10001
	NotAFile                   = 20001
	NotADirectory              = 20002
	NoSuchProcess              = 20003
	DirectoryNotEmpty          = 20006

	// VIX_COMMAND_* constants from Commands.h
	CommandGuestReturnsBinary = 0x80

	// VIX_FILE_ATTRIBUTES_ constants from vix.h
	FileAttributesDirectory = 0x0001
	FileAttributesSymlink   = 0x0002
)

// SetGuestFileAttributes flags as defined in vixOpenSource.h
const (
	FileAttributeSetAccessDate      = 0x0001
	FileAttributeSetModifyDate      = 0x0002
	FileAttributeSetReadonly        = 0x0004
	FileAttributeSetHidden          = 0x0008
	FileAttributeSetUnixOwnerid     = 0x0010
	FileAttributeSetUnixGroupid     = 0x0020
	FileAttributeSetUnixPermissions = 0x0040
)

type Error int

func (err Error) Error() string {
	return fmt.Sprintf("vix error=%d", err)
}

// ErrorCode does its best to map the given error to a VIX error code.
// See also: Vix_TranslateErrno
func ErrorCode(err error) int {
	switch t := err.(type) {
	case Error:
		return int(t)
	case *os.PathError:
		if errno, ok := t.Err.(syscall.Errno); ok {
			switch errno {
			case syscall.ENOTEMPTY:
				return DirectoryNotEmpty
			}
		}
	case *exec.Error:
		if t.Err == exec.ErrNotFound {
			return FileNotFound
		}
	}

	switch {
	case os.IsNotExist(err):
		return FileNotFound
	case os.IsExist(err):
		return FileAlreadyExists
	case os.IsPermission(err):
		return FileAccessError
	default:
		return Fail
	}
}

type Header struct {
	Magic          uint32
	MessageVersion uint16

	TotalMessageLength uint32
	HeaderLength       uint32
	BodyLength         uint32
	CredentialLength   uint32

	CommonFlags uint8
}

type CommandRequestHeader struct {
	Header

	OpCode       uint32
	RequestFlags uint32

	TimeOut uint32

	Cookie         uint64
	ClientHandleID uint32

	UserCredentialType uint32
}

type StartProgramRequest struct {
	CommandRequestHeader

	Body struct {
		StartMinimized    uint8
		ProgramPathLength uint32
		ArgumentsLength   uint32
		WorkingDirLength  uint32
		NumEnvVars        uint32
		EnvVarLength      uint32
	}

	ProgramPath string
	Arguments   string
	WorkingDir  string
	EnvVars     []string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *StartProgramRequest) MarshalBinary() ([]byte, error) {
	var env bytes.Buffer

	if n := len(r.EnvVars); n != 0 {
		for _, e := range r.EnvVars {
			_, _ = env.Write([]byte(e))
			_ = env.WriteByte(0)
		}
		r.Body.NumEnvVars = uint32(n)
		r.Body.EnvVarLength = uint32(env.Len())
	}

	var fields []string

	add := func(s string, l *uint32) {
		if n := len(s); n != 0 {
			*l = uint32(n) + 1
			fields = append(fields, s)
		}
	}

	add(r.ProgramPath, &r.Body.ProgramPathLength)
	add(r.Arguments, &r.Body.ArgumentsLength)
	add(r.WorkingDir, &r.Body.WorkingDirLength)

	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	for _, val := range fields {
		_, _ = buf.Write([]byte(val))
		_ = buf.WriteByte(0)
	}

	if r.Body.EnvVarLength != 0 {
		_, _ = buf.Write(env.Bytes())
	}

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *StartProgramRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	fields := []struct {
		len uint32
		val *string
	}{
		{r.Body.ProgramPathLength, &r.ProgramPath},
		{r.Body.ArgumentsLength, &r.Arguments},
		{r.Body.WorkingDirLength, &r.WorkingDir},
	}

	for _, field := range fields {
		if field.len == 0 {
			continue
		}

		x := buf.Next(int(field.len))
		*field.val = string(bytes.TrimRight(x, "\x00"))
	}

	for i := 0; i < int(r.Body.NumEnvVars); i++ {
		env, rerr := buf.ReadString(0)
		if rerr != nil {
			return rerr
		}

		env = env[:len(env)-1] // discard NULL terminator
		r.EnvVars = append(r.EnvVars, env)
	}

	return nil
}

type KillProcessRequest struct {
	CommandRequestHeader

	Body struct {
		Pid     int64
		Options uint32
	}
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *KillProcessRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *KillProcessRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	return binary.Read(buf, binary.LittleEndian, &r.Body)
}

type ListProcessesRequest struct {
	CommandRequestHeader

	Body struct {
		Key     uint32
		Offset  uint32
		NumPids uint32
	}

	Pids []int64
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *ListProcessesRequest) MarshalBinary() ([]byte, error) {
	r.Body.NumPids = uint32(len(r.Pids))

	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	for _, pid := range r.Pids {
		_ = binary.Write(buf, binary.LittleEndian, &pid)
	}

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *ListProcessesRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	r.Pids = make([]int64, r.Body.NumPids)

	for i := uint32(0); i < r.Body.NumPids; i++ {
		err := binary.Read(buf, binary.LittleEndian, &r.Pids[i])
		if err != nil {
			return err
		}
	}

	return nil
}

type ReadEnvironmentVariablesRequest struct {
	CommandRequestHeader

	Body struct {
		NumNames    uint32
		NamesLength uint32
	}

	Names []string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *ReadEnvironmentVariablesRequest) MarshalBinary() ([]byte, error) {
	var env bytes.Buffer

	if n := len(r.Names); n != 0 {
		for _, e := range r.Names {
			_, _ = env.Write([]byte(e))
			_ = env.WriteByte(0)
		}
		r.Body.NumNames = uint32(n)
		r.Body.NamesLength = uint32(env.Len())
	}

	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	if r.Body.NamesLength != 0 {
		_, _ = buf.Write(env.Bytes())
	}

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *ReadEnvironmentVariablesRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	for i := 0; i < int(r.Body.NumNames); i++ {
		env, rerr := buf.ReadString(0)
		if rerr != nil {
			return rerr
		}

		env = env[:len(env)-1] // discard NULL terminator
		r.Names = append(r.Names, env)
	}

	return nil
}

type CreateTempFileRequest struct {
	CommandRequestHeader

	Body struct {
		Options             int32
		FilePrefixLength    uint32
		FileSuffixLength    uint32
		DirectoryPathLength uint32
		PropertyListLength  uint32
	}

	FilePrefix    string
	FileSuffix    string
	DirectoryPath string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *CreateTempFileRequest) MarshalBinary() ([]byte, error) {
	var fields []string

	add := func(s string, l *uint32) {
		*l = uint32(len(s)) // NOTE: NULL byte is not included in the length fields on the wire
		fields = append(fields, s)
	}

	add(r.FilePrefix, &r.Body.FilePrefixLength)
	add(r.FileSuffix, &r.Body.FileSuffixLength)
	add(r.DirectoryPath, &r.Body.DirectoryPathLength)

	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	for _, val := range fields {
		_, _ = buf.Write([]byte(val))
		_ = buf.WriteByte(0)
	}

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *CreateTempFileRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	fields := []struct {
		len uint32
		val *string
	}{
		{r.Body.FilePrefixLength, &r.FilePrefix},
		{r.Body.FileSuffixLength, &r.FileSuffix},
		{r.Body.DirectoryPathLength, &r.DirectoryPath},
	}

	for _, field := range fields {
		field.len++ // NOTE: NULL byte is not included in the length fields on the wire

		x := buf.Next(int(field.len))
		*field.val = string(bytes.TrimRight(x, "\x00"))
	}

	return nil
}

type FileRequest struct {
	CommandRequestHeader

	Body struct {
		FileOptions         int32
		GuestPathNameLength uint32
	}

	GuestPathName string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *FileRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	r.Body.GuestPathNameLength = uint32(len(r.GuestPathName))

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	_, _ = buf.WriteString(r.GuestPathName)
	_ = buf.WriteByte(0)

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *FileRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	name := buf.Next(int(r.Body.GuestPathNameLength))
	r.GuestPathName = string(bytes.TrimRight(name, "\x00"))

	return nil
}

type DirRequest struct {
	CommandRequestHeader

	Body struct {
		FileOptions          int32
		GuestPathNameLength  uint32
		FilePropertiesLength uint32
		Recursive            bool
	}

	GuestPathName string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *DirRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	r.Body.GuestPathNameLength = uint32(len(r.GuestPathName))

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	_, _ = buf.WriteString(r.GuestPathName)
	_ = buf.WriteByte(0)

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *DirRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	name := buf.Next(int(r.Body.GuestPathNameLength))
	r.GuestPathName = string(bytes.TrimRight(name, "\x00"))

	return nil
}

type RenameFileRequest struct {
	CommandRequestHeader

	Body struct {
		CopyFileOptions      int32
		OldPathNameLength    uint32
		NewPathNameLength    uint32
		FilePropertiesLength uint32
		Overwrite            bool
	}

	OldPathName string
	NewPathName string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *RenameFileRequest) MarshalBinary() ([]byte, error) {
	var fields []string

	add := func(s string, l *uint32) {
		*l = uint32(len(s)) // NOTE: NULL byte is not included in the length fields on the wire
		fields = append(fields, s)
	}

	add(r.OldPathName, &r.Body.OldPathNameLength)
	add(r.NewPathName, &r.Body.NewPathNameLength)

	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	for _, val := range fields {
		_, _ = buf.Write([]byte(val))
		_ = buf.WriteByte(0)
	}

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *RenameFileRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	fields := []struct {
		len uint32
		val *string
	}{
		{r.Body.OldPathNameLength, &r.OldPathName},
		{r.Body.NewPathNameLength, &r.NewPathName},
	}

	for _, field := range fields {
		field.len++ // NOTE: NULL byte is not included in the length fields on the wire

		x := buf.Next(int(field.len))
		*field.val = string(bytes.TrimRight(x, "\x00"))
	}

	return nil
}

type ListFilesRequest struct {
	CommandRequestHeader

	Body struct {
		FileOptions         int32
		GuestPathNameLength uint32
		PatternLength       uint32
		Index               int32
		MaxResults          int32
		Offset              uint64
	}

	GuestPathName string
	Pattern       string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *ListFilesRequest) MarshalBinary() ([]byte, error) {
	var fields []string

	add := func(s string, l *uint32) {
		if n := len(s); n != 0 {
			*l = uint32(n) + 1
			fields = append(fields, s)
		}
	}

	add(r.GuestPathName, &r.Body.GuestPathNameLength)
	add(r.Pattern, &r.Body.PatternLength)

	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	for _, val := range fields {
		_, _ = buf.Write([]byte(val))
		_ = buf.WriteByte(0)
	}

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *ListFilesRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	fields := []struct {
		len uint32
		val *string
	}{
		{r.Body.GuestPathNameLength, &r.GuestPathName},
		{r.Body.PatternLength, &r.Pattern},
	}

	for _, field := range fields {
		if field.len == 0 {
			continue
		}

		x := buf.Next(int(field.len))
		*field.val = string(bytes.TrimRight(x, "\x00"))
	}

	return nil
}

type SetGuestFileAttributesRequest struct {
	CommandRequestHeader

	Body struct {
		FileOptions         int32
		AccessTime          int64
		ModificationTime    int64
		OwnerID             int32
		GroupID             int32
		Permissions         int32
		Hidden              bool
		ReadOnly            bool
		GuestPathNameLength uint32
	}

	GuestPathName string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *SetGuestFileAttributesRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	r.Body.GuestPathNameLength = uint32(len(r.GuestPathName))

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	_, _ = buf.WriteString(r.GuestPathName)
	_ = buf.WriteByte(0)

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *SetGuestFileAttributesRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	name := buf.Next(int(r.Body.GuestPathNameLength))
	r.GuestPathName = string(bytes.TrimRight(name, "\x00"))

	return nil
}

func (r *SetGuestFileAttributesRequest) IsSet(opt int32) bool {
	return r.Body.FileOptions&opt == opt
}

type CommandHgfsSendPacket struct {
	CommandRequestHeader

	Body struct {
		PacketSize uint32
		Timeout    int32
	}

	Packet []byte
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *CommandHgfsSendPacket) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	_, _ = buf.Write(r.Packet)

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *CommandHgfsSendPacket) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	r.Packet = buf.Next(int(r.Body.PacketSize))

	return nil
}

type InitiateFileTransferToGuestRequest struct {
	CommandRequestHeader

	Body struct {
		Options             int32
		GuestPathNameLength uint32
		Overwrite           bool
	}

	GuestPathName string
}

// MarshalBinary implements the encoding.BinaryMarshaler interface
func (r *InitiateFileTransferToGuestRequest) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	r.Body.GuestPathNameLength = uint32(len(r.GuestPathName))

	_ = binary.Write(buf, binary.LittleEndian, &r.Body)

	_, _ = buf.WriteString(r.GuestPathName)
	_ = buf.WriteByte(0)

	return buf.Bytes(), nil
}

// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface
func (r *InitiateFileTransferToGuestRequest) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(data)

	err := binary.Read(buf, binary.LittleEndian, &r.Body)
	if err != nil {
		return err
	}

	name := buf.Next(int(r.Body.GuestPathNameLength))
	r.GuestPathName = string(bytes.TrimRight(name, "\x00"))

	return nil
}

type UserCredentialNamePassword struct {
	Body struct {
		NameLength     uint32
		PasswordLength uint32
	}

	Name     string
	Password string
}

func (c *UserCredentialNamePassword) UnmarshalBinary(data []byte) error {
	buf := bytes.NewBuffer(bytes.TrimRight(data, "\x00"))

	err := binary.Read(buf, binary.LittleEndian, &c.Body)
	if err != nil {
		return err
	}

	str, err := base64.StdEncoding.DecodeString(buf.String())
	if err != nil {
		return err
	}

	c.Name = string(str[0:c.Body.NameLength])
	c.Password = string(str[c.Body.NameLength+1 : len(str)-1])

	return nil
}

func (c *UserCredentialNamePassword) MarshalBinary() ([]byte, error) {
	buf := new(bytes.Buffer)

	c.Body.NameLength = uint32(len(c.Name))
	c.Body.PasswordLength = uint32(len(c.Password))

	_ = binary.Write(buf, binary.LittleEndian, &c.Body)

	src := append([]byte(c.Name+"\x00"), []byte(c.Password+"\x00")...)

	enc := base64.StdEncoding
	pwd := make([]byte, enc.EncodedLen(len(src)))
	enc.Encode(pwd, src)
	_, _ = buf.Write(pwd)
	_ = buf.WriteByte(0)

	return buf.Bytes(), nil
}