Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I programmatically get all snapshots of an APFS volume?

Tags:

macos

apfs

This shell command lists all APFS snaphots of a volume called TM-Backup:

diskutil apfs listSnapshots /Volumes/TM-Backup

How do I achieve the same in code, without invoking the diskutil command?

like image 849
Thomas Tempelmann Avatar asked Dec 06 '25 03:12

Thomas Tempelmann


1 Answers

try this (via pwn20wnstuff / Osiris:)

#import <sys/snapshot.h>

typedef struct val_attrs {
    uint32_t          length;
    attribute_set_t   returned;
    attrreference_t   name_info;
} val_attrs_t;

int snapshot_list(const char *vol)
{
    struct attrlist attr_list = { 0 };
    int total=0;
    
    attr_list.commonattr = ATTR_BULK_REQUIRED;
    
    char *buf = (char*)calloc(2048, sizeof(char));
    int retcount;
    int fd = open(vol, O_RDONLY, 0);
    while ((retcount = fs_snapshot_list(fd, &attr_list, buf, 2048, 0))>0) {
        total += retcount;
        char *bufref = buf;
        
        for (int i=0; i<retcount; i++) {
            val_attrs_t *entry = (val_attrs_t *)bufref;
            if (entry->returned.commonattr & ATTR_CMN_NAME) {
                printf("%s\n", (char*)(&entry->name_info) + entry->name_info.attr_dataoffset);
            }
            bufref += entry->length;
        }
    }
    free(buf);
    close(fd);
    
    if (retcount < 0) {
        perror("fs_snapshot_list");
        return -1;
    }
    
    return total;
}
like image 185
Karsten Avatar answered Dec 08 '25 18:12

Karsten