github.com/quay/claircore@v1.5.28/rpm/bdb/doc.go (about)

     1  // Package bdb provides support for read-only access to an RPM database using the
     2  // BerkeleyDB "hash" format.
     3  package bdb
     4  
     5  import (
     6  	"context"
     7  	"encoding/binary"
     8  	"io"
     9  
    10  	"github.com/quay/zlog"
    11  )
    12  
    13  // CheckMagic looks at bit of the provided Reader to see if it looks like a
    14  // BerkeleyDB file.
    15  //
    16  // According to the libmagic database I looked at:
    17  //
    18  //	# Hash 1.85/1.86 databases store metadata in network byte order.
    19  //	# Btree 1.85/1.86 databases store the metadata in host byte order.
    20  //	# Hash and Btree 2.X and later databases store the metadata in host byte order.
    21  //
    22  // Since this process can't (and doesn't want to) know the endian-ness of the
    23  // layer's eventual host, we just look both ways for the one type we support.
    24  func CheckMagic(ctx context.Context, r io.Reader) bool {
    25  	const Hash = 0x00061561
    26  	// Most hosts are still x86, try LE first.
    27  	ord := []binary.ByteOrder{binary.LittleEndian, binary.BigEndian}
    28  	b := make([]byte, 16)
    29  
    30  	if _, err := io.ReadFull(r, b); err != nil {
    31  		zlog.Warn(ctx).Err(err).Msg("unexpected error checking magic")
    32  		return false
    33  	}
    34  	// Look at position 12 for a magic number.
    35  	for _, o := range ord {
    36  		if o.Uint32(b[12:]) == Hash {
    37  			return true
    38  		}
    39  	}
    40  	return false
    41  }