Example #1
0
// walkTo handles the walking logic. Walk returns a fidState, len(names) qids
// and a nil error if the walk succeeded. If the walk was partially successful,
// it returns a nil fidState, less than len(names) qids and a nil error. If the
// walk was completely unsuccessful, a nil fidState, nil qid slice and a non-nil
// error is returned.
func walkTo(oldState *fidState, names []string) (*fidState, []qp.Qid, error) {
	var (
		handle          trees.ReadWriteAtCloser
		isdir, addToLoc bool
		root, temproot  trees.File
		username, name  string
		newloc          FilePath
		qids            []qp.Qid
		d               trees.Dir
		err             error
		q               qp.Qid
	)

	// Walk and Arrived can block, so we don't want to be holding locks. Copy
	// what we need.
	oldState.RLock()
	handle = oldState.handle
	newloc = oldState.location.Clone()
	username = oldState.username
	oldState.RUnlock()

	root = newloc.Current()

	if root == nil {
		return nil, nil, errors.New(InvalidOpOnFid)
	}

	if handle != nil {
		// Can't walk on an open fid.
		return nil, nil, errors.New(FidOpen)
	}

	for i := range names {
		addToLoc = false
		name = names[i]
		switch name {
		case ".":
			// This always succeeds, but we don't want to add it to our location
			// list.
		case "..":
			// This also always succeeds, and it either does nothing or shortens
			// our location list. We don't want anything added to the list
			// regardless.
			root = newloc.Parent()
			if len(newloc) > 1 {
				newloc = newloc[:len(newloc)-1]
			}
		default:
			// A regular file name. In this case, walking to the name is only
			// legal if the current file is a directory.
			addToLoc = true

			isdir, err = root.IsDir()
			if err != nil {
				return nil, nil, err
			}

			if !isdir {
				// Root isn't a dir, so we can't walk.
				err = errors.New(FidNotDirectory)
				goto done
			}

			d = root.(trees.Dir)
			if root, err = d.Walk(username, name); err != nil {
				// The walk failed for some arbitrary reason.
				goto done
			} else if root == nil {
				// The file did not exist
				err = errors.New(NoSuchFile)
				goto done
			}

			if temproot, err = root.Arrived(username); err != nil {
				// The Arrived callback failed for some arbitrary reason.
				goto done
			}

			if temproot != nil {
				root = temproot
			}
		}

		if addToLoc {
			newloc = append(newloc, root)
		}

		q, err = root.Qid()
		if err != nil {
			return nil, nil, err
		}

		qids = append(qids, q)
	}

done:
	if err != nil && len(qids) == 0 {
		return nil, nil, err
	}
	if len(qids) < len(names) {
		return nil, qids, nil
	}

	s := &fidState{
		username: username,
		location: newloc,
	}

	return s, qids, nil
}