-
Notifications
You must be signed in to change notification settings - Fork 13
/
file.go
109 lines (83 loc) · 2.18 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
package main
import (
"bytes"
"encoding/xml"
"io"
"io/ioutil"
"path/filepath"
"regexp"
"github.com/keltia/archive"
"github.com/pkg/errors"
)
/* cf. https://tools.ietf.org/html/rfc7489#section-7.2.1.1
filename = receiver "!" policy-domain "!" begin-timestamp
"!" end-timestamp [ "!" unique-id ] "." extension
unique-id = 1*(ALPHA / DIGIT)
*/
const (
reFileName = `^([\S\.]+)!([\S\.]+)!([\d]+)!([\d]+)(![[:alnum:]]+)*(\.\S+)(\.(gz|zip))*$`
)
var reFN *regexp.Regexp
func init() {
reFN = regexp.MustCompile(reFileName)
}
func checkFilename(file string) (ok bool) {
base := filepath.Base(file)
return reFN.MatchString(base)
}
// HandleZipFile is here for zip files because archive.NewFromReader() does not work here
func HandleZipFile(ctx *Context, file string) (string, error) {
debug("HandleZipFile")
var body []byte
a, err := archive.New(file)
if err == nil {
body, err = a.Extract(".xml")
if err != nil {
return "", errors.Wrap(err, "extract")
}
} else {
// Got plain text (i.e. xml)
if body, err = ioutil.ReadFile(file); err != nil {
return "", errors.Wrap(err, "ReadFile")
}
}
debug("xml=%s", string(body))
var report Feedback
if err := xml.Unmarshal(body, &report); err != nil {
return "", errors.Wrap(err, "unmarshall")
}
debug("report=%v\n", report)
return Analyze(ctx, report)
}
// HandleSingleFile creates a tempdir and dispatch csv/zip files to handler.
func HandleSingleFile(ctx *Context, r io.ReadCloser, typ int) (string, error) {
debug("HandleSingleFile")
var body []byte
debug("typ=%d", typ)
if typ == archive.ArchiveZip {
return "", errors.New("unsupported")
}
a, err := archive.NewFromReader(r, typ)
if err == nil {
debug("a=%#v", a)
body, err = a.Extract("")
if err != nil {
return "", errors.Wrap(err, "extract")
}
} else {
// Got plain text (i.e. xml)
buf := bytes.NewBuffer(body)
_, err := io.Copy(buf, r)
if err != nil {
return "", errors.Wrap(err, "copy")
}
}
debug("xml=%#v", body)
var report Feedback
if err := xml.Unmarshal(body, &report); err != nil {
debug("%d %s", typ, fType)
return "", errors.Wrap(err, "unmarshall")
}
debug("report=%v\n", report)
return Analyze(ctx, report)
}