summaryrefslogtreecommitdiff
path: root/store/store.go
blob: f7420aa1dc97d7ed1a9b6a2724f996699c8473c2 (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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package store

import (
	"encoding/json"
	"github.com/bwmarrin/snowflake"
	log "github.com/sirupsen/logrus"
	"os"
	"runtime"
	"strconv"
	"sync"
)

const revision = -6

var (
	imageNode *snowflake.Node
	userNode  *snowflake.Node
)

// Info represents system information of a store.
type Info struct {
	Revision       int         `json:"revision"`
	Compat         bool        `json:"compat"`
	Register       bool        `json:"register"`
	InitialUser    string      `json:"initial_user"`
	PermissionDir  os.FileMode `json:"permission_dir"`
	PermissionFile os.FileMode `json:"permission_file"`
}

// Store represents a file store.
type Store struct {
	Path           string
	SingleUser     bool
	Revision       int
	Compat         bool
	Register       bool
	InitialUser    string
	PermissionDir  os.FileMode
	PermissionFile os.FileMode
	mutex          map[string]*sync.RWMutex
	sync.RWMutex
}

func init() {
	// Set Epoch to beginning of time (01/01/1970)
	snowflake.Epoch = 0

	// Create a single node
	var err error
	imageNode, err = snowflake.NewNode(9)
	userNode, err = snowflake.NewNode(7)
	if err != nil {
		log.Fatalf("Error while creating snowflake generation node, %s", err)
		os.Exit(1)
	}
}

// New initialises a new store instance.
func New(path string, single bool) *Store {
	var store *Store
	if stat, err := os.Stat(path); err != nil {
		log.Infof("Initializing new store at %s.", path)
		// Initialise empty store.
		store = &Store{
			Path:           path,
			SingleUser:     single,
			Revision:       revision,
			Compat:         runtime.GOOS == "windows",
			Register:       false,
			PermissionDir:  0700,
			PermissionFile: 0600,
			mutex:          make(map[string]*sync.RWMutex),
		}
		if err = store.create(); err != nil {
			log.Fatalf("Error creating store, %s", err)
			os.Exit(1)
		}
	} else {
		// Exit if store is not a directory.
		if !stat.IsDir() {
			log.Fatal("Store is not a directory.")
			os.Exit(1)
		}

		// Load and parse store info.
		var info Info
		var payload []byte
		if payload, err = os.ReadFile(path + "/" + infoJson); err != nil {
			log.Fatalf("Error reading store information, %s", err)
			os.Exit(1)
		} else {
			if err = json.Unmarshal(payload, &info); err != nil {
				log.Fatalf("Error parsing store information, %s", err)
				os.Exit(1)
			}
		}
		if info.Revision != revision {
			log.Fatalf("Store format revision %v, expecting revision %v.", info.Revision, revision)
			os.Exit(1)
		}

		// Create store instance.
		store = &Store{
			Path:           path,
			SingleUser:     single,
			Revision:       info.Revision,
			Compat:         info.Compat,
			Register:       info.Register,
			InitialUser:    info.InitialUser,
			PermissionDir:  info.PermissionDir,
			PermissionFile: info.PermissionFile,
			mutex:          make(map[string]*sync.RWMutex),
		}
	}
	if store.file(store.LockPath()) {
		if pid, err := os.ReadFile(store.LockPath()); err != nil {
			log.Fatalf("Store locked, lock file unreadable, %s", err)
			log.Exit(1)
		} else {
			log.Fatalf("Store locked by process %s.", string(pid))
			log.Exit(1)
		}
	}
	if err := os.WriteFile(store.LockPath(), []byte(strconv.Itoa(os.Getpid())), store.PermissionFile); err != nil {
		log.Fatalf("Error locking store, %s", err)
		log.Exit(1)
	}
	return store
}

// Close closes the store.
func (s *Store) Close() {
	if err := os.Remove(s.LockPath()); err != nil {
		log.Fatalf("Error unlocking store, %s", err)
		log.Exit(1)
	}
	log.Info("Store closed.")
}

// create sets up the store directory if it does not exist.
func (s *Store) create() error {
	// Check if exists
	if _, err := os.Stat(s.Path); err == nil {
		return AlreadyExists
	}

	// Create directories
	if err := os.Mkdir(s.Path, s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.TagsDir(), s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.ImagesDir(), s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.ImagesSnowflakeDir(), s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.UsersDir(), s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.SecretsDir(), s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.PageBaseDir(), s.PermissionDir); err != nil {
		return err
	}
	if err := os.Mkdir(s.UsernamesDir(), s.PermissionDir); err != nil {
		return err
	}

	// Create initial user
	info := s.UserAdd("root", true, "initial")
	if info.Snowflake == "" {
		log.Fatalf("Error creating initial user.")
		os.Exit(1)
	} else {
		log.Infof("Created initial user with username root and password initial.")
	}
	s.InitialUser = info.Snowflake

	// Create information file
	if payload, err := json.Marshal(Info{
		Revision:       s.Revision,
		Compat:         s.Compat,
		Register:       s.Register,
		InitialUser:    s.InitialUser,
		PermissionDir:  s.PermissionDir,
		PermissionFile: s.PermissionFile,
	}); err != nil {
		return err
	} else {
		if err = os.WriteFile(s.Path+"/"+infoJson, payload, s.PermissionFile); err != nil {
			return err
		}
	}

	return nil
}

// getLock returns a lock associated with a string.
func (s *Store) getLock(entry string) *sync.RWMutex {
	s.RLock()
	mutex, ok := s.mutex[entry]
	s.RUnlock()
	if !ok {
		s.Lock()
		mutex = &sync.RWMutex{}
		s.mutex[entry] = mutex
		s.Unlock()
	}
	return mutex
}

// file probes for the existence of specified entry on the filesystem.
func (s *Store) file(path string) bool {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return false
		} else {
			log.Fatalf("Error while stat %s, %s", path, err)
			os.Exit(1)
		}
	}
	return true
}

// dir probes for the presence of specified directory on the filesystem.
func (s *Store) dir(path string) bool {
	if stat, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return false
		} else {
			log.Fatalf("Error while stat %s, %s", path, err)
			os.Exit(1)
		}
	} else {
		if !stat.IsDir() {
			log.Fatalf("Path %s is not a directory.", path)
			os.Exit(1)
		}
	}
	return true
}

// flake validates a snowflake string.
func (s *Store) flake(flake string) bool {
	if flake == "" {
		return false
	}
	_, err := strconv.Atoi(flake)
	return err == nil
}

// link provides symlink-like usage while considering compat mode.
func (s *Store) link(old, new string) {
	if !s.Compat {
		if err := os.Symlink(old, new); err != nil {
			log.Fatalf("Error while linking %s to %s, %s", old, new, err)
			os.Exit(1)
		}
	} else {
		if err := os.WriteFile(new, []byte(old), s.PermissionFile); err != nil {
			log.Fatalf("Error while writing associate file for %s to %s, %s", old, new, err)
			os.Exit(1)
		}
	}
}

// readlink provides readlink-like usage while considering compat mode.
func (s *Store) readlink(path string) string {
	if !s.Compat {
		//if final, err := os.Readlink(path); err != nil {
		//	if os.IsNotExist(err) {
		//		return ""
		//	} else {
		//		log.Fatalf("Error reading symlink %s, %s.", path, err)
		//		os.Exit(1)
		//	}
		//} else {
		//	return final
		//}
		return path
	} else {
		if final, err := os.ReadFile(path); err != nil {
			if os.IsNotExist(err) {
				return ""
			} else {
				log.Fatalf("Error reading association file %s, %s.", path, err)
				os.Exit(1)
			}
		} else {
			return string(final)
		}
	}
	return ""
}