// Open rekeys if nonce[2:8] is different than in the last call, masks the nonce,
// and calls Open for aes128gcm.
429931
func (s *rekeyAEAD) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
	if err := s.rekeyIfRequired(nonce); err != nil {
		return nil, err
	}
	maskNonce(s.nonceBuf, nonce, s.nonceMask)
	return s.gcmAEAD.Open(dst, s.nonceBuf, ciphertext, additionalData)
}
344908
func Open(paths ...string) gkv.KV {
	var path string
	if len(paths) != 0 {
		path = paths[0]
	} else {
		path = filepath.Join(gkv.ProjectDir(), "data")
	}
	f, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			err = os.MkdirAll(path, 0755)
		}
		if err != nil {
			panic(err)
		}
	} else if !f.IsDir() {
		path = filepath.Dir(path)
	}

	opts := badger.DefaultOptions
	opts.Dir = path
	opts.ValueDir = path
	opts.MaxTableSize = 1 << 15
	opts.LevelOneSize = 4 << 15
	opts.SyncWrites = false

	db, err := badger.Open(opts)
	if err != nil {
		panic(err)
	}
	return &KV{
		db: db,
	}
}
1216370
func (e *TableDualExec) Open(ctx context.Context) error {
	e.numReturned = 0
	return nil
}
1009167
func (t *multiReopenWriter) Reopen() error {
	for _, w := range t.writers {
		err := w.Reopen()
		if err != nil {
			return err
		}
	}
	return nil
}
1092037
func Open(name string) (int, error) {
	return open(name, syscall.IFF_TUN|syscall.IFF_NO_PI)
}
504411
func Open(out, box []byte, nonce nacl.Nonce, peersPublicKey, privateKey nacl.Key) ([]byte, bool) {
	sharedKey := Precompute(peersPublicKey, privateKey)
	return secretbox.Open(out, box, nonce, sharedKey)
}
345720
func open(buf []byte, passphrase string) (map[string]string, error) {
	salt := make([]byte, saltLength)
	copy(salt, buf[:saltLength])
	var nonce [nonceLength]byte
	copy(nonce[:], buf[saltLength:nonceLength+saltLength])
	secretKey := deriveKey(passphrase, salt)
	decrypted, ok := secretbox.Open(nil, buf[nonceLength+saltLength:], &nonce, &secretKey)
	if !ok {
		return nil, fmt.Errorf("failed to decrypt")
	}
	data := map[string]string{}
	if err := json.Unmarshal(decrypted, &data); err != nil {
		return nil, err
	}
	return data, nil
}
1237066
func (e *Extractor) Open() (RETSResponse, error) {
	// TODO extract common work from rets/rets_response.go
	rets := RETSResponse{}
	e.parser = xml.NewDecoder(e.Body)
	start, err := e.skipTo("(RETS|RETS-STATUS)")
	if err != nil {
		return rets, err
	}
	attrs := make(map[string]string)
	for _, v := range start.Attr {
		attrs[strings.ToLower(v.Name.Local)] = v.Value
	}
	code, err := strconv.ParseInt(attrs["replycode"], 10, 16)
	if err != nil {
		return rets, err
	}
	rets.ReplyCode = int(code)
	rets.ReplyText = attrs["replytext"]
	return rets, nil
}
724351
func Open(bs *BlockDriverState, options *QDict, flag int) error {
	s := bs.Opaque
	var header Header

	err := bdrvPread(bs.file, 0, &header, unsafe.Sizeof(header))
	if err != nil {
		err = errors.Wrap(err, "Could not read qcow2 header")
		return err
	}

	if !bytes.Equal(BEUvarint32(header.Magic), MAGIC) {
		err := errors.Wrap(syscall.EINVAL, "Image is not in qcow2 format")
		return err
	}
	if header.Version < Version2 || header.Version > Version3 {
		err := errors.Wrapf(syscall.ENOTSUP, "Unsupported qcow2 version %d", header.Version)
		return err
	}

	s.Version = header.Version

	// Initialise cluster size
	if header.ClusterBits < MIN_CLUSTER_BITS || header.ClusterBits > MAX_CLUSTER_BITS {
		err := errors.Wrapf(syscall.EINVAL, "Unsupported cluster size: 2^%d", header.ClusterBits)
		return err
	}

	s.ClusterBits = int(header.ClusterBits)
	s.ClusterSize = 1 << uint(s.ClusterBits)
	s.ClusterSectors = 1 << uint(s.ClusterBits-9)

	// Initialise version 3 header fields
	if header.Version == Version2 {
		header.IncompatibleFeatures = 0
		header.CompatibleFeatures = 0
		header.AutoclearFeatures = 0
		header.RefcountOrder = 4
		header.HeaderLength = 72
	} else {
		if header.HeaderLength < 104 {
			err := errors.Wrap(syscall.EINVAL, "qcow2 header too short")
			return err
		}
	}

	if header.HeaderLength > uint32(s.ClusterSize) {
		err := errors.Wrap(syscall.EINVAL, "qcow2 header exceeds cluster size")
		return err
	}

	hdrSizeof := uint32(unsafe.Sizeof(header))
	if header.HeaderLength > hdrSizeof {
		s.UnknownheaderFieldsSize = int(header.HeaderLength - hdrSizeof)
		s.UnknownHeaderFields = make([]byte, s.UnknownheaderFieldsSize)
		err := bdrvPread(bs.file, int64(hdrSizeof), &s.UnknownHeaderFields, uintptr(s.UnknownheaderFieldsSize))
		if err != nil {
			err = errors.Wrap(err, "Could not read unknown qcow2 header fields")
			return err
		}
	}

	if header.BackingFileOffset > uint64(s.ClusterSize) {
		err := errors.Wrap(syscall.EINVAL, "Invalid backing file offset")
		return err
	}

	// var extEnd uint64
	// if header.BackingFileOffset != 0 {
	// 	extEnd = header.BackingFileOffset
	// } else {
	// 	extEnd = 1 << header.ClusterBits
	// }

	// Handle feature bits
	s.IncompatibleFeatures = header.IncompatibleFeatures
	s.CompatibleFeatures = header.CompatibleFeatures
	s.AutoclearFeatures = header.AutoclearFeatures

	if int(s.IncompatibleFeatures) & ^INCOMPAT_MASK != 0 {
		// TODO(zchee): implements read extensions
		// featureTable := nil
		// qcow2_read_extensions(bs, header.header_length, ext_end, &feature_table, NULL);
		// report_unsupported_feature(errp, feature_table, s->incompatible_features & ~QCOW2_INCOMPAT_MASK);
		// ret = -ENOTSUP;
		// g_free(feature_table);
		// goto fail;
	}

	if s.IncompatibleFeatures&INCOMPAT_CORRUPT != 0 {
		// TODO(zchee): implements
		// Corrupt images may not be written to unless they are being repaired
		// if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
		// 	error_setg(errp, "qcow2: Image is corrupt; cannot be opened read/write");
		// 	ret = -EACCES;
		// 	goto fail;
		// }
	}

	// Check support for various header values
	if header.RefcountOrder > 6 {
		err := errors.Wrap(syscall.EINVAL, "Reference count entry width too large; may not exceed 64 bits")
		return err
	}
	s.RefcountOrder = int(header.RefcountOrder)
	s.RefcountBits = 1 << uint(s.RefcountOrder)
	s.RefcountMax = uint64(1) << uint64(s.RefcountBits-1)
	s.RefcountMax += s.RefcountMax - 1

	if header.CryptMethod > CRYPT_AES {
		err := errors.Wrapf(syscall.EINVAL, "Unsupported encryption method: %d", header.CryptMethod)
		return err
	}
	// TODO(zchee): implements
	// if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
	// 	error_setg(errp, "AES cipher not available");
	// 	ret = -EINVAL;
	// 	goto fail;
	// }
	s.CryptMethodHeader = uint32(header.CryptMethod)
	if s.CryptMethodHeader != 0 {
		// TODO(zchee): implements
		// s->crypt_method_header == QCOW_CRYPT_AES) {
		// 	error_setg(errp, "Use of AES-CBC encrypted qcow2 images is no longer supported in system emulators")
		// 	error_append_hint(errp, "You can use 'qemu-img convert' to convert your image to an alternative supported format, such as unencrypted qcow2, or raw with the LUKS format instead.\n")
		// 	ret = -ENOSYS;
		// 	goto fail;
	}

	s.L2Bits = s.ClusterBits - 3
	s.L2Size = 1 << uint(s.L2Bits)
	// 2^(s->refcount_order - 3) is the refcount width in bytes
	s.RefcountBlockBits = s.ClusterBits - (s.RefcountOrder - 3)
	s.RefcountBlockSize = 1 << uint(s.RefcountBlockBits)
	bs.TotalSectors = int64(header.Size / 512)
	s.Csize_shift = (62 - (s.ClusterBits - 8))
	s.Csize_mask = (1 - (s.ClusterBits - 8)) - 1
	s.ClusterOffsetMask = (1 << uint(s.Csize_shift)) - 1

	s.RefcountTableOffset = header.RefcountTableOffset
	s.RefcountTableSize = header.RefcountTableClusters << uint(s.ClusterBits-3)

	if uint64(header.RefcountTableClusters) > maxRefcountClusters(s) {
		err := errors.Wrap(syscall.EINVAL, "Reference count table too large")
		return err
	}

	// ret = validate_table_offset(bs, header.l1_table_offset, header.l1_size, sizeof(uint64_t));

	return nil
}
876420
func (a *AtomicFS) Open(ctx context.Context, path string) (ctxvfs.ReadSeekCloser, error) {
	fs := a.v.Load().(ctxvfs.NameSpace)
	return fs.Open(ctx, path)
}
950298
func (w *ledgerDriver) Open(device io.ReadWriter, passphrase string) error {
	w.device, w.failure = device, nil

	_, err := w.ledgerDerive(accounts.DefaultBaseDerivationPath)
	if err != nil {
		// Ethereum app is not running or in browser mode, nothing more to do, return
		if err == errLedgerReplyInvalidHeader {
			w.browser = true
		}
		return nil
	}
	// Try to resolve the Ethereum app's version, will fail prior to v1.0.2
	if w.version, err = w.ledgerVersion(); err != nil {
		w.version = [3]byte{1, 0, 0} // Assume worst case, can't verify if v1.0.0 or v1.0.1
	}
	return nil
}
1233226
func Open(cfg RawConfig) (*Client, error) {
	client, err := OpenForSender(cfg, &senderOpener{})
	return client, errors.Trace(err)
}
1211033
func OpenAfterPrecomputation(out, box []byte, nonce nacl.Nonce, sharedKey nacl.Key) ([]byte, bool) {
	return secretbox.Open(out, box, nonce, sharedKey)
}
768667
func (c AesCbcHmac) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	if len(ciphertext) < c.keysize {
		return nil, errors.New("invalid ciphertext (too short)")
	}

	tagOffset := len(ciphertext) - c.tagsize
	if tagOffset%c.blockCipher.BlockSize() != 0 {
		return nil, fmt.Errorf(
			"invalid ciphertext (invalid length: %d %% %d != 0)",
			tagOffset,
			c.blockCipher.BlockSize(),
		)
	}
	tag := ciphertext[tagOffset:]
	ciphertext = ciphertext[:tagOffset]

	expectedTag := c.ComputeAuthTag(data, nonce, ciphertext)
	if subtle.ConstantTimeCompare(expectedTag, tag) != 1 {
		if debug.Enabled {
			debug.Printf("provided tag = %x\n", tag)
			debug.Printf("expected tag = %x\n", expectedTag)
		}
		return nil, errors.New("invalid ciphertext (tag mismatch)")
	}

	cbc := cipher.NewCBCDecrypter(c.blockCipher, nonce)
	buf := make([]byte, tagOffset)
	cbc.CryptBlocks(buf, ciphertext)

	plaintext, err := padbuf.PadBuffer(buf).Unpad(c.blockCipher.BlockSize())
	if err != nil {
		return nil, errors.Wrap(err, `failed to generate plaintext from decrypted blocks`)
	}
	ret := ensureSize(dst, len(plaintext))
	out := ret[len(dst):]
	copy(out, plaintext)
	return ret, nil
}
277050
func (l *OSFileSystemLoader) Open(name string) (io.ReadCloser, error) {
	return os.Open(name)
}
811636
func (f *File) Open(ctx context.Context, req *fuse.OpenRequest, resp *fuse.OpenResponse) (fs.Handle, error) {
	var dgst digest.Digest
	if rf, ok := f.resource.(continuity.RegularFile); ok {
		digests := rf.Digests()
		if len(digests) > 0 {
			dgst = digests[0]
		}
	}
	// TODO(dmcgowan): else check if device can be opened for read
	r, err := f.provider.Open(f.resource.Path(), dgst)
	if err != nil {
		logrus.Debugf("Error opening handle: %v", err)
		return nil, err
	}
	return &fileHandler{
		reader: r,
	}, nil

}
618939
func (res *Resource) Open() {
	res.stmu.Lock()
	defer res.stmu.Unlock()

	res.chmu.Lock()
	res.ch = make(chan struct{})
	res.chmu.Unlock()
}