### Execute Direct Volume API Calls in Go Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Provides examples for querying volume metadata and file system information using low-level Windows API wrappers. ```go package main import ( "fmt" "log" "github.com/gentlemanautomaton/volmgmt/volumeapi" ) func main() { // Get volume name for mount point volumeName, err := volumeapi.GetVolumeNameForVolumeMountPoint(`C:\`) if err != nil { log.Fatalf("Failed to get volume name: %v", err) } fmt.Printf("Volume GUID Path: %s\n", volumeName) // Get all paths for a volume name paths, err := volumeapi.GetVolumePathNamesForVolumeName(volumeName) if err != nil { log.Fatalf("Failed to get paths: %v", err) } fmt.Printf("Mount Points: %v\n", paths) // Get volume handle for direct operations handle, err := volumeapi.Handle(`\\.\C:`, 0x80000000, 3) // GENERIC_READ, FILE_SHARE_READ|WRITE if err != nil { log.Fatalf("Failed to get handle: %v", err) } defer volumeapi.CloseHandle(handle) // Get volume information by handle label, serialNum, maxCompLen, flags, fsName, err := volumeapi.GetVolumeInformationByHandle(handle) if err != nil { log.Fatalf("Failed to get volume info: %v", err) } fmt.Printf("Label: %s\n", label) fmt.Printf("Serial Number: %d\n", serialNum) fmt.Printf("Max Component Length: %d\n", maxCompLen) fmt.Printf("Flags: 0x%X\n", flags) fmt.Printf("File System: %s\n", fsName) } ``` -------------------------------- ### Build and Manage USN Record Caches in Go Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Shows how to build an in-memory cache from a journal query and perform manual cache operations for path resolution. ```go package main import ( "context" "fmt" "log" "github.com/gentlemanautomaton/volmgmt/usn" "github.com/gentlemanautomaton/volmgmt/usnfilter" "github.com/gentlemanautomaton/volmgmt/volume" ) func main() { ctx := context.Background() vol, err := volume.New(`\\.\C:`) if err != nil { log.Fatalf("Failed to open volume: %v", err) } defer vol.Close() journal := vol.Journal() defer journal.Close() data, err := journal.Query() if err != nil { log.Fatalf("Failed to query journal: %v", err) } // Build cache with directory records for path resolution cache, err := journal.Cache(ctx, usnfilter.IsDir, usn.Min, data.NextUSN) if err != nil { log.Fatalf("Failed to build cache: %v", err) } fmt.Printf("Cache size: %d directory records\n", cache.Size()) // Get all cached records with resolved paths records := cache.Records() for i, record := range records { if i >= 10 { fmt.Printf("... and %d more\n", len(records)-10) break } fmt.Printf("Path: %s\n", record.Path) } // Manual cache operations newCache := usn.NewCache() // Add record to cache newCache.Set(usn.Record{ FileName: "example", }) // Look up by file reference number // record, found := newCache.Get(fileRefID) // Use cache as filer for path resolution filer := newCache.Filer _ = filer // Use with cursor or journal operations } ``` -------------------------------- ### Monitor USN Journal Changes in Go Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Sets up a real-time monitor for file system changes using listener channels. Requires handling of OS signals for graceful shutdown. ```go package main import ( "fmt" "log" "os" "os/signal" "syscall" "time" "github.com/gentlemanautomaton/volmgmt/usn" ) func main() { monitor, err := usn.NewMonitor(`\\.\C:`) if err != nil { log.Fatalf("Failed to create monitor: %v", err) } defer monitor.Close() // Create listener channel with buffer size listener := monitor.Listen(1000) // Start monitoring from current position // Parameters: start USN, polling interval, reason mask, processor, filter, filer errCh := monitor.Run( 0, // Start from beginning (or use specific USN) time.Second, // Poll every second usn.ReasonAny, // All change types nil, // No processor nil, // No filter nil, // No path resolver ) // Handle graceful shutdown sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) fmt.Println("Monitoring file system changes (Ctrl+C to stop)...") go func() { for record := range listener { fmt.Printf("[%s] %s - %s\n", record.TimeStamp.Format("15:04:05"), record.FileName, record.Reason.Join("|", usn.ReasonFormatShort)) } }() select { case <-sigCh: fmt.Println("\nShutting down...") monitor.Stop() case err := <-errCh: if err != nil { log.Printf("Monitor error: %v", err) } } } ``` -------------------------------- ### Parse and Format USN Reason Codes Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Demonstrates parsing reason code strings, formatting constants, and checking for specific change types within a reason mask. ```go package main import ( "fmt" "log" "github.com/gentlemanautomaton/volmgmt/usn" ) func main() { // Parse reason codes from string reason, err := usn.ParseReason("create,delete,move") if err != nil { log.Fatalf("Failed to parse reason: %v", err) } fmt.Printf("Parsed reason mask: 0x%X\n", reason) // Available reason codes reasons := []usn.Reason{ usn.ReasonDataOverwrite, // File data was overwritten usn.ReasonDataExtend, // File data was extended usn.ReasonDataTruncation, // File data was truncated usn.ReasonFileCreate, // File was created usn.ReasonFileDelete, // File was deleted usn.ReasonRenameOldName, // File renamed (old name) usn.ReasonRenameNewName, // File renamed (new name) usn.ReasonRename, // File renamed (combined) usn.ReasonSecurityChange, // Security descriptor changed usn.ReasonBasicInfoChange, // Basic info changed usn.ReasonHardLinkChange, // Hard link changed usn.ReasonCompressionChange, // Compression changed usn.ReasonEncryptionChange, // Encryption changed usn.ReasonReparsePointChange, // Reparse point changed usn.ReasonClose, // File handle closed usn.ReasonAny, // Match any reason } for _, r := range reasons { // Format as constant name fmt.Printf("Constant: %s\n", r.String()) // Format as short name fmt.Printf("Short: %s\n", r.Join("|", usn.ReasonFormatShort)) // Format as basic name fmt.Printf("Basic: %s\n\n", r.Join("|", usn.ReasonFormatBasic)) } // Check if reason matches specific codes combined := usn.ReasonFileCreate | usn.ReasonFileDelete fmt.Printf("Has FileCreate: %t\n", combined.Match(usn.ReasonFileCreate)) fmt.Printf("Is Rename: %t\n", combined.Rename()) } ``` -------------------------------- ### Create and Combine USN Filters in Go Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Demonstrates how to define custom filter functions for USN records and combine them using boolean logic. ```go package main import ( "fmt" "regexp" "strings" "github.com/gentlemanautomaton/volmgmt/fileattr" "github.com/gentlemanautomaton/volmgmt/usn" "github.com/gentlemanautomaton/volmgmt/usnfilter" ) func main() { // Built-in filter: directories only dirFilter := usnfilter.IsDir // Custom filter: specific file extension txtFilter := func(r usn.Record) bool { return strings.HasSuffix(strings.ToLower(r.FileName), ".txt") } // Custom filter: exclude hidden files visibleFilter := func(r usn.Record) bool { return !r.FileAttributes.Match(fileattr.Hidden) } // Custom filter: regex pattern matching pattern := regexp.MustCompile(`(?i)\.log$`) regexFilter := func(r usn.Record) bool { return pattern.MatchString(r.FileName) } // Combine filters with AND logic combinedFilter := func(r usn.Record) bool { return visibleFilter(r) && txtFilter(r) } // Example records for testing records := []usn.Record{ {FileName: "document.txt", FileAttributes: 0}, {FileName: "hidden.txt", FileAttributes: fileattr.Hidden}, {FileName: "folder", FileAttributes: fileattr.Directory}, {FileName: "app.log", FileAttributes: 0}, } for _, r := range records { fmt.Printf("File: %-15s Dir: %-5t Txt: %-5t Visible: %-5t Log: %-5t Combined: %t\n", r.FileName, dirFilter(r), txtFilter(r), visibleFilter(r), regexFilter(r), combinedFilter(r)) } } ``` -------------------------------- ### Create a USN Journal Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Initializes a new USN change journal on a volume, optionally specifying custom size and allocation delta parameters. ```go package main import ( "fmt" "log" "github.com/gentlemanautomaton/volmgmt/usn" ) func main() { journal, err := usn.NewJournal(`\\.\C:`) if err != nil { log.Fatalf("Failed to open journal: %v", err) } defer journal.Close() // Create journal with default parameters (pass 0, 0) err = journal.Create(0, 0) if err != nil { log.Fatalf("Failed to create journal: %v", err) } // Or create with custom parameters // maxSize: maximum size of journal in bytes // allocDelta: allocation delta in bytes err = journal.Create(32*1024*1024, 4*1024*1024) // 32MB max, 4MB delta if err != nil { log.Fatalf("Failed to create journal with custom params: %v", err) } fmt.Println("USN Journal created successfully") } ``` -------------------------------- ### Open and Query Windows Volume Information Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Opens a volume handle using a path string and retrieves various metadata, including labels, device numbers, and hardware identifiers. ```go package main import ( "fmt" "log" "github.com/gentlemanautomaton/volmgmt/volume" ) func main() { // Open volume by drive letter vol, err := volume.New(`\\.\C:`) if err != nil { log.Fatalf("Failed to open volume: %v", err) } defer vol.Close() // Alternative formats: // vol, _ := volume.New(`\\?\Volume{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\`) // vol, _ := volume.New(`\\.\PhysicalDrive0`) // Get volume label label, err := vol.Label() if err != nil { log.Printf("Failed to get label: %v", err) } fmt.Printf("Volume Label: %s\n", label) // Get volume GUID name name, err := vol.Name() if err != nil { log.Printf("Failed to get name: %v", err) } fmt.Printf("Volume Name: %s\n", name) // Get device information fmt.Printf("Device Number: %d\n", vol.DeviceNumber()) fmt.Printf("Partition Number: %d\n", vol.PartitionNumber()) fmt.Printf("Device Type: %d\n", vol.DeviceType()) // Get hardware information fmt.Printf("Bus Type: %d\n", vol.BusType()) fmt.Printf("Removable Media: %t\n", vol.RemovableMedia()) fmt.Printf("Vendor ID: %s\n", vol.VendorID()) fmt.Printf("Product ID: %s\n", vol.ProductID()) fmt.Printf("Serial Number: %s\n", vol.SerialNumber()) // Get mount points paths, err := vol.Paths() if err != nil { log.Printf("Failed to get paths: %v", err) } fmt.Printf("Mount Points: %v\n", paths) // Get NT device path devicePath, err := vol.DevicePath() if err != nil { log.Printf("Failed to get device path: %v", err) } fmt.Printf("NT Device Path: %s\n", devicePath) } ``` -------------------------------- ### Enumerate MFT Records in Go Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Accesses the NTFS Master File Table to iterate through file records within a specified USN range. Requires a volume handle and a buffer for record processing. ```go package main import ( "context" "fmt" "io" "log" "github.com/gentlemanautomaton/volmgmt/usn" "github.com/gentlemanautomaton/volmgmt/volume" ) func main() { ctx := context.Background() vol, err := volume.New(`\\.\C:`) if err != nil { log.Fatalf("Failed to open volume: %v", err) } defer vol.Close() mft := vol.MFT() defer mft.Close() // Create filter (nil for all records) var filter usn.Filter = nil // Enumerate all records iter, err := mft.Enumerate(filter, usn.Min, usn.Max) if err != nil { log.Fatalf("Failed to create enumerator: %v", err) } defer iter.Close() buffer := make([]byte, 65536) var records []usn.Record count := 0 for { if ctx.Err() != nil { break } records, err = iter.Next(buffer, records[:0]) if err != nil { if err == io.EOF { break } log.Fatalf("Failed to enumerate: %v", err) } for _, record := range records { fmt.Printf("FRN: %s, Name: %s, Attrs: %s\n", record.FileReferenceNumber.String(), record.FileName, record.FileAttributes.String()) count++ } } fmt.Printf("\nEnumerated %d MFT records\n", count) } ``` -------------------------------- ### Lookup File by Reference Number in Go Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Retrieves a specific file record from the MFT using its unique file reference number. The root directory typically uses reference number 5. ```go package main import ( "fmt" "log" "github.com/gentlemanautomaton/volmgmt/fileref" "github.com/gentlemanautomaton/volmgmt/usn" ) func main() { mft, err := usn.NewMFT(`\\.\C:`) if err != nil { log.Fatalf("Failed to open MFT: %v", err) } defer mft.Close() // Create file reference ID (example: root directory is typically 5) fileID := fileref.New64(5) record, err := mft.File(fileID) if err != nil { log.Fatalf("Failed to find file: %v", err) } fmt.Printf("File Reference: %s\n", record.FileReferenceNumber.String()) fmt.Printf("Parent Reference: %s\n", record.ParentFileReferenceNumber.String()) fmt.Printf("File Name: %s\n", record.FileName) fmt.Printf("USN: %d\n", record.USN) fmt.Printf("Timestamp: %s\n", record.TimeStamp) fmt.Printf("Attributes: %s\n", record.FileAttributes.String()) } ``` -------------------------------- ### Scan and Filter Master File Table Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Use mftscan to query the Master File Table for files based on patterns, size, and modification time. ```bash mftscan \\.\C: ``` ```bash mftscan -include "\.exe$" \\.\C: mftscan -exclude "Windows" \\.\C: ``` ```bash mftscan -bigger 1MB \\.\C: mftscan -smaller 100KB \\.\C: ``` ```bash mftscan -after "2024-01-01" \\.\C: ``` ```bash mftscan -list -include "\.log$" \\.\C: ``` ```bash mftscan -v -p \\.\C: ``` -------------------------------- ### Query USN Journal Metadata Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Retrieves journal ID, USN boundaries, and version support information from a volume's USN journal. ```go package main import ( "fmt" "log" "github.com/gentlemanautomaton/volmgmt/usn" ) func main() { // Create journal accessor directly journal, err := usn.NewJournal(`\\.\C:`) if err != nil { log.Fatalf("Failed to open journal: %v", err) } defer journal.Close() // Query journal information data, err := journal.Query() if err != nil { log.Fatalf("Failed to query journal: %v", err) } fmt.Printf("Journal ID: %d\n", data.JournalID) fmt.Printf("First USN: %d\n", data.FirstUSN) fmt.Printf("Next USN: %d\n", data.NextUSN) fmt.Printf("Lowest Valid USN: %d\n", data.LowestValidUSN) fmt.Printf("Max USN: %d\n", data.MaxUSN) fmt.Printf("Maximum Size: %d bytes\n", data.MaximumSize) fmt.Printf("Allocation Delta: %d bytes\n", data.AllocationDelta) fmt.Printf("Supported Versions: %d-%d\n", data.MinSupportedMajorVersion, data.MaxSupportedMajorVersion) } ``` -------------------------------- ### Read USN Journal Records with Cursor Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Iterates through USN journal records using a cursor, supporting directory caching for path resolution and custom filtering. ```go package main import ( "context" "fmt" "io" "log" "strings" "github.com/gentlemanautomaton/volmgmt/usn" "github.com/gentlemanautomaton/volmgmt/usnfilter" "github.com/gentlemanautomaton/volmgmt/volume" ) func main() { ctx := context.Background() vol, err := volume.New(`\\.\C:`) if err != nil { log.Fatalf("Failed to open volume: %v", err) } defer vol.Close() journal := vol.Journal() defer journal.Close() data, err := journal.Query() if err != nil { log.Fatalf("Failed to query journal: %v", err) } // Build cache of directories for path resolution cache, err := journal.Cache(ctx, usnfilter.IsDir, 0, data.FirstUSN) if err != nil { log.Fatalf("Failed to build cache: %v", err) } fmt.Printf("Cached %d directories\n", cache.Size()) // Processor updates cache with new directory records cacheUpdater := func(record usn.Record) { if usnfilter.IsDir(record) { cache.Set(record) } } // Create filter for specific file types filter := func(r usn.Record) bool { return strings.HasSuffix(strings.ToLower(r.FileName), ".txt") } // Create cursor with: // - processor: updates cache with directory changes // - reasonMask: filter by change types (ReasonAny for all) // - filter: custom record filter // - filer: path resolver using cache cursor, err := journal.Cursor(cacheUpdater, usn.ReasonAny, filter, cache.Filer) if err != nil { log.Fatalf("Failed to create cursor: %v", err) } defer cursor.Close() buffer := make([]byte, 65536) count := 0 for { records, err := cursor.Next(buffer) if err != nil { if err == io.EOF { break } log.Fatalf("Failed to read records: %v", err) } for _, record := range records { fmt.Printf("[%s] %s - %s\n", record.TimeStamp.Format("2006-01-02 15:04:05"), record.Path, record.Reason.Join("|", usn.ReasonFormatShort)) count++ } } total, filtered := cursor.Stats() fmt.Printf("\nProcessed %d total records, matched %d\n", total.Records, filtered.Records) } ``` -------------------------------- ### Scan and Filter USN Journal Source: https://context7.com/gentlemanautomaton/volmgmt/llms.txt Use journalscan to query the Windows USN journal with various filters for change types, filenames, and time ranges. ```bash journalscan \\.\C: ``` ```bash journalscan -t create,delete \\.\C: ``` ```bash journalscan -include "\.txt$" \\.\C: journalscan -exclude "\.tmp$" \\.\C: ``` ```bash journalscan -after "2024-01-01" -before "2024-12-31" \\.\C: ``` ```bash journalscan -t create -include "\.doc" -after "2024-06-01" \\.\C: ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.