all repos — nirvash @ main

modular CMS using the quartzgun library

archetype/fileManager.go (raw)

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
package archetype

import (
	"errors"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

type SimpleFileManager struct {
	Root        string
	ShowHTML    bool
	ShowHidden  bool
	maxUploadMB int64
}

type FileData struct {
	Error  string
	Path   string
	Name   string
	Parent string
	IsDir  bool
}

type FileListing struct {
	Error   string
	Root    string
	Up      string
	SubDirs []string
	Files   []string
}

type FileManager interface {
	Init(cfg *Config) error
	ListSubTree(root string) FileListing
	GetFileData(slug string) FileData
	AddFile(path string, req *http.Request) error
	MkDir(path, newDir string) error
	Remove(path string) error
	Rename(oldFullPath, newPath, newName string) error
	MaxUploadMB() int64
}

func (self *SimpleFileManager) Init(cfg *Config) error {
	self.Root = filepath.Clean(cfg.StaticRoot)
	self.ShowHTML = cfg.StaticShowHTML
	self.ShowHidden = cfg.StaticShowHidden
	self.maxUploadMB = cfg.StaticMaxUploadMB
	return nil
}

func (self *SimpleFileManager) ListSubTree(root string) FileListing {
	list := FileListing{}

	fullPath := filepath.Join(self.Root, root)

	if !strings.HasPrefix(filepath.Clean(fullPath), self.Root) {
		list.Error = "You cannot escape!"
		return list
	}

	files, err := ioutil.ReadDir(fullPath)

	if err != nil {
		list.Error = err.Error()
		return list
	}

	list.Root = root
	if !strings.HasSuffix(list.Root, "/") {
		list.Root += "/"
	}
	if !strings.HasPrefix(list.Root, "/") {
		list.Root = "/" + list.Root
	}

	levels := strings.Split(root, "/")

	if list.Root != "/" {
		list.Up = "/"
	}
	if len(levels) >= 2 && list.Root != "/" {
		list.Up = strings.Join(levels[:len(levels)-1], "/")
		if !strings.HasPrefix(list.Up, "/") {
			list.Up = "/" + list.Up
		}
	}

	for _, file := range files {
		if !self.ShowHidden && strings.HasPrefix(file.Name(), ".") {
			continue
		}
		if file.IsDir() {
			list.SubDirs = append(list.SubDirs, file.Name())
		} else {
			if !self.ShowHTML && strings.HasSuffix(file.Name(), ".html") {
				continue
			}
			list.Files = append(list.Files, file.Name())
		}
	}

	return list
}

func (self *SimpleFileManager) GetFileData(slug string) FileData {
	fullPath := filepath.Join(self.Root, slug)
	fileInfo, err := os.Stat(fullPath)

	if err != nil {
		return FileData{
			Error: err.Error(),
		}
	}
	if !strings.HasPrefix(filepath.Clean(fullPath), self.Root) {
		return FileData{
			Error: "You cannot escape!",
		}
	}

	cleanedSlug := filepath.Clean(slug)
	fileBase := filepath.Base(cleanedSlug)
	parent := strings.TrimSuffix("/"+cleanedSlug, "/"+fileBase)
	return FileData{
		Path:   filepath.Clean(slug),
		Name:   fileBase,
		Parent: parent,
		IsDir:  fileInfo.IsDir(),
	}
}

func (self *SimpleFileManager) Remove(slug string) error {
	fullPath := filepath.Join(self.Root, slug)

	if !strings.HasPrefix(filepath.Clean(fullPath), self.Root) {
		return errors.New("You cannot escape!")
	}

	_, err := os.Stat(fullPath)
	if err != nil {
		return err
	}

	return os.RemoveAll(fullPath)
}

func (self *SimpleFileManager) AddFile(path string, req *http.Request) error {
	fullPath := filepath.Join(self.Root, path)

	if !strings.HasPrefix(filepath.Clean(fullPath), filepath.Clean(self.Root)) {
		return errors.New("You cannot escape!")
	}

	_, err := os.Stat(fullPath)
	if err != nil {
		return err
	}

	req.ParseMultipartForm(self.maxUploadMB << 20)
	file, header, err := req.FormFile("file")
	if err != nil {
		return err
	}

	fileData, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}

	destPath := filepath.Join(fullPath, header.Filename)
	dest, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer dest.Close()

	dest.Write(fileData)
	return nil
}

func (self *SimpleFileManager) MkDir(path, newDir string) error {
	fullPath := filepath.Join(self.Root, path)
	if !strings.HasPrefix(filepath.Clean(fullPath), self.Root) {
		return errors.New("You cannot escape!")
	}

	_, err := os.Stat(fullPath)
	if err != nil {
		return err
	}

	if strings.Contains(newDir, "/") || strings.Contains(newDir, "\\") {
		return errors.New("Cannot create nested directories at once")
	}

	newDirPath := filepath.Join(fullPath, newDir)
	_, err = os.Stat(newDirPath)
	if !os.IsNotExist(err) {
		return errors.New("Directory exists")
	}

	return os.Mkdir(newDirPath, 0755)
}

func (self *SimpleFileManager) Rename(oldFullPath, newPath, newName string) error {
	fullPath := filepath.Join(self.Root, oldFullPath)

	if !strings.HasPrefix(filepath.Clean(fullPath), self.Root) {
		return errors.New("You cannot escape!")
	}

	_, err := os.Stat(fullPath)
	if err != nil {
		return err
	}

	newParent := filepath.Clean(filepath.Join(self.Root, newPath))
	if !strings.HasPrefix(newParent, self.Root) {
		return errors.New("You cannot escape!")
	}

	_, err = os.Stat(newParent)
	if err != nil {
		return err
	}

	if newName == "" {
		_, oldName := filepath.Split(oldFullPath)
		newName = oldName
	}

	newFullPath := filepath.Join(newParent, newName)
	if !strings.HasPrefix(filepath.Clean(newFullPath), newParent) {
		return errors.New("You cannot escape!")
	}

	return os.Rename(fullPath, filepath.Join(newParent, newName))
}

func (self *SimpleFileManager) MaxUploadMB() int64 {
	return self.maxUploadMB
}