-
Notifications
You must be signed in to change notification settings - Fork 202
/
file.go
201 lines (164 loc) · 4.52 KB
/
file.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package core
import (
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/pelletier/go-toml"
)
// ArgCreateFileArgument will hold the arguments for a new file creation method call
type ArgCreateFileArgument struct {
Directory string
Prefix string
FileExtension string
}
// OpenFile method opens the file from given path - does not close the file
func OpenFile(relativePath string) (*os.File, error) {
path, err := filepath.Abs(relativePath)
if err != nil {
log.Warn("cannot create absolute path for the provided file", "error", err.Error())
return nil, err
}
f, err := os.Open(filepath.Clean(path))
if err != nil {
return nil, err
}
return f, nil
}
// LoadTomlFile method to open and decode toml file
func LoadTomlFile(dest interface{}, relativePath string) error {
f, err := OpenFile(relativePath)
if err != nil {
return err
}
defer func() {
err = f.Close()
if err != nil {
log.Warn("cannot close file", "error", err.Error())
}
}()
return toml.NewDecoder(f).Decode(dest)
}
// LoadTomlFileToMap opens and decodes a toml file as a map[string]interface{}
func LoadTomlFileToMap(relativePath string) (map[string]interface{}, error) {
f, err := OpenFile(relativePath)
if err != nil {
return nil, err
}
fileinfo, err := f.Stat()
if err != nil {
log.Error("cannot stat file", "error", err.Error())
return nil, err
}
filesize := fileinfo.Size()
buffer := make([]byte, filesize)
_, err = f.Read(buffer)
if err != nil {
log.Error("cannot read from file", "error", err.Error())
return nil, err
}
defer func() {
err = f.Close()
if err != nil {
log.Error("cannot close file", "error", err.Error())
}
}()
loadedTree, err := toml.Load(string(buffer))
if err != nil {
log.Error("cannot interpret file contents as toml", "error", err.Error())
return nil, err
}
loadedMap := loadedTree.ToMap()
return loadedMap, nil
}
// LoadJsonFile method to open and decode json file
func LoadJsonFile(dest interface{}, relativePath string) error {
f, err := OpenFile(relativePath)
if err != nil {
return err
}
defer func() {
err = f.Close()
if err != nil {
log.Warn("cannot close file", "error", err.Error())
}
}()
return json.NewDecoder(f).Decode(dest)
}
// CreateFile opens or creates a file relative to the default path
func CreateFile(arg ArgCreateFileArgument) (*os.File, error) {
absPath, err := filepath.Abs(arg.Directory)
if err != nil {
return nil, err
}
err = os.MkdirAll(absPath, os.ModePerm)
if err != nil {
return nil, err
}
fileName := time.Now().Format("2006-01-02T15-04-05")
fileName = strings.Replace(fileName, "T", "-", 1)
if arg.Prefix != "" {
fileName = arg.Prefix + "-" + fileName
}
return os.OpenFile(
filepath.Join(absPath, fileName+"."+arg.FileExtension),
os.O_CREATE|os.O_APPEND|os.O_WRONLY,
FileModeUserReadWrite)
}
// LoadSkPkFromPemFile loads the secret key and existing public key bytes stored in the file
func LoadSkPkFromPemFile(relativePath string, skIndex int) ([]byte, string, error) {
if skIndex < 0 {
return nil, "", ErrInvalidIndex
}
file, err := OpenFile(relativePath)
if err != nil {
return nil, "", err
}
defer func() {
cerr := file.Close()
log.LogIfError(cerr)
}()
buff, err := ioutil.ReadAll(file)
if err != nil {
return nil, "", fmt.Errorf("%w while reading %s file", err, relativePath)
}
if len(buff) == 0 {
return nil, "", fmt.Errorf("%w while reading %s file", ErrEmptyFile, relativePath)
}
var blkRecovered *pem.Block
for i := 0; i <= skIndex; i++ {
if len(buff) == 0 {
//less private keys present in the file than required
return nil, "", fmt.Errorf("%w while reading %s file, invalid index %d", ErrInvalidIndex, relativePath, i)
}
blkRecovered, buff = pem.Decode(buff)
if blkRecovered == nil {
return nil, "", fmt.Errorf("%w while reading %s file, error decoding", ErrPemFileIsInvalid, relativePath)
}
}
if blkRecovered == nil {
return nil, "", ErrNilPemBLock
}
blockType := blkRecovered.Type
header := "PRIVATE KEY for "
if strings.Index(blockType, header) != 0 {
return nil, "", fmt.Errorf("%w missing '%s' in block type", ErrPemFileIsInvalid, header)
}
blockTypeString := blockType[len(header):]
return blkRecovered.Bytes, blockTypeString, nil
}
// SaveSkToPemFile saves secret key bytes in the file
func SaveSkToPemFile(file *os.File, identifier string, skBytes []byte) error {
if file == nil {
return ErrNilFile
}
blk := pem.Block{
Type: "PRIVATE KEY for " + identifier,
Bytes: skBytes,
}
return pem.Encode(file, &blk)
}