go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/connection/ssh/sftp/file.go (about) 1 // Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package sftp 15 16 import ( 17 "errors" 18 "fmt" 19 "os" 20 21 "github.com/pkg/sftp" 22 ) 23 24 type File struct { 25 fd *sftp.File 26 c *sftp.Client 27 } 28 29 func FileOpen(s *sftp.Client, name string) (*File, error) { 30 fd, err := s.Open(name) 31 if err != nil { 32 return &File{}, err 33 } 34 return &File{ 35 fd: fd, 36 c: s, 37 }, nil 38 } 39 40 func FileCreate(s *sftp.Client, name string) (*File, error) { 41 fd, err := s.Create(name) 42 if err != nil { 43 return &File{}, err 44 } 45 return &File{ 46 fd: fd, 47 c: s, 48 }, nil 49 } 50 51 func (f *File) Close() error { 52 if f != nil && f.fd != nil { 53 return f.fd.Close() 54 } 55 return nil 56 } 57 58 func (f *File) Name() string { 59 if f != nil && f.fd != nil { 60 return f.fd.Name() 61 } 62 return "" 63 } 64 65 func (f *File) Stat() (os.FileInfo, error) { 66 if f != nil && f.fd != nil { 67 return f.fd.Stat() 68 } 69 return nil, errors.New("cannot access file") 70 } 71 72 func (f *File) Sync() error { 73 return nil 74 } 75 76 func (f *File) Truncate(size int64) error { 77 return f.fd.Truncate(size) 78 } 79 80 func (f *File) Read(b []byte) (n int, err error) { 81 return f.fd.Read(b) 82 } 83 84 // TODO 85 func (f *File) ReadAt(b []byte, off int64) (n int, err error) { 86 return 0, errors.New("not implemented") 87 } 88 89 func (f *File) Readdir(count int) (res []os.FileInfo, err error) { 90 return f.c.ReadDir(f.Name()) 91 } 92 93 func (f *File) Readdirnames(n int) (names []string, err error) { 94 dirFileInfos, err := f.c.ReadDir(f.Name()) 95 if err != nil { 96 return nil, fmt.Errorf("ssh> could not read dirnames: %v", err) 97 } 98 99 dir := make([]string, len(dirFileInfos)) 100 for i := range dirFileInfos { 101 dir[i] = dirFileInfos[i].Name() 102 } 103 return dir, nil 104 } 105 106 func (f *File) Seek(offset int64, whence int) (int64, error) { 107 return f.fd.Seek(offset, whence) 108 } 109 110 func (f *File) Write(b []byte) (n int, err error) { 111 return f.fd.Write(b) 112 } 113 114 // TODO 115 func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 116 return 0, errors.New("not implemented") 117 } 118 119 func (f *File) WriteString(s string) (ret int, err error) { 120 return f.fd.Write([]byte(s)) 121 }