-
Notifications
You must be signed in to change notification settings - Fork 0
/
creatcmd.go
88 lines (73 loc) · 2.31 KB
/
creatcmd.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
88
package commands
import (
"encoding/json"
"errors"
"fmt"
"github.com/cpssd/paranoid/libpfs/encryption"
"github.com/cpssd/paranoid/libpfs/returncodes"
"io/ioutil"
"os"
"path"
)
//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.Info("creat command called")
Log.Verbose("creat : paranoidDirectory = " + paranoidDirectory)
err := GetFileSystemLock(paranoidDirectory, ExclusiveLock)
if err != nil {
return returncodes.EUNEXPECTED, err
}
defer func() {
err := UnLockFileSystem(paranoidDirectory)
if 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")
}
Log.Verbose("creat : creating file " + filePath)
uuidbytes, err := generateNewInode()
if err != nil {
return returncodes.EUNEXPECTED, err
}
uuidstring := string(uuidbytes)
Log.Verbose("creat : uuid = " + uuidstring)
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
}