From a9156992f4d268c9e7e9c63c2f6d9d9d3be34860 Mon Sep 17 00:00:00 2001 From: LittleSheep Date: Fri, 18 Oct 2024 23:36:54 +0800 Subject: [PATCH] :bug: Fix bug crash caused by hash small files --- .idea/workspace.xml | 6 ++-- pkg/internal/services/analyzer.go | 55 ++++++++++++++++++------------- 2 files changed, 35 insertions(+), 26 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index ca03800..c2c7670 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -4,7 +4,7 @@ - @@ -142,7 +141,8 @@ - true diff --git a/pkg/internal/services/analyzer.go b/pkg/internal/services/analyzer.go index 6a8de2f..8603ad0 100644 --- a/pkg/internal/services/analyzer.go +++ b/pkg/internal/services/analyzer.go @@ -277,32 +277,41 @@ func HashAttachment(file models.Attachment) (hash string, err error) { hasher := sha256.New() - // Hash the first 32KB - buf := make([]byte, chunkSize) - if _, err := inFile.Read(buf); err != nil && err != io.EOF { - return "", fmt.Errorf("error reading file: %v", err) - } - hasher.Write(buf) + if chunkSize*3 <= fileInfo.Size() { + // If the total size is smaller than three chunks, then hash the whole file + buf := make([]byte, fileInfo.Size()) + if _, err := inFile.Read(buf); err != nil && err != io.EOF { + return "", fmt.Errorf("error reading whole file: %v", err) + } + hasher.Write(buf) + } else { + // Hash the first 32KB + buf := make([]byte, chunkSize) + if _, err := inFile.Read(buf); err != nil && err != io.EOF { + return "", fmt.Errorf("error reading file: %v", err) + } + hasher.Write(buf) - // Hash the middle 32KB - middleOffset := fileInfo.Size() / 2 - if _, err := inFile.Seek(middleOffset, io.SeekStart); err != nil { - return "", fmt.Errorf("error seeking to middle: %v", err) - } - if _, err := inFile.Read(buf); err != nil && err != io.EOF { - return "", fmt.Errorf("error reading middle: %v", err) - } - hasher.Write(buf) + // Hash the middle 32KB + middleOffset := fileInfo.Size() / 2 + if _, err := inFile.Seek(middleOffset, io.SeekStart); err != nil { + return "", fmt.Errorf("error seeking to middle: %v", err) + } + if _, err := inFile.Read(buf); err != nil && err != io.EOF { + return "", fmt.Errorf("error reading middle: %v", err) + } + hasher.Write(buf) - // Hash the last 32KB - endOffset := fileInfo.Size() - chunkSize - if _, err := inFile.Seek(endOffset, io.SeekStart); err != nil { - return "", fmt.Errorf("error seeking to end: %v", err) + // Hash the last 32KB + endOffset := fileInfo.Size() - chunkSize + if _, err := inFile.Seek(endOffset, io.SeekStart); err != nil { + return "", fmt.Errorf("error seeking to end: %v", err) + } + if _, err := inFile.Read(buf); err != nil && err != io.EOF { + return "", fmt.Errorf("error reading end: %v", err) + } + hasher.Write(buf) } - if _, err := inFile.Read(buf); err != nil && err != io.EOF { - return "", fmt.Errorf("error reading end: %v", err) - } - hasher.Write(buf) // Hash with the file metadata hasher.Write([]byte(fmt.Sprintf("%d", file.Size)))