Skip to content

Commit

Permalink
io: prevent seeking to position prior to offsetwrite.base
Browse files Browse the repository at this point in the history
We don't want to permit writing before the start of an OffsetWriter.

One of the goals of OffsetWriter is to restrict where data
can be written.

However, this rule can be violated by WriteAt() method of OffsetWriter
as the following code shows:

f, _ := os.Create("file.txt")
owr := io.NewOffsetWriter(f, 10)
owr.Write([]byte("world"))
owr.WriteAt([]byte("hello"), -10)

Change-Id: I6c7519fea68daefa641f25130cdd9803dc8aae22
GitHub-Last-Rev: a29d890d6f32fd5a1ecef84d012b8447b406e2e2
GitHub-Pull-Request: golang/go#60222
Reviewed-on: https://go-review.googlesource.com/c/go/+/495155
Run-TryBot: Ian Lance Taylor <[email protected]>
Reviewed-by: Ian Lance Taylor <[email protected]>
Auto-Submit: Ian Lance Taylor <[email protected]>
Run-TryBot: Ian Lance Taylor <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
Reviewed-by: Jabar Asadi <[email protected]>
Reviewed-by: Dmitri Shuralyov <[email protected]>
  • Loading branch information
Azhovan authored and gopherbot committed May 20, 2023
1 parent a0d5319 commit aeb0644
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/io/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,10 @@ func (o *OffsetWriter) Write(p []byte) (n int, err error) {
}

func (o *OffsetWriter) WriteAt(p []byte, off int64) (n int, err error) {
if off < 0 {
return 0, errOffset
}

off += o.base
return o.w.WriteAt(p, off)
}
Expand Down
20 changes: 20 additions & 0 deletions src/io/io_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,26 @@ func TestOffsetWriter_WriteAt(t *testing.T) {
}
}

func TestWriteAt_PositionPriorToBase(t *testing.T) {
tmpdir := t.TempDir()
tmpfilename := "TestOffsetWriter_WriteAt"
tmpfile, err := os.CreateTemp(tmpdir, tmpfilename)
if err != nil {
t.Fatalf("CreateTemp(%s) failed: %v", tmpfilename, err)
}
defer tmpfile.Close()

// start writing position in OffsetWriter
offset := int64(10)
// position we want to write to the tmpfile
at := int64(-1)
w := NewOffsetWriter(tmpfile, offset)
_, e := w.WriteAt([]byte("hello"), at)
if e == nil {
t.Errorf("error expected to be not nil")
}
}

func TestOffsetWriter_Write(t *testing.T) {
const content = "0123456789ABCDEF"
contentSize := len(content)
Expand Down

0 comments on commit aeb0644

Please sign in to comment.