#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/fsuid.h>

static int get_fsuid_now(void)
{
    /*
       setfsuid(-1) fails, but returns the current fsuid.
       This is the usual Linux trick for reading fsuid.
    */
    return setfsuid((uid_t)-1);
}

static void show_ids(void)
{
    FILE *f = fopen("/proc/self/status", "r");
    char line[256];

    if (!f) {
        perror("fopen");
        exit(1);
    }

    while (fgets(line, sizeof line, f)) {
        if (strncmp(line, "Uid:", 4) == 0 ||
            strncmp(line, "Gid:", 4) == 0) {
            fputs(line, stdout);
        }
    }

    fclose(f);
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s <new-fsuid>\n", argv[0]);
        return 1;
    }

    uid_t target = atoi(argv[1]);

    printf("Before:\n");
    show_ids();
    printf("current fsuid = %d\n\n", get_fsuid_now());

    int old = setfsuid(target);
    int now = get_fsuid_now();

    printf("setfsuid(%d) returned old fsuid = %d\n", target, old);

    printf("After:\n");
    show_ids();
    printf("current fsuid = %d\n", now);

    if (now != target) {
        printf("\nfsuid did NOT change. You probably lack CAP_SETUID, "
               "or target UID is not allowed.\n");
    }

    return 0;
}
