Skip to content

Commit

Permalink
Initialize
Browse files Browse the repository at this point in the history
  • Loading branch information
trytriangles committed Sep 22, 2021
0 parents commit a7fdc8b
Show file tree
Hide file tree
Showing 8 changed files with 345 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
test/breakdance.avi
test/dummy.bin
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Ryan Plant ([email protected])

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
76 changes: 76 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# oshash (Open Subtitles Hash)

## Description

This package provides both a command-line utility and a Go library for computing Open Subtitles-format hashes for files and arbitrary data.

The Open Subtitles hash is an 8-byte identifying value produced from the input data's size and from 64 kibibytes (65536 bytes) at the beginning and end of the data, and made by simply interpreting chunks of it (which may overlap) as integers and summing them. It goes without saying that this is not a substitute for a SHA256 or Keccak hash of the full data. Instead it's a very compact and very cheap-to-produce identifier useful for fast deduplication and match-narrowing.

## CLI usage

### Options

- `-x`: show hexadecimal values (default).
- `-b`: show binary values.
- `-d`: show decimal values (64-bit integers).
- `-f`: show filename with output.
- `-pipe`: read lines from stdin and write results to stdout.
- `-sep`: specify string to use to separate fields in tabular output (default: tab).

### Example

```
> oshash parrots.jpg
f44f78d5e4a8fbee
> oshash -d parrots.jpg
17604422328474205166
> cat filesnames.txt | oshash -pipe
f44f78d5e4a8fbee
bf01ea2bi00a21f7
a189811aabf1ce20
> cat filesnames.txt | oshash -pipe -f -x -d
images/parrot.jpg f44f78d5e4a8fbee 17604422328474205166
images/toucan.jpg bf01ea2bi00a21f7 10242892102200212726
images/lorikeet.jpg a189811aabf1ce20 18827272012277274944
> oshash -f -sep "," "parrot.jpg" "toucan.jpg"
parrot.jpg,f44f78d5e4a8fbee
toucan.jpg,bf01ea2bi00a21f7
```

## Library usage

- `FromFile(*os.File) (uint64, err)`
- `FromFilepath(string) (uint64, err)`
- `FromBytes([]byte) (uint64, err)`

To convert the uint64 values to a hexdecimal string, use `strconv.FormatUint(oshash_value, 16)`.

## Credits

Test-suite parrot image by [edmondlafoto](https://pixabay.com/users/edmondlafoto-7913128/).

## License (MIT)

©️ 2020 [Ryan Plant](mailto:[email protected])

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.
76 changes: 76 additions & 0 deletions cmd/oshash/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package main

import (
"bufio"
"flag"
"fmt"
"os"
"strconv"
"strings"

"github.com/ryantriangles/oshash"
)

var binFlag = flag.Bool("b", false, "display binary values")
var decFlag = flag.Bool("d", false, "display decimal values")
var hexFlag = flag.Bool("x", false, "display hexadecimal values")
var pipeFlag = flag.Bool("pipe", false, "pipe mode")
var showFilenames = flag.Bool("f", false, "show filenames with output")
var sep = flag.String("sep", "\t", "separator string for tabular output")

func init() {
flag.Parse()

// If no flags are used, set the hexadecimal flag to true, making
// hexadecimal representation the default.
if !*binFlag && !*decFlag {
*hexFlag = true
}
}

func handleFilename(filename string) {
h, err := oshash.FromFilepath(filename)
if err == oshash.ErrDataTooSmall {
fmt.Println("Too small")
return
}
if err != nil {
panic(err)
}
str := []string{}
if *showFilenames {
str = append(str, filename)
}
if *hexFlag {
str = append(str, strconv.FormatUint(h, 16))
}
if *binFlag {
str = append(str, strconv.FormatUint(h, 2))
}
if *decFlag {
str = append(str, strconv.FormatUint(h, 10))
}
fmt.Println(strings.Join(str, *sep))
}

func stdinScanner() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
filename := scanner.Text()
handleFilename(filename)
}

if err := scanner.Err(); err != nil {
panic(err)
}
}

func main() {
if *pipeFlag {
stdinScanner()
} else {
for _, arg := range flag.Args() {
handleFilename(arg)
}
}
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/ryantriangles/oshash

go 1.17
93 changes: 93 additions & 0 deletions oshash.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Package oshash provides a library and a command-line interface tool for
// compputing OpenSubtitles hash values for files and arbitrary data.
//
// The OpenSubtitles hash format is defined as a 64-bit integer value, made from
// the size of the input data in bytes, a checksum of the first 64 kibibytes in
// the data (the head), and a checksum of the last 64 kibibytes in the data
// (the tail).
//
// A notable limitation is that a piece of data must be at least 64 kibibytes
// long to have a valid OpenSubtitles hash. Supplying a file or []byte of less
// than 64 kibibytes will result in the error oshash.ErrDataTooSmall.
//
// All hash values returned by these functions are uint64s, but they can be
// trivially converted to hexadecimal strings with
// strconv.FormatUint(hash_value, 16).
package oshash

import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"os"
)

const ChunkSize = 65536

var ErrDataTooSmall = errors.New("data is less than 65536 bytes")
var ErrReadTooFewBytes = fmt.Errorf("failed to read %v bytes", ChunkSize)

// FromFile computes the oshash for an *os.File.
func FromFile(file *os.File) (uint64, error) {
fi, err := file.Stat()
if err != nil {
return 0, err
}
if fi.Size() < ChunkSize {
return 0, ErrDataTooSmall
}
buf := make([]byte, ChunkSize*2)
if err = readChunk(file, 0, buf[:ChunkSize]); err != nil {
return 0, err
}
if err = readChunk(file, fi.Size()-ChunkSize, buf[ChunkSize:]); err != nil {
return 0, err
}
return computeOsHash(buf, uint64(fi.Size()))
}

// FromFilepath computes the oshash of the specified file.
func FromFilepath(filename string) (hash uint64, err error) {
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
return FromFile(f)
}

// FromFilepath computes the oshash of some given data.
func FromBytes(b []byte) (hash uint64, err error) {
if len(b) < ChunkSize {
return 0, ErrDataTooSmall
}
buf := make([]byte, ChunkSize*2)
copy(buf[:ChunkSize], b[0:ChunkSize])
copy(buf[ChunkSize:], b[(len(b)-ChunkSize):])
return computeOsHash(buf, uint64(len(b)))
}

// readChunk reads file into buf starting at offset, and returns an error if it
// did not read at least 64 kibibytes.
func readChunk(file *os.File, offset int64, buf []byte) (err error) {
n, err := file.ReadAt(buf, offset)
if err == nil && n != ChunkSize {
return ErrReadTooFewBytes
}
return err
}

// computeOsHash computes a final oshash value from buf, a bytearray of the
// sampled data.
func computeOsHash(buf []byte, filesize uint64) (hash uint64, err error) {
var nums [(ChunkSize * 2) / 8]uint64
reader := bytes.NewReader(buf)
if err = binary.Read(reader, binary.LittleEndian, &nums); err != nil {
return 0, err
}
for _, num := range nums {
hash += num
}
return hash + filesize, nil
}
74 changes: 74 additions & 0 deletions oshash_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package oshash

import (
"os"
"testing"
)

func fromFileTester(filename string, expected uint64, t *testing.T) {
f, err := os.Open(filename)
if err != nil {
t.Error(err)
}
h, err := FromFile(f)
if err != nil {
t.Error(err)
}
if h != expected {
t.Errorf("Expected %v, got %v", expected, h)
}
}
func TestFromFile(t *testing.T) {
fromFileTester("test/parrots.jpg", uint64(17604422328474205166), t)

// Tests for the OpenSubtitles reference files. These files are not
// included in the GitHub repository due to their large filesize, and so
// are commented out here, but you can download the files (and extract
// the 4 GB dummy.bin file from its RAR archive) for more thorough testing.
//
// http://www.opensubtitles.org/addons/avi/breakdance.avi
// fromFileTester("test/breakdance.avi", uint64(10242414353417707026), t)
//
// http://www.opensubtitles.org/addons/avi/dummy.rar
// fromFileTester("test/dummy.bin", uint64(7059239720196713467), t)
}

func TestFromFilepath(t *testing.T) {
expected := uint64(17604422328474205166)
h, err := FromFilepath("test/parrots.jpg")
if err != nil {
t.Error(err)
}
if h != expected {
t.Errorf("Expected %v, got %v", expected, h)
}
}

func TestFromBytes(t *testing.T) {
f, err := os.Open("test/parrots.jpg")
if err != nil {
t.Error(err)
}
info, err := os.Stat("test/parrots.jpg")
if err != nil {
t.Error(err)
}
buf := make([]byte, info.Size())
f.Read(buf)
h, err := FromBytes(buf)
if err != nil {
t.Error(err)
}
expected := uint64(17604422328474205166)
if h != expected {
t.Errorf("Expected %v, got %v", expected, h)
}
}

func TestSmallDataErrors(t *testing.T) {
buf := []byte("just a bit of data")
_, err := FromBytes(buf)
if err != ErrDataTooSmall {
t.Error(err)
}
}
Binary file added test/parrots.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit a7fdc8b

Please sign in to comment.