-
Notifications
You must be signed in to change notification settings - Fork 0
/
creat.go
87 lines (71 loc) · 2.23 KB
/
creat.go
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
package libpfs
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"github.com/cpssd-students/paranoid/pkg/libpfs/encryption"
"github.com/cpssd-students/paranoid/pkg/libpfs/returncodes"
)
//CreatCommand creates a new file with the name filePath in the pfs paranoidDirectory
func CreatCommand(
paranoidDirectory, filePath string, perms os.FileMode,
) (returnCode returncodes.Code, returnError error) {
log.Printf("creat called on %s in %s", filePath, paranoidDirectory)
if err := GetFileSystemLock(paranoidDirectory, ExclusiveLock); err != nil {
return returncodes.EUNEXPECTED, err
}
defer func() {
if err := UnLockFileSystem(paranoidDirectory); err != nil {
returnCode = returncodes.EUNEXPECTED
returnError = err
}
}()
namepath := getParanoidPath(paranoidDirectory, filePath)
fileType, err := getFileType(paranoidDirectory, namepath)
if err != nil {
return returncodes.EUNEXPECTED, err
}
if fileType != typeENOENT {
return returncodes.EEXIST, errors.New(filePath + " already exists")
}
uuidbytes, err := generateNewInode()
if err != nil {
return returncodes.EUNEXPECTED, err
}
uuidstring := string(uuidbytes)
err = ioutil.WriteFile(namepath, uuidbytes, 0600)
if err != nil {
return returncodes.EUNEXPECTED, errors.New("error writing name file")
}
nodeData := &inode{
Mode: perms,
Inode: uuidstring,
Count: 1}
jsonData, err := json.Marshal(nodeData)
if err != nil {
return returncodes.EUNEXPECTED, fmt.Errorf("error marshalling json: %s", err)
}
err = ioutil.WriteFile(path.Join(paranoidDirectory, "inodes", uuidstring), jsonData, 0600)
if err != nil {
return returncodes.EUNEXPECTED, fmt.Errorf("error writing inodes file: %s", err)
}
contentsFile, err := os.Create(path.Join(paranoidDirectory, "contents", uuidstring))
if err != nil {
return returncodes.EUNEXPECTED, fmt.Errorf("error creating contents file: %s", err)
}
defer contentsFile.Close()
if encryption.Encrypted {
n, err := contentsFile.WriteAt([]byte{1}, 0)
if err != nil {
return returncodes.EUNEXPECTED, fmt.Errorf("error creating contents file: %s", err)
}
if n != 1 {
return returncodes.EUNEXPECTED, errors.New("error writing first byte to contents file")
}
}
return returncodes.OK, nil
}