Monday | 15 APR 2024
[ previous ]
[ next ]

FUSE Tutorial - 03 getattr - The First Avenger

Title:
Date: 2023-02-02
Tags:  

In the last chapter we ended with doing a ls -l on the mounted folder and seeing some question marks. This is because there are no attributes currently being set and so there is nothing for linux to display.

The next step is to fix this, we need to make sure that our mount point gets the correct sizing and permissions when something gets mounted to it. We're going to do this by hooking into the getattr call. We will write our own function that will handle this call and based on what is getting requested, we'll handle it differently.

Things will become clearer once we begin!

Let's add a getattr function:

int sfs_getattr(const char *path, struct stat *st)
{
    printf("Calling getattr on: %s\n",path);

    if (!strcmp(path, "/")) {
        st->st_mode = S_IFDIR | 0755;
        st->st_nlink = 2;
        st->st_size = 4096;

    } else {
        st->st_mode = S_IFREG | 0644;
        st->st_nlink = 2;
        st->st_size = 4096;
    }

    st->st_uid = getuid();
    st->st_gid = getgid();

    return 0;
}

The key to note here is that given a path, we need to decide what to do with it. If the path is supposed to be a directory, then we need to set the mode properly. If the path is a file then we will set the mode to S_IFREG.

We also set the number of links to 2, for a directory this is because all directories will contain a minimum of 2 links, one to the current directory and one to the above. I'm curious why the regular file also has 2 links.

This function is also where we set the user id and group id of our pretend file system.

Now we need to update the list of ops that we are overwriting.

static struct fuse_operations sfs_ops = {
    .getattr = sfs_getattr,
};

Now we can compile and run our program:

gcc -lfuse -D_FILE_OFFSET_BITS=64 sfs.c -o sfs
./sfs -f db.sqlite dir

Now we can do ls -l dir and then see the following output:

ls -l
drwxr-xr-x 2 nivethan nivethan 4096 Dec 31  1969 dir

We would also see in our fuse program the following output:

Lighting FUSE...
Getting attributes for: /

If you see multiple lines of the getting attributes, it means that your shell might be doing more than a single query. When using fish, due to the autocomplete and suggestions I get far more calls to getattr. Very fun and cool to see.

The getattr function is going to be critical for getting our sqlite file to behave as a file system however it's not clear yet how it's going to be important. We need to write our readdir function first and then we can come back to our getattr function.

Onwards and forwards!