// RLockedOpenFile - returns a wrapped read locked file, if the file
// doesn't exist at path returns an error.
554352
func RLockedOpenFile(path string) (*RLockedFile, error) {
	lkFile, err := LockedOpenFile(path, os.O_RDONLY, 0666)
	if err != nil {
		return nil, err
	}

	return newRLockedFile(lkFile)

}
644946
func DecryptPEMBlock(block *pem.Block, password []byte) ([]byte, error) {
	der := block.Bytes

	var privKey encryptedPrivateKeyInfo
	if _, err := asn1.Unmarshal(der, &privKey); err != nil {
		return nil, errors.New("pkcs8: only PKCS #5 v2.0 supported")
	}

	if !privKey.EncryptionAlgorithm.IDPBES2.Equal(oidPBES2) {
		return nil, errors.New("pkcs8: only PBES2 supported")
	}

	if !privKey.EncryptionAlgorithm.PBES2Params.KeyDerivationFunc.IDPBKDF2.Equal(oidPKCS5PBKDF2) {
		return nil, errors.New("pkcs8: only PBKDF2 supported")
	}

	encParam := privKey.EncryptionAlgorithm.PBES2Params.EncryptionScheme
	kdfParam := privKey.EncryptionAlgorithm.PBES2Params.KeyDerivationFunc.PBKDF2Params

	switch {
	case encParam.EncryAlgo.Equal(oidAES256CBC):
		iv := encParam.IV
		salt := kdfParam.Salt
		iter := kdfParam.IterationCount

		encryptedKey := privKey.EncryptedData
		symkey := pbkdf2.Key(password, salt, iter, 32, sha1.New)
		block, err := aes.NewCipher(symkey)
		if err != nil {
			return nil, err
		}
		mode := cipher.NewCBCDecrypter(block, iv)
		mode.CryptBlocks(encryptedKey, encryptedKey)

		if _, err := derhelpers.ParsePrivateKeyDER(encryptedKey); err != nil {
			return nil, errors.New("pkcs8: incorrect password")
		}

		// Remove padding from key as it might be used to encode to memory as pem
		keyLen := len(encryptedKey)
		padLen := int(encryptedKey[keyLen-1])
		if padLen > keyLen || padLen > aes.BlockSize {
			return nil, errors.New("pkcs8: invalid padding size")
		}
		encryptedKey = encryptedKey[:keyLen-padLen]

		return encryptedKey, nil
	default:
		return nil, errors.New("pkcs8: only AES-256-CBC supported")
	}
}
1021540
func CreateLockFile(file string) (LockFile, error) {
	f, err := os.Create(file)
	if err != nil {
		// Consider those fatal, others may be considered transient
		// (for instance FD limit reached, etc...)
		if os.IsNotExist(err) || os.IsPermission(err) {
			return nil, err
		}
		return nil, ErrUnableToLockNow
	}
	spec := &syscall.Flock_t{
		Type:   syscall.F_WRLCK,
		Whence: int16(io.SeekStart),
		Start:  0,
		Len:    0, // 0 means to lock the entire file.
	}
	if err := syscall.FcntlFlock(f.Fd(), syscall.F_SETLK, spec); err != nil {
		// Try to gather all errors that we deem transient and return
		// ErrUnableToLockNow in this case to indicate the caller that
		// the lock could not be acquired at this time but it could
		// try later.
		// Basing this from possible ERRORS from this page:
		// http://pubs.opengroup.org/onlinepubs/009695399/functions/fcntl.html
		if err == syscall.EAGAIN || err == syscall.EACCES ||
			err == syscall.EINTR || err == syscall.ENOLCK {
			err = ErrUnableToLockNow
		}
		// TODO: If error is not ErrUnableToLockNow, it may mean that
		// the call is not supported on that platform, etc...
		// We should have another level of verification, for instance
		// check content of the lockfile is not being updated by the
		// owner of the file, etc...
		f.Close()
		return nil, err
	}
	return &lockFile{f: f}, nil
}
253476
func (fm *filesManager) lockFile(file *file) (bool, error) {
	if atomic.CompareAndSwapInt32(&file.state, fileOpened, fileInUse) {
		return true, nil
	}
	return false, fm.openFile(file)
}
29401
func (f *LockPIDFile) Lock() (err error) {
	if isIOS {
		// on iOS, our share extension can have multiple copies running, and furthermore this lock
		// doesn't do anything there, so let's just do nothing.
		f.G().Log.Debug("Skipping PID file lock on iOS")
		return nil
	}

	if f.file, err = os.OpenFile(f.name, os.O_CREATE|os.O_RDWR, 0600); err != nil {
		return PIDFileLockError{f.name}
	}

	// LOCK_EX = exclusive
	// LOCK_NB = nonblocking
	if err = syscall.Flock(int(f.file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
		f.file.Close()
		f.file = nil
		return PIDFileLockError{f.name}
	}

	pid := os.Getpid()
	fmt.Fprintf(f.file, "%d", pid)
	f.file.Sync()

	f.G().Log.Debug("Locked pidfile %s for pid=%d", f.name, pid)

	return nil
}
693857
func (c *Client) IsFileLockedByCurrentCommitter(path string) bool {
	filter := map[string]string{"path": path}
	locks, err := c.searchLocalLocks(filter, 1)
	if err != nil {
		tracerx.Printf("Error searching cached locks: %s\nForcing remote search", err)
		locks, _ = c.searchRemoteLocks(filter, 1)
	}
	return len(locks) > 0
}
1085196
func (fbo *folderBlockOps) getDirtyDirUnrefsLocked(
	lState *kbfssync.LockState, ptr data.BlockPointer) []data.BlockInfo {
	fbo.blockLock.AssertRLocked(lState)
	return fbo.dirtyDirs[ptr]
}
521270
func DecryptFile(inFilePath, outFilePath string, key, iv, aad []byte) error {
	if _, err := os.Stat(inFilePath); os.IsNotExist(err) {
		return fmt.Errorf("A file does not exist at %s", inFilePath)
	}

	inFile, err := os.Open(inFilePath)
	if err != nil {
		return err
	}
	defer inFile.Close()

	outFile, err := os.OpenFile(outFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	defer outFile.Close()

	w, err := NewDecryptWriteCloser(outFile, key, iv, aad)
	if err != nil {
		return err
	}
	defer w.Close()

	_, err = io.Copy(w, inFile)
	return err
}
217644
func unlockpt(f *os.File) error {
	var u int32
	return ioctl(f.Fd(), unix.TIOCPTYUNLK, uintptr(unsafe.Pointer(&u)))
}
648262
func getLockfile() (lockfile.Lockfile, error) {
	lockPath := filepath.Join(os.TempDir(), ".containerdiff.lock")
	lock, err := lockfile.New(lockPath)
	if err != nil {
		return lock, err
	}
	return lock, nil
}
649459
func (fm *filesManager) closeLockedFile(file *file) error {
	if !atomic.CompareAndSwapInt32(&file.state, fileInUse, fileClosing) {
		panic(fmt.Errorf("file %q is requested to be closed but was not locked by caller", file.name))
	}
	fm.Lock()
	err := fm.doClose(file)
	fm.Unlock()
	return err
}
966396
func unlockSandbox(lockFile *os.File) error {
	if lockFile == nil {
		return fmt.Errorf("lockFile cannot be empty")
	}

	err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
	if err != nil {
		return err
	}

	lockFile.Close()

	return nil
}
284443
func (d *Diskv) ensurePathWithLock(pathKey *PathKey) error {
	return os.MkdirAll(d.pathFor(pathKey), d.PathPerm)
}
635785
func UnmarshalBlockFromFile(blockFile string) *common.Block {
	blockBytes, err := ioutil.ReadFile(blockFile)
	Expect(err).NotTo(HaveOccurred())

	block, err := utils.UnmarshalBlock(blockBytes)
	Expect(err).NotTo(HaveOccurred())

	return block
}
834448
func CleanKeyLocks(lockDir string) error {
	f, err := os.Open(lockDir)
	if err != nil {
		return errwrap.Wrap(errors.New("error opening lockDir"), err)
	}
	defer f.Close()
	files, err := f.Readdir(0)
	if err != nil {
		return errwrap.Wrap(errors.New("error getting lock files list"), err)
	}
	for _, f := range files {
		filename := filepath.Join(lockDir, f.Name())
		keyLock, err := TryExclusiveKeyLock(lockDir, f.Name())
		if err == ErrLocked {
			continue
		}
		if err != nil {
			return err
		}

		err = os.Remove(filename)
		if err != nil {
			keyLock.Close()
			return errwrap.Wrap(errors.New("error removing lock file"), err)
		}
		keyLock.Close()
	}
	return nil
}
876132
func TryExclusiveLock(path string, lockType LockType) (*FileLock, error) {
	l, err := NewLock(path, lockType)
	if err != nil {
		return nil, err
	}
	err = l.TryExclusiveLock()
	if err != nil {
		return nil, err
	}
	return l, err
}
49338
func LoadPEMPrivKeyFile(name string) (*rsa.PrivateKey, error) {
	file, err := os.Open(name)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	return LoadPEMPrivKey(file)
}