Skip to content

Commit

Permalink
Merge pull request #53 from ningmingxiao/dev1
Browse files Browse the repository at this point in the history
add check file type is fifo
  • Loading branch information
estesp authored Apr 28, 2023
2 parents 151b205 + e5b3831 commit 3682a42
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion fifo.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,18 @@ func OpenFifo(ctx context.Context, fn string, flag int, perm os.FileMode) (io.Re
}

func openFifo(ctx context.Context, fn string, flag int, perm os.FileMode) (*fifo, error) {
if _, err := os.Stat(fn); err != nil {
if file, err := os.Stat(fn); err != nil {
if os.IsNotExist(err) && flag&syscall.O_CREAT != 0 {
if err := syscall.Mkfifo(fn, uint32(perm&os.ModePerm)); err != nil && !os.IsExist(err) {
return nil, fmt.Errorf("error creating fifo %v: %w", fn, err)
}
} else {
return nil, err
}
} else {
if file.Mode()&os.ModeNamedPipe == 0 {
return nil, fmt.Errorf("file %s is not fifo", fn)
}
}

block := flag&syscall.O_NONBLOCK == 0 || flag&syscall.O_RDWR != 0
Expand Down
13 changes: 13 additions & 0 deletions fifo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package fifo

import (
"context"
"fmt"
"io"
"os"
"path/filepath"
Expand All @@ -31,6 +32,18 @@ import (
"github.com/stretchr/testify/assert"
)

func TestOpenNonNamedPipe(t *testing.T) {
tmpdir := t.TempDir()

normalFile := filepath.Join(tmpdir, "empty")
f, err := os.Create(normalFile)
assert.NoError(t, err)
f.Close()

_, err = OpenFifo(context.TODO(), normalFile, syscall.O_RDONLY|syscall.O_NONBLOCK, 0600)
assert.ErrorContains(t, err, fmt.Sprintf("file %v is not fifo", normalFile))
}

func TestFifoCancel(t *testing.T) {
tmpdir, err := os.MkdirTemp("", "fifos")
assert.NoError(t, err)
Expand Down

0 comments on commit 3682a42

Please sign in to comment.