/
dicompot.go
291 lines (256 loc) · 7.86 KB
/
dicompot.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
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
package main
import (
"flag"
"log"
"net"
"os"
"path/filepath"
"strings"
"sync"
"github.com/grailbio/go-dicom"
"github.com/mattn/go-colorable"
"github.com/nsmfoo/dicompot"
"github.com/nsmfoo/dicompot/dimse"
"github.com/sirupsen/logrus"
"github.com/snowzach/rotatefilehook"
)
var (
portFlag = flag.String("port", "11112", "TCP port to listen to")
ipFlag = flag.String("ip", "127.0.0.1", "IP address to listen to")
enFlag = flag.String("enforce", "no", "Enforce AE title check")
aeFlag = flag.String("ae", "radiant", "AE title of this server")
dirFlag = flag.String("dir", ".", "Picture directory")
logFlag = flag.String("log", "dicompot.log", "logfile")
)
func logInit() {
var logLevel = logrus.InfoLevel
rotateFileHook, err := rotatefilehook.NewRotateFileHook(rotatefilehook.RotateFileConfig{
Filename: *logFlag,
MaxSize: 10,
MaxBackups: 3,
MaxAge: 7,
Level: logLevel,
Formatter: &logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
},
})
if err != nil {
logrus.Fatalf("Failed to initialize file rotate hook: %v", err)
}
logrus.SetOutput(colorable.NewColorableStdout())
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
})
logrus.AddHook(rotateFileHook)
}
type server struct {
mu *sync.Mutex
// Set of dicom files the server manages. Keys are file paths.
datasets map[string]*dicom.DataSet
}
// Represents a match.
type filterMatch struct {
path string // DICOM path name
elems []*dicom.Element // Elements within "ds" that match the filter
}
// "filters" are matching conditions specified in C-{FIND,GET,MOVE}. This
// function returns the list of datasets and their elements that match filters.
func (ss *server) findMatchingFiles(filters []*dicom.Element) ([]filterMatch, error) {
ss.mu.Lock()
defer ss.mu.Unlock()
var matches []filterMatch
// sum := 0
for path, ds := range ss.datasets {
allMatched := true
match := filterMatch{path: path}
for _, filter := range filters {
ok, elem, err := dicom.Query(ds, filter)
if err != nil {
return matches, err
}
if !ok {
allMatched = false
break
}
if elem != nil {
match.elems = append(match.elems, elem)
} else {
elem, err := dicom.NewElement(filter.Tag)
if err != nil {
log.Println(err)
return matches, err
}
match.elems = append(match.elems, elem)
}
}
if allMatched {
if len(match.elems) == 0 {
panic(match)
}
matches = append(matches, match)
}
}
return matches, nil
}
func (ss *server) onCFind(
transferSyntaxUID string,
sopClassUID string,
filters []*dicom.Element,
sessionID string,
ch chan dicompot.CFindResult) {
matches, err := ss.findMatchingFiles(filters)
logrus.WithFields(logrus.Fields{
"Matches": len(matches),
"ID": sessionID,
}).Warn("C-FIND Search result")
if err != nil {
ch <- dicompot.CFindResult{Err: err}
} else {
for _, match := range matches {
ch <- dicompot.CFindResult{Elements: match.elems}
}
}
close(ch)
}
func (ss *server) onCMoveOrCGet(
transferSyntaxUID string,
sopClassUID string,
filters []*dicom.Element,
sessionID string,
ch chan dicompot.CMoveResult) {
matches, err := ss.findMatchingFiles(filters)
logrus.WithFields(logrus.Fields{
"Matches": len(matches),
"ID": sessionID,
}).Warn("C-FIND Search result")
if err != nil {
ch <- dicompot.CMoveResult{Err: err}
} else {
for i, match := range matches {
ds, err := dicom.ReadDataSetFromFile(match.path, dicom.ReadOptions{})
resp := dicompot.CMoveResult{
Remaining: len(matches) - i - 1,
Path: match.path,
}
if err != nil {
resp.Err = err
} else {
resp.DataSet = ds
}
ch <- resp
}
}
close(ch)
}
// Find DICOM files in or under "dir" and read its attributes.
func listDicomFiles(dir string) (map[string]*dicom.DataSet, error) {
datasets := make(map[string]*dicom.DataSet)
readFile := func(path string) {
if _, ok := datasets[path]; ok {
return
}
ds, err := dicom.ReadDataSetFromFile(path, dicom.ReadOptions{DropPixelData: true})
if err != nil {
log.Printf("%s: failed to parse dicom file: %v", path, err)
return
}
datasets[path] = ds
}
walkCallback := func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Printf("%v: skip file: %v", path, err)
return nil
}
if (info.Mode() & os.ModeDir) != 0 {
// If a directory contains file "DICOMDIR", all the files in the directory are DICOM files.
if _, err := os.Stat(filepath.Join(path, "DICOMDIR")); err != nil {
return nil
}
subpaths, err := filepath.Glob(path + "/*")
if err != nil {
log.Printf("%v: glob: %v", path, err)
return nil
}
for _, subpath := range subpaths {
if !strings.HasSuffix(subpath, "DICOMDIR") {
readFile(subpath)
}
}
return nil
}
if strings.HasSuffix(path, ".dcm") {
readFile(path)
}
return nil
}
if err := filepath.Walk(dir, walkCallback); err != nil {
return nil, err
}
return datasets, nil
}
func canonicalizeHostPort(TcpPort string) string {
if !strings.Contains(TcpPort, ":") {
return ":" + TcpPort
}
return TcpPort
}
func canonicalizeHostIp(IpAdr string) string {
if net.ParseIP(IpAdr) == nil {
logrus.WithFields(logrus.Fields{
"IP Address": strings.Replace(IpAdr, "\"", "", -1),
}).Error("Invalid IP address, please try again")
os.Exit(1)
}
return IpAdr
}
func main() {
flag.Parse()
logInit()
port := canonicalizeHostPort(*portFlag)
ip := canonicalizeHostIp(*ipFlag)
hostAddress := ip + port
datasets, err := listDicomFiles(*dirFlag)
log.Printf(`
██████╗ ██╗ ██████╗ ██████╗ ███╗ ███╗██████╗ ██████╗ ████████╗
██╔══██╗██║██╔════╝██╔═══██╗████╗ ████║██╔══██╗██╔═══██╗╚══██╔══╝
██║ ██║██║██║ ██║ ██║██╔████╔██║██████╔╝██║ ██║ ██║
██║ ██║██║██║ ██║ ██║██║╚██╔╝██║██╔═══╝ ██║ ██║ ██║
██████╔╝██║╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚██████╔╝ ██║
╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝
@nsmfoo - Mikael Keri
`)
log.Printf("-| Loaded %d images", len(datasets))
ss := server{
mu: &sync.Mutex{},
datasets: datasets,
}
log.Printf("-| Listening on: %s", hostAddress)
params := dicompot.ServiceProviderParams{
AETitle: *aeFlag,
Enforce: *enFlag,
CEcho: func(connState dicompot.ConnectionState) dimse.Status {
return dimse.Success
},
CFind: func(connState dicompot.ConnectionState, transferSyntaxUID string, sopClassUID string,
filter []*dicom.Element, sessionID string, ch chan dicompot.CFindResult) {
ss.onCFind(transferSyntaxUID, sopClassUID, filter, sessionID, ch)
},
CMove: func(connState dicompot.ConnectionState, transferSyntaxUID string, sopClassUID string,
filter []*dicom.Element, sessionID string, ch chan dicompot.CMoveResult) {
ss.onCMoveOrCGet(transferSyntaxUID, sopClassUID, filter, sessionID, ch)
},
CGet: func(connState dicompot.ConnectionState, transferSyntaxUID string, sopClassUID string,
filter []*dicom.Element, sessionID string, ch chan dicompot.CMoveResult) {
ss.onCMoveOrCGet(transferSyntaxUID, sopClassUID, filter, sessionID, ch)
},
}
log.Printf("-| Local AE Title: %s", params.AETitle)
log.Printf("-| Attacker log: %s", *logFlag)
sp, err := dicompot.NewServiceProvider(params, hostAddress)
if err != nil {
panic(err)
}
sp.Run()
}