summaryrefslogtreecommitdiff
path: root/tests/symlink_race/main.go
blob: 6fb794f0f533bcf884ee315c9b870fab89f78494 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main

import (
	"fmt"
	"os"
	"syscall"
	"time"
)

const (
	testFile    = "symlink_race.test_file"
	testFileTmp = testFile + ".tmp"
)

func renameLoop() {
	// May be left behind from an earlier run
	syscall.Unlink(testFileTmp)

	var err error
	var fd *os.File
	for {
		err = syscall.Symlink("/root/chmod_me", testFileTmp)
		if err != nil {
			fmt.Printf("Symlink() failed: %v\n", err)
			continue
		}
		err = syscall.Rename(testFileTmp, testFile)
		if err != nil {
			fmt.Printf("Rename() 1 failed: %v\n", err)
			continue
		}
		fd, err = os.Create(testFileTmp)
		if err != nil {
			fmt.Printf("Create() failed: %v\n", err)
			continue
		}
		fd.Close()
		err = syscall.Rename(testFileTmp, testFile)
		if err != nil {
			fmt.Printf("Rename() 2 failed: %v\n", err)
			continue
		}
		fmt.Printf(".")
	}
}

func chmodLoop() {
	var err error
	for {
		err = syscall.Chmod(testFile, 0777)
		if err != nil {
			fmt.Printf("Chmod() failed: %v\n", err)
		} else {
			fmt.Printf("Chmod() ok\n")
		}
		time.Sleep(100 * time.Microsecond)
	}
}

func openLoop() {
	var err error
	var f *os.File
	buf := make([]byte, 100)
	owned := []byte("owned")
	var n int
	for {
		f, err = os.OpenFile(testFile, os.O_RDWR, 0777)
		if err != nil {
			fmt.Printf("Open() failed: %v\n", err)
			continue
		}
		_, err = f.Write(owned)
		if err != nil {
			fmt.Printf("Write() failed: %v\n", err)
		}
		n, err = f.Read(buf)
		if err != nil {
			fmt.Printf("Read() failed: %v\n", err)
			continue
		}
		if n > 0 {
			fmt.Printf("Content: %q\n", string(buf[:n]))
			os.Exit(1)
		}
	}
}

func main() {
	go openLoop()
	renameLoop()
}