libblkid only works with root and after running as root

313 Views Asked by At

This is the weirdest thing that I've ever seen (actually, it has a nice explanation).

I created a C code to list partitions and its own types:

char *get_luks_partition(void) {
    blkid_dev dev;
    blkid_cache cache;
    blkid_dev_iterate iter;
    const char *devname = NULL;
    char *ret = NULL;
    const char *type = NULL;

    if (blkid_get_cache(&cache, NULL))
        return NULL;
    blkid_probe_all(cache);

    iter = blkid_dev_iterate_begin(cache);

    while (!blkid_dev_next(iter, &dev)) {
        devname = blkid_dev_devname(dev);
        type = blkid_get_tag_value(cache, "TYPE", devname);

        if (type)
            printf("dev: %s type: %s\n", devname, type);

        if (type && !strcmp(type, "crypto_LUKS")) {
            ret = (char *) devname;
            break;
        }
    }

    blkid_dev_iterate_end(iter);

    return ret;
}

It does not show any device/partition and type when I run as a normal user. So, I try to run as root and I finally see devices, partitions and types. And when I return to user, I can see the same output as root if I run again. See the sequence:

$ ./main 
dev: /dev/sr0 type: udf

$ sudo ./main 
dev: /dev/vda1 type: vfat
dev: /dev/vda2 type: xfs
dev: /dev/vda3 type: crypto_LUKS

$ ./main 
dev: /dev/vda1 type: vfat
dev: /dev/vda2 type: xfs
dev: /dev/vda3 type: crypto_LUKS

Does anyone know what is happening?

1

There are 1 best solutions below

0
On BEST ANSWER

From the BLKID(8) man page:

The libblkid library is used to identify block devices (disks) as to their content (e.g. filesystem type) as well as extracting additional information such as filesystem labels/volume names, unique identifiers/serial num‐ bers. A common use is to allow use of LABEL= and UUID= tags instead of hard-coding specific block device names into configuration files.

...

Note that blkid reads information directly from devices and for non-root users it returns cached unverified information.

From the LIBBLKID(3) man page:

The high-level part of the library keeps information about block devices in a cache file and is verified to still be valid before being returned to the user (if the user has read permission on the raw block device, otherwise not). The cache file also allows unprivileged users (normally anyone other than root, or those not in the "disk" group) to locate devices by label/id. The standard location of the cache file can be overridden by the envi‐ ronment variable BLKID_FILE.

So after you've run it as root, the information is cached. Afterwards that information is retrieved when you run again as non-root.