Debian Codegraph @

internal/sender/flist.go

raw symbols SCIP
1 package sender
2
3 import (
4 "fmt"
5 "io/fs"
6 "os"
7 "os/user"
8 "path"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "sync"
13 "time"
14
15 "github.com/gokrazy/rsync"
16 "github.com/gokrazy/rsync/internal/rsyncchecksum"
17 "github.com/gokrazy/rsync/internal/rsyncopts"
18 "github.com/gokrazy/rsync/internal/rsyncwire"
19 )
20
21 type file struct {
22 source FileSource
23 path string
24 Wpath string
25 regular bool
26
27 // fields below are used by the receiver (TODO: unify)
28 Name string
29 Length int64
30 ModTime time.Time
31 Mode int32
32 Uid int32
33 Gid int32
34 LinkTarget string
35 Rdev int32
36 }
37
38 type fileList struct {
39 TotalSize int64
40 Files []file
41 Sources []FileSource
42 }
43
44 // A fileList must not be used after calling Close().
45 func (fl *fileList) Close() {
46 for _, source := range fl.Sources {
47 source.Close()
48 }
49 fl.Sources = nil
50 }
51
52 // rsync/rsync.h defines chunkSize as 32 * 1024, which we match.
53 //
54 // Other parts of rsync have subtle dependencies on the chunkSize.
55 // For example, (*sender.Transfer).hashSearch declares a window
56 // of at least 256 KB and then reads from that window, requesting
57 // 2*chunkSize+alignFudge, which must not exceed the window.
58 // So raising chunkSize to 128 KB or 256 KB breaks transfers
59 // with "file has changed mid-transfer" (issue #53).
60 const chunkSize = 32 * 1024
61
62 var (
63 lookupOnce sync.Once
64 lookupGroupOnce sync.Once
65 )
66
67 // getStrip operates on wire paths (slash space).
68 func getStrip(requested string) string {
69 if requested == "/" {
70 return ""
71 }
72 if strings.HasSuffix(requested, "/") {
73 return strings.TrimPrefix(path.Clean(requested), "/") + "/"
74 }
75 return ""
76 }
77
78 type scopedWalker struct {
79 st *Transfer
80 ioError func(err error)
81 conn *rsyncwire.Conn
82 fec *rsyncwire.Buffer
83 excl *filterRuleList
84 uidMap map[int32]string
85 gidMap map[int32]string
86 fileList *fileList
87 source FileSource
88 localDir string
89 requested string
90 strip string
91 subdir string
92 prefix string
93 }
94
95 func (s *scopedWalker) walk() error {
96 if s.source == nil {
97 fi, err := os.Lstat(s.localDir)
98 if err != nil {
99 s.st.Logger.Printf(" Lstat(localDir=%q): %v", s.localDir, err)
100 return fmt.Errorf("i/o error: requested module path is not accessible")
101 }
102 if fi.IsDir() {
103 root, err := os.OpenRoot(s.localDir)
104 if err != nil {
105 s.st.Logger.Printf(" OpenRoot(localDir=%q): %v", s.localDir, err)
106 return fmt.Errorf("i/o error: requested module path is not accessible")
107 }
108 s.source = newOSRootSource(root)
109 } else {
110 s.source = newSingleFileSource(s.localDir, fi)
111 }
112 s.fileList.Sources = append(s.fileList.Sources, s.source)
113 }
114 if s.subdir != "." {
115 sub, err := newSubSource(s.source, s.subdir)
116 if err != nil {
117 s.st.Logger.Printf(" newSubSource(subdir=%q): %v", s.subdir, err)
118 return fmt.Errorf("i/o error: requested module path is not accessible")
119 }
120 s.source = sub
121 }
122
123 rootname := s.requested
124 // fs.WalkDir(root.FS(), …) does not accept absolute paths,
125 // so make them relative by prepending a .
126 if strings.HasPrefix(rootname, "/") {
127 rootname = "." + rootname
128 }
129 if err := fs.WalkDir(s.source.FS(), path.Clean(rootname), s.walkFn); err != nil {
130 return err
131 }
132 return nil
133 }
134
135 func (s *scopedWalker) walkFn(path string, d fs.DirEntry, err error) error {
136 logger := s.st.Logger // for convenience
137 opts := s.st.Opts // for convenience
138 if opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
139 logger.Printf("filepath.WalkFn(path=%s)", path)
140 }
141 var info fs.FileInfo
142 if err == nil {
143 info, err = d.Info()
144 }
145 if err != nil {
146 // set the I/O error flag, but keep walking
147 s.ioError(err)
148 return nil
149 }
150
151 if opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
152 logger.Printf("isDir=%v, xferDirs=%v", info.Mode().IsDir(), opts.XferDirs())
153 }
154 if info.Mode().IsDir() && opts.XferDirs() == 0 {
155 logger.Printf("skipping directory %s", path)
156 return filepath.SkipDir
157 }
158
159 // Only ever transmit long names, like openrsync
160 flags := byte(rsync.XMIT_LONG_NAME)
161
162 name := path
163 if s.strip != "" {
164 if path+"/" == s.strip {
165 // Transmit the top directory as ., like tridge rsync.
166 name = "."
167 } else {
168 name = strings.TrimPrefix(name, s.strip)
169 }
170 }
171 if s.prefix != "" {
172 if path == "." {
173 name = s.prefix
174 } else {
175 name = s.prefix + "/" + path
176 }
177 }
178 if opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
179 logger.Printf("Trim(path=%q) = %q", path, name)
180 }
181 if path == "." && s.prefix == "" {
182 flags |= rsync.XMIT_TOP_DIR
183 }
184 // st.logger.Printf("flags for %q: %v", name, flags)
185
186 if s.excl.matches(name) {
187 return filepath.SkipDir
188 }
189
190 s.fileList.Files = append(s.fileList.Files, file{
191 source: s.source,
192 path: path,
193 regular: info.Mode().IsRegular(),
194 Wpath: name,
195 Length: info.Size(),
196 })
197
198 s.fec.Reset()
199
200 // 1. status byte (integer)
201 s.fec.WriteByte(flags)
202
203 // 2. inherited filename length (optional, byte)
204 // 3. filename length (integer or byte)
205 s.fec.WriteInt32(int32(len(name)))
206
207 // 4. file (byte array)
208 s.fec.WriteString(name)
209
210 // 5. file length (long)
211 size := info.Size()
212 if info.Mode().IsDir() {
213 // tmpfs returns non-4K sizes for directories. Override with
214 // 4096 to make the tests succeed regardless of the /tmp file
215 // system type.
216 size = 4096
217 }
218 s.fec.WriteInt64(size)
219
220 s.fileList.TotalSize += size
221
222 // 6. file modification time (optional, integer)
223 // TODO: this will overflow in 2038! :(
224 s.fec.WriteInt32(int32(info.ModTime().Unix()))
225
226 // 7. file mode (optional, mode_t, integer)
227 mode := int32(info.Mode() & os.ModePerm)
228 isDev := false
229 isSpecial := false
230 if info.Mode().IsDir() {
231 mode |= rsync.S_IFDIR
232 } else if info.Mode().IsRegular() {
233 mode |= rsync.S_IFREG
234 } else if info.Mode().Type()&os.ModeSymlink != 0 {
235 mode |= rsync.S_IFLNK
236 // TODO: skip symlink if PreserveSymlinks is not set
237 }
238
239 if info.Mode().Type()&os.ModeCharDevice != 0 {
240 mode |= rsync.S_IFCHR
241 isDev = true
242 } else if info.Mode().Type()&os.ModeDevice != 0 {
243 mode |= rsync.S_IFBLK
244 isDev = true
245 }
246
247 if info.Mode().Type()&os.ModeNamedPipe != 0 {
248 mode |= rsync.S_IFIFO
249 isSpecial = true
250 }
251
252 if info.Mode().Type()&os.ModeSocket != 0 {
253 mode |= rsync.S_IFSOCK
254 isSpecial = true
255 }
256
257 s.fec.WriteInt32(mode)
258
259 if opts.PreserveUid() {
260 uid, ok := uidFromFileInfo(info)
261 if ok {
262 if _, ok := s.uidMap[uid]; !ok && uid != 0 {
263 u, err := user.LookupId(strconv.Itoa(int(uid)))
264 if err != nil {
265 lookupOnce.Do(func() {
266 logger.Printf("lookup(%d) = %v", uid, err)
267 })
268 } else {
269 s.uidMap[uid] = u.Username
270 }
271 }
272 }
273 // 8. if -o, the user id (integer)
274 s.fec.WriteInt32(uid)
275 }
276
277 if opts.PreserveGid() {
278 gid, ok := gidFromFileInfo(info)
279 if ok {
280 if _, ok := s.gidMap[gid]; !ok && gid != 0 {
281 g, err := user.LookupGroupId(strconv.Itoa(int(gid)))
282 if err != nil {
283 lookupGroupOnce.Do(func() {
284 logger.Printf("lookupgroup(%d) = %v", gid, err)
285 })
286 } else {
287 s.gidMap[gid] = g.Name
288 }
289 }
290 }
291 // 9. if -g, the group id (integer)
292 s.fec.WriteInt32(gid)
293 }
294
295 if (opts.PreserveDevices() && isDev) ||
296 (opts.PreserveSpecials() && isSpecial) {
297 // 10. if a special file and -D, the device “rdev” type (integer)
298 rdev, _ := rdevFromFileInfo(info)
299 s.fec.WriteInt32(rdev)
300 }
301
302 if opts.PreserveLinks() && info.Mode().Type()&os.ModeSymlink != 0 {
303 // 11. if a symbolic link and -l, the link target's length (integer)
304 // 12. if a symbolic link and -l, the link target (byte array)
305
306 target, err := s.source.Readlink(path)
307 if err != nil {
308 return err // TODO
309 }
310 s.fec.WriteInt32(int32(len(target)))
311 s.fec.WriteString(target)
312 }
313
314 if opts.AlwaysChecksum() {
315 var emptyChecksum [rsyncchecksum.Size]byte
316 checksum := emptyChecksum[:]
317 if info.Mode().IsRegular() {
318 f, err := s.source.Open(path)
319 if err != nil {
320 return err
321 }
322 checksum, err = rsyncchecksum.ReaderChecksum(f)
323 f.Close()
324 if err != nil {
325 return err
326 }
327 } else {
328 // send empty md4 checksum
329 }
330 s.fec.WriteString(string(checksum))
331 }
332
333 s.conn.WriteString(s.fec.String())
334
335 // The status byte may consist of the following bits and determines which of the optional fields are transmitted.
336
337 // 0x01 A top-level directory. (Only applies to directory files.) If specified, the matching local directory is for deletions.
338 // 0x02 Do not send the file mode: it is a repeat of the last file's mode.
339 // 0x08 Like 0x02, but for the user id.
340 // 0x10 Like 0x02, but for the group id.
341 // 0x20 Inherit some of the prior file name. Enables the inherited filename length transmission.
342 // 0x40 Use full integer length for file name. Otherwise, use only the byte length.
343 // 0x80 Do not send the file modification time: it is a repeat of the last file's.
344
345 // If the status byte is zero, the file-list has terminated.
346
347 if info.Mode().IsDir() && !opts.Recurse() {
348 return filepath.SkipDir
349 }
350
351 return nil
352 }
353
354 // rsync/flist.c:send_file_list
355 func (st *Transfer) SendFileList(localDir string, paths []string, excl *filterRuleList) (*fileList, error) {
356 var fileList fileList
357 fec := &rsyncwire.Buffer{}
358
359 uidMap := make(map[int32]string)
360 gidMap := make(map[int32]string)
361
362 // TODO: flush in between to keep the pipes filled when traversal takes long
363
364 // TODO: handle info == nil case (permission denied?): should set an i/o
365 // error flag, but traversal should continue
366
367 st.Logger.Printf("building file list")
368 if st.Opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
369 st.Logger.Printf("sendFileList()")
370 }
371 ioErrors := int32(0)
372
373 ioError := func(err error) {
374 if os.IsNotExist(err) {
375 st.Logger.Printf("file vanished: %v", err)
376 } else {
377 st.Logger.Printf("lstat: %v", err)
378 }
379 ioErrors = 1
380 }
381
382 for _, requested := range paths {
383 subdir := "."
384 prefix := ""
385 local := localDir
386 if local == rsync.FileSystemRoot {
387 // Implicit module (/) and absolute requested path (/tmp/foo/),
388 // turn the path into the local directory and request /.
389 local = filepath.Clean(requested)
390 if strings.HasSuffix(requested, "/") {
391
392 } else {
393 prefix = filepath.Base(requested)
394 }
395 requested = "/"
396 } else if !strings.HasSuffix(requested, "/") {
397 st.Logger.Printf(" handling requested=%q", requested)
398 clean := path.Clean(strings.TrimPrefix(requested, "/"))
399 subdir = path.Dir(clean)
400 requested = path.Base(clean)
401 st.Logger.Printf(" -> subdir=%q, requested=%q", subdir, requested)
402 }
403
404 if st.Opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
405 st.Logger.Printf(" path %q (local dir %q)", requested, local)
406 }
407 // st.Logger.Printf("getRootStrip(requested=%q, localDir=%q", requested, localDir)
408 strip := getStrip(requested)
409 // st.Logger.Printf("root=%q, strip=%q", root, strip)
410 if st.Opts.DebugGTE(rsyncopts.DEBUG_FLIST, 1) {
411 st.Logger.Printf(" fs.Walk(%q, %q), strip=%q", local, requested)
412 }
413
414 sw := &scopedWalker{
415 st: st,
416 conn: st.Conn,
417 fec: fec,
418 excl: excl,
419 uidMap: uidMap,
420 gidMap: gidMap,
421 fileList: &fileList,
422 source: st.Source,
423 ioError: ioError,
424 localDir: local,
425 requested: requested,
426 strip: strip,
427 subdir: subdir,
428 prefix: prefix,
429 }
430 if err := sw.walk(); err != nil {
431 return nil, err
432 }
433 }
434
435 if st.Opts.InfoGTE(rsyncopts.INFO_PROGRESS, 1) {
436 st.Logger.Printf("%d files to consider", len(fileList.Files))
437 }
438
439 fec.Reset()
440
441 const endOfFileList = 0
442 fec.WriteByte(endOfFileList)
443
444 const endOfSet = 0
445 if st.Opts.PreserveUid() {
446 for uid, name := range uidMap {
447 fec.WriteInt32(uid)
448 fec.WriteByte(byte(len(name)))
449 fec.WriteString(name)
450 }
451 fec.WriteInt32(endOfSet)
452 }
453 if st.Opts.PreserveGid() {
454 for gid, name := range gidMap {
455 fec.WriteInt32(gid)
456 fec.WriteByte(byte(len(name)))
457 fec.WriteString(name)
458 }
459 fec.WriteInt32(endOfSet)
460 }
461
462 fec.WriteInt32(ioErrors)
463
464 if err := st.Conn.WriteString(fec.String()); err != nil {
465 return nil, err
466 }
467
468 return &fileList, nil
469 }