-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdlsir.go
569 lines (460 loc) · 16 KB
/
dlsir.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package main
import (
"fmt"
"net"
"net/http"
"os"
"slices"
"strconv"
"strings"
"time"
"github.com/zam-haus/dlsir/internal/config"
"github.com/zam-haus/dlsir/internal/firmware"
"github.com/gin-gonic/gin"
// "github.com/davecgh/go-spew/spew"
)
const confDir = "./conf/"
const confSrv = confDir + "/dlsir.conf"
const confDumpDir = "./conf_dump/"
type phoneNextProvStep int
const (
Initial = iota // No contact yet
WaitForSolicited // ContactMe was sent; now wait for request from phone
SendConfig // Send system configuration
SendFiles // Send files (excluding software)
SendSoftware // Send system software (i.e., firmware update)
WaitForUpdate // Software was sent; now wait for phone response
RequestConfig // Request the phone's current configuration
)
func (state phoneNextProvStep) String() string {
switch state {
case Initial:
return "Initial"
case WaitForSolicited:
return "WaitForSolicited"
case SendConfig:
return "SendConfig"
case SendFiles:
return "SendFiles"
case SendSoftware:
return "SendSoftware"
case WaitForUpdate:
return "WaitForUpdate"
case RequestConfig:
return "RequestConfig"
default:
return "INVALID"
}
}
type phoneDesc struct {
Mac string
IP string
Number string
NextStep phoneNextProvStep
PendingFiles []string
RqBegin time.Time
DevType string
FwVersion firmware.FirmwareVersion
FwNeedsUpdate bool
}
type item struct {
Name string `xml:"name,attr"`
Index int `xml:"index,attr,omitempty"`
Status string `xml:"status,attr,omitempty"`
Value string `xml:",chardata"`
}
type reason struct {
Action string `xml:"action,attr,omitempty"`
Status string `xml:"status,attr,omitempty"`
Value string `xml:",chardata"`
}
type message struct {
Action string `xml:"Action,omitempty"`
Reason reason `xml:"ReasonForContact"`
Nonce string `xml:"nonce,attr"`
MaxItems int `xml:"maxItems,attr,omitempty"`
Fragment string `xml:"fragment,attr,omitempty"`
Items []item `xml:"ItemList>Item"`
}
type loginServiceData struct {
Message message `xml:"Message"`
}
type dlsMessage struct {
XMLName struct{} `xml:"DLSMessage"`
Message message `xml:"Message"`
}
var phoneState map[string]*phoneDesc
func formatItemList(items []item) string {
var sb strings.Builder
for _, item := range items {
sb.WriteString(item.Name)
if item.Index != 0 {
sb.WriteString("[")
sb.WriteString(strconv.Itoa(item.Index))
sb.WriteString("]")
}
sb.WriteString(" = ")
sb.WriteString(item.Value)
if item.Status != "" {
sb.WriteString(" [")
sb.WriteString(item.Status)
sb.WriteString("]")
}
sb.WriteString("\n")
}
return sb.String()
}
func itemFromEntry(entry config.ConfigEntry) (*item, error) {
if entry.Index != "" {
index, err := strconv.Atoi(entry.Index)
if err != nil {
return nil, fmt.Errorf("failed to parse index '%v' as int: %v", entry.Index, err)
}
return &item{Name: entry.Name, Index: index, Status: "", Value: entry.Value}, nil
}
return &item{Name: entry.Name, Index: 0, Status: "", Value: entry.Value}, nil
}
func itemsFromEntries(entries []config.ConfigEntry) ([]item, error) {
items := make([]item, 0)
for _, entry := range entries {
i, err := itemFromEntry(entry)
if err != nil {
return nil, err
}
items = append(items, *i)
}
return items, nil
}
func sendConfig(c *gin.Context, phone *phoneDesc, msg message) (string, []item) {
conf, err := config.GetMergedConfig(confDir+"/"+phone.Mac+".conf", confDir+"/phonedefault.conf")
if err != nil {
_log(c, "Failed to read phone config: %v", err)
return "", []item{}
}
entries := conf.GetFilteredEntries("file-", false)
items, err := itemsFromEntries(entries)
if err != nil {
_log(c, "Failed to convert config entries to phone items: %v", err)
return "", []item{}
}
return "WriteItems", items
}
func sendFiles(c *gin.Context, phone *phoneDesc, msg message) (string, []item) {
conf, err := config.GetMergedConfig(confDir+"/"+phone.Mac+".conf", confDir+"/phonedefault.conf")
if err != nil {
_log(c, "Failed to read phone conf: %v", err)
return "", []item{}
}
entries := conf.GetFilteredEntries("file-", true)
localHost := c.Request.Host
for idx := range entries {
if entries[idx].Name == "file-name" {
entries[idx].Name = "file-https-base-url"
entries[idx].Value = fmt.Sprintf("https://%v/file/%v", localHost, entries[idx].Value)
}
}
items, err := itemsFromEntries(entries)
if err != nil {
_log(c, "Failed to convert config entries to phone items: %v", err)
return "", []item{}
}
return "FileDeployment", items
}
func sendSoftware(c *gin.Context, phone *phoneDesc, msg message) (string, []item) {
items := make([]item, 0)
localHost := c.Request.Host
conf, err := config.GetConfigFile(confSrv)
if err != nil {
_log(c, "Failed to read config file %v: %v", confSrv, err)
return "", []item{}
}
fwConfigName := config.GetFwItemName(phone.DevType)
fwFile, err := conf.GetEntry(fwConfigName)
if err != nil {
_log(c, "Failed to read firmware file from configuration; missing entry fw-openstage40")
_log(c, "This is strange; we should not have ended up here!")
return "", []item{}
}
fw, err := firmware.GetFirmwareInfo("files/" + fwFile.Value)
if err != nil {
_log(c, "Failed to read firmware version from file; maybe not a proper firmware file?")
_log(c, "Error: %v", err.Error())
return "", []item{}
}
_log(c, "Issuing software update for phone %v / %v", phone.Number, phone.IP)
_log(c, " - old version: %v", phone.FwVersion)
_log(c, " - new version: %v", fw.FwVersion)
items = append(items, item{Name: "file-https-base-url", Index: 0, Value: fmt.Sprintf("https://%v/file/%v", localHost, fwFile.Value)})
items = append(items, item{Name: "file-priority", Index: 0, Value: "immediate"})
items = append(items, item{Name: "file-sw-type", Index: 0, Value: fw.FwType})
items = append(items, item{Name: "file-sw-version", Index: 0, Value: fw.FwVersion.String()})
items = append(items, item{Name: "file-type", Index: 0, Value: "APP"})
_log(c, "Sending: %v", formatItemList(items))
return "SoftwareDeployment", items
}
func readAllItems(phone *phoneDesc, msg message) (string, []item) {
return "ReadAllItems", []item{}
}
func checkReply(c *gin.Context, phone *phoneDesc, msg message) bool {
_log(c, "Action %v was %v", msg.Reason.Action, msg.Reason.Status)
//printItemList(c, msg.Items);
if msg.Reason.Action == "ReadAllItems" && msg.Reason.Status == "accepted" {
file := fmt.Sprintf("%v/%v.conf", confDumpDir, phone.Number)
content := formatItemList(msg.Items)
err := os.WriteFile(file, []byte(content), 0666)
if err != nil {
_log(c, "failed to write to file %v with error:\n %v", file, err)
}
}
return msg.Reason.Status == "accepted"
}
func findItem(items []item, name string, index int) *item {
for _, item := range items {
if item.Name == name && item.Index == index {
return &item
}
}
return nil
}
func checkStatus(c *gin.Context, phone *phoneDesc, msg message) bool {
for _, item := range msg.Items {
if item.Name == "file-deployment-name" {
statusItem := findItem(msg.Items, "file-deployment-status", item.Index)
_log(c, " - File '%v' upload %v\n", item.Value, statusItem.Value)
}
}
// _log(c, "WARNING: Status response does not contain required items!\n");
// spew.Dump(msg)
return true
}
func getFile(c *gin.Context) {
file := c.Params.ByName("file")
_log(c, "Got GET request for file %v\n", file)
c.FileAttachment("./files/"+file, file)
}
func itemByName(items []item, name string) *string {
idx := slices.IndexFunc(items, func(i item) bool { return i.Name == name })
if idx == -1 {
return nil
}
return &items[idx].Value
}
func postLoginService(c *gin.Context) {
var data loginServiceData
err := c.BindXML(&data)
if err != nil {
_log(c, "BindXML failed: %v\n", err)
c.Status(http.StatusBadRequest)
return
}
msg := data.Message
// try to find phone number in response
phoneIP := c.RemoteIP()
if _, ok := phoneState[phoneIP]; !ok {
phoneNoPtr := itemByName(msg.Items, "e164")
phoneNo := "?"
if phoneNoPtr != nil {
phoneNo = *phoneNoPtr
}
phoneMac := itemByName(msg.Items, "mac-addr")
devType := itemByName(msg.Items, "device-type")
fwType := itemByName(msg.Items, "software-type")
fwVersion := itemByName(msg.Items, "software-version")
if phoneMac == nil || devType == nil || fwType == nil || fwVersion == nil {
_log(c, "Initial contact missing required information")
_log(c, " - mac-addr: %v", *phoneMac)
_log(c, " - device-type: %v", *devType)
_log(c, " - software-type: %v", *fwType)
_log(c, " - software-version: %v", *fwVersion)
c.Status(http.StatusBadRequest)
return
}
ver, err := firmware.ParseFirmwareVersion(*fwVersion)
if err != nil {
_log(c, "%v", err.Error())
c.Status(http.StatusBadRequest)
return
}
conf, err := config.GetConfigFile(confSrv)
if err != nil {
_log(c, "Failed to read config file %v: %v", confSrv, err)
c.Status(http.StatusInternalServerError)
return
}
fwConfigName := config.GetFwItemName(*devType)
fwFile, err := conf.GetEntry(fwConfigName)
needsUpdate := false
if err == nil {
myVersion, err := firmware.GetFirmwareInfo("files/" + fwFile.Value)
if err != nil {
_log(c, "Failed to read firmware version from file; maybe not a proper firmware file?")
_log(c, "Error: %v", err.Error())
} else {
needsUpdate = ver.Compare(myVersion.FwVersion) < 0
if needsUpdate {
_log(c, "Phone is running old firmware, is: %v, should be: %v", *ver, myVersion.FwVersion)
} else {
_log(c, "Phone is running most recent firmware %v", *ver)
}
}
} else {
_log(c, "I don't have a firmware for %v (configure as %v)", *devType, fwConfigName)
}
phoneState[phoneIP] = &phoneDesc{Mac: *phoneMac, IP: phoneIP, Number: phoneNo, NextStep: Initial, RqBegin: time.Now(), DevType: *devType, FwVersion: *ver, FwNeedsUpdate: needsUpdate}
}
phone := phoneState[phoneIP]
_log(c, "Request from phone '%v' with reason '%v'\n", phone.Number, msg.Reason.Value)
_log(c, " - Nonce: %v\n", msg.Nonce)
_log(c, " - local/remote IP: %v - %v\n", c.Request.Host, c.Request.RemoteAddr)
_log(c, " - NextStep: %v\n", phone.NextStep)
var action string
var responseItems []item
if msg.Reason.Value == "start-up" && phone.NextStep == WaitForUpdate {
// we issued a software update and the phone rebooted
// -> software update was likely successful
_log(c, "Yay - phone came back after a software update; requesting current configuration")
action, responseItems = readAllItems(phone, msg)
phone.NextStep = RequestConfig
} else if msg.Reason.Value == "start-up" || msg.Reason.Value == "solicited" {
// we send the full phone configuration both on startup and explicit request
action, responseItems = sendConfig(c, phone, msg)
phone.NextStep = SendFiles
} else if msg.Reason.Value == "reply-to" {
// this is a reply to a previous request - check the reply and continue with the next request
wasAccepted := checkReply(c, phone, msg)
if wasAccepted {
if phone.NextStep == SendFiles {
_log(c, "Configuration options sent successfully, continuing with files\n")
action, responseItems = sendFiles(c, phone, msg)
if phone.FwNeedsUpdate {
phone.NextStep = SendSoftware
} else {
phone.NextStep = RequestConfig
}
} else if phone.NextStep == RequestConfig {
_log(c, "Configuration finished successfully - current dump in %v\n", confDumpDir)
// we're done configuring the phone; wipe phone state and wait for new requests
delete(phoneState, phoneIP)
}
} else {
_log(c, "WARNING: Phone didn't accept previous request; aborting...")
}
} else if msg.Reason.Value == "status" {
// "status" is only sent after file operations
wasAccepted := checkStatus(c, phone, msg)
if !wasAccepted {
_log(c, "WARNING: Phone didn't accept previous request")
}
if phone.NextStep == SendSoftware {
action, responseItems = sendSoftware(c, phone, msg)
phone.NextStep = WaitForUpdate
} else if phone.NextStep == RequestConfig {
action, responseItems = readAllItems(phone, msg)
// phone.NextStep = RequestConfig
} else {
_log(c, "Error: Got unexpected NextStep = %v", phone.NextStep)
}
} else if msg.Reason.Value == "local-changes" {
// we currently just ignore local changes on the phone
itemString := formatItemList(msg.Items)
_log(c, "Ignoring reason local-changes - we just don't care yet!")
_log(c, "Phone sent:\n%v", itemString)
} else {
_log(c, "WARNING: Request reason %v is unknown/not implemented yet\n", msg.Reason.Value)
c.Status(http.StatusNoContent)
return
}
if responseItems != nil {
//_log(c, "Sending items:\n");
//printItemList(c, responseItems);
// we always send a response if the handling function above provided items to send to the phone
response := dlsMessage{Message: message{Action: action, Nonce: msg.Nonce, Items: responseItems}}
c.XML(http.StatusOK, response)
}
}
type connDialer struct {
c net.Conn
}
func (cd connDialer) Dial(network, addr string) (net.Conn, error) {
return cd.c, nil
}
func sendContactMe(listenPort, host string) {
conn, err := net.Dial("tcp", net.JoinHostPort(host, "8085"))
if err != nil {
_log(nil, "Connection to %v failed - %v", host, err)
return
}
defer conn.Close()
connIP, _, err := net.SplitHostPort(conn.LocalAddr().String())
if err != nil {
_log(nil, "Failed to parse local addr - this should not happen: %v", err)
return
}
_log(nil, "Sending ContactMe to %v; %v:%v\n", host, connIP, listenPort)
client := http.Client{Transport: &http.Transport{Dial: connDialer{conn}.Dial}}
url := fmt.Sprintf("http://%v:8085/contact_dls.html/ContactDLS", host)
body := strings.NewReader(fmt.Sprintf("ContactMe=true&dls_ip_addr=%v&dls_ip_port=%v", connIP, listenPort))
response, err := client.Post(url, "application/x-www-form-urlencoded", body)
if err != nil {
_log(nil, "ContactMe for %v failed: %v", host, err)
} else if response.StatusCode != 204 {
_log(nil, "Unexpected response from %v for ContactMe: %v", host, response.Status)
} else {
_log(nil, "ContactMe successfully sent to %v\n", host)
}
}
func timerFunc(managedPhones []config.ConfigEntry, manageInterval time.Duration, listenPort string) {
ticker := time.NewTicker(manageInterval)
defer ticker.Stop()
_log(nil, "Sending initial ContactMe to %v phones\n", len(managedPhones))
for {
for _, phone := range managedPhones {
sendContactMe(listenPort, phone.Value)
// XXX optionally wait between individual phones
// this makes the log cleaner for debugging,
// but does not serve any further purpose
time.Sleep(5 * time.Second)
}
<-ticker.C
_log(nil, "Ticker elapsed; sending ContactMe to %v phones\n", len(managedPhones))
}
}
func requireConfigEntry(conf config.ConfigFile, name string) config.ConfigEntry {
entry, err := conf.GetEntry(name)
if err != nil {
_log(nil, "Failed to find required entry %v\n", name)
os.Exit(1)
panic("")
}
return entry
}
func main() {
phoneState = make(map[string]*phoneDesc)
conf, err := config.GetConfigFile(confSrv)
if err != nil {
_log(nil, "Failed to read config file %v: %v", confSrv, err)
os.Exit(1)
}
listenIP := requireConfigEntry(*conf, "listen-ip").Value
listenPort := requireConfigEntry(*conf, "listen-port").Value
tlsCert := requireConfigEntry(*conf, "tls-cert-file").Value
tlsKey := requireConfigEntry(*conf, "tls-key-file").Value
managedPhones := conf.GetFilteredEntries("managed-phones", true)
manageIntervalStr := requireConfigEntry(*conf, "manage-interval").Value
manageInterval, err := time.ParseDuration(manageIntervalStr)
if err != nil {
_log(nil, "Failed to parse manage-interval '%v'\n", manageIntervalStr)
os.Exit(1)
}
go timerFunc(managedPhones, manageInterval, listenPort)
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
_ = router.SetTrustedProxies(nil)
router.GET("/file/:file", getFile)
router.POST("/DeploymentService/LoginService", postLoginService)
err = router.RunTLS(fmt.Sprintf("%v:%v", listenIP, listenPort), tlsCert, tlsKey)
if err != nil {
_log(nil, "Failed to start server: %v", err)
os.Exit(1)
}
}