summaryrefslogtreecommitdiff
path: root/cmd/_____/http/uploads.go
blob: 468e8a19f3928200dbe8fa1460b287975444af8e (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
package http

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"strings"
	"sync"
)

const (
	// There is no error, the file uploaded with success.
	UploadErrorOK = 0

	// No file was uploaded.
	UploadErrorNoFile = 4

	// Missing a temporary folder.
	UploadErrorNoTmpDir = 5

	// Failed to write file to disk.
	UploadErrorCantWrite = 6

	// ForbidUploads file extension.
	UploadErrorExtension = 7
)

// FileUpload represents singular file wrapUpload.
type FileUpload struct {
	// Name contains filename specified by the client.
	Name string `json:"name"`

	// MimeType contains mime-type provided by the client.
	MimeType string `json:"type"`

	// Size of the uploaded file.
	Size int64 `json:"size"`

	// Error indicates file upload error (if any). See http://php.net/manual/en/features.file-upload.errors.php
	Error int `json:"error"`

	// TempFilename points to temporary file location.
	TempFilename string `json:"tmpName"`

	// associated file header
	header *multipart.FileHeader
}

func (f *FileUpload) Open(cfg *Config) error {
	if cfg.Forbidden(f.Name) {
		f.Error = UploadErrorExtension
		return nil
	}

	file, err := f.header.Open()
	if err != nil {
		f.Error = UploadErrorNoFile
		return err
	}
	defer file.Close()

	tmp, err := ioutil.TempFile(cfg.TmpDir, "upload")
	if err != nil {
		// most likely cause of this issue is missing tmp dir
		f.Error = UploadErrorNoTmpDir
		return err
	}

	f.TempFilename = tmp.Name()
	defer tmp.Close()

	if f.Size, err = io.Copy(tmp, file); err != nil {
		f.Error = UploadErrorCantWrite
	}

	return err
}

func wrapUpload(f *multipart.FileHeader) *FileUpload {
	return &FileUpload{
		Name:     f.Filename,
		MimeType: f.Header.Get("Content-Type"),
		Error:    UploadErrorOK,
		header:   f,
	}
}

type fileTree map[string]interface{}

func (d fileTree) push(k string, v []*FileUpload) {
	if len(v) == 0 {
		// skip empty values
		return
	}

	indexes := make([]string, 0)
	for _, index := range strings.Split(k, "[") {
		indexes = append(indexes, strings.Trim(index, "]"))
	}

	if len(indexes) <= maxLevel {
		d.mount(indexes, v)
	}
}

// mount mounts data tree recursively.
func (d fileTree) mount(i []string, v []*FileUpload) {
	if len(v) == 0 {
		return
	}

	if len(i) == 1 {
		// single value context
		d[i[0]] = v[0]
		return
	}

	if len(i) == 2 && i[1] == "" {
		// non associated array of elements
		d[i[0]] = v
		return
	}

	if p, ok := d[i[0]]; ok {
		p.(fileTree).mount(i[1:], v)
	}

	d[i[0]] = make(fileTree)
	d[i[0]].(fileTree).mount(i[1:], v)
}

// tree manages uploaded files tree and temporary files.
type Uploads struct {
	// pre processed data tree for Uploads.
	tree fileTree

	// flat list of all file Uploads.
	list []*FileUpload
}

// MarshalJSON marshal tree tree into JSON.
func (u *Uploads) MarshalJSON() ([]byte, error) {
	return json.Marshal(u.tree)
}

// Open moves all uploaded files to temp directory, return error in case of issue with temp directory. File errors
// will be handled individually. @todo: do we need it?
func (u *Uploads) Open(cfg *Config) error {
	var wg sync.WaitGroup
	for _, f := range u.list {
		wg.Add(1)
		go func(f *FileUpload) {
			defer wg.Done()
			f.Open(cfg)
		}(f)
	}

	wg.Wait()
	return nil
}

// Clear deletes all temporary files.
func (u *Uploads) Clear() {
	for _, f := range u.list {
		if f.TempFilename != "" && exists(f.TempFilename) {
			os.Remove(f.TempFilename)
		}
	}
}

// parse incoming dataTree request into JSON (including multipart form dataTree)
func parseUploads(r *http.Request) (*Uploads, error) {
	u := &Uploads{
		tree: make(fileTree),
		list: make([]*FileUpload, 0),
	}

	for k, v := range r.MultipartForm.File {
		files := make([]*FileUpload, 0, len(v))
		for _, f := range v {
			files = append(files, wrapUpload(f))
		}

		u.list = append(u.list, files...)
		u.tree.push(k, files)
	}

	return u, nil
}

// exists if file exists. by osutils; todo: better?
func exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}

	if os.IsNotExist(err) {
		return false
	}

	panic(fmt.Errorf("unable to stat path %q; %v", path, err))
}