-
-
Notifications
You must be signed in to change notification settings - Fork 545
/
roaming.go
602 lines (519 loc) · 18.3 KB
/
roaming.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package roaming
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/brocaar/chirpstack-network-server/v3/internal/backend/joinserver"
"github.com/brocaar/chirpstack-network-server/v3/internal/band"
"github.com/brocaar/chirpstack-network-server/v3/internal/config"
downdata "github.com/brocaar/chirpstack-network-server/v3/internal/downlink/data"
"github.com/brocaar/chirpstack-network-server/v3/internal/logging"
"github.com/brocaar/chirpstack-network-server/v3/internal/models"
"github.com/brocaar/chirpstack-network-server/v3/internal/roaming"
"github.com/brocaar/chirpstack-network-server/v3/internal/storage"
updata "github.com/brocaar/chirpstack-network-server/v3/internal/uplink/data"
"github.com/brocaar/chirpstack-network-server/v3/internal/uplink/join"
"github.com/brocaar/lorawan"
"github.com/brocaar/lorawan/backend"
)
// Setup configures the roaming API.
func Setup(c config.Config) error {
roamingConfig := c.Roaming
if roamingConfig.API.Bind == "" {
log.Debug("api/roaming: roaming is disabled")
return nil
}
log.WithFields(log.Fields{
"bind": roamingConfig.API.Bind,
"ca_cert": roamingConfig.API.CACert,
"tls_cert": roamingConfig.API.TLSCert,
"tls_key": roamingConfig.API.TLSKey,
}).Info("api/roaming: starting roaming api")
server := http.Server{
Handler: &API{
netID: c.NetworkServer.NetID,
},
Addr: roamingConfig.API.Bind,
TLSConfig: &tls.Config{},
}
if roamingConfig.API.CACert == "" && roamingConfig.API.TLSCert == "" && roamingConfig.API.TLSKey == "" {
go func() {
err := server.ListenAndServe()
log.WithError(err).Fatal("api/roaming: api server error")
}()
return nil
}
if roamingConfig.API.CACert != "" {
caCert, err := ioutil.ReadFile(roamingConfig.API.CACert)
if err != nil {
return errors.Wrap(err, "read ca certificate error")
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
return errors.New("append ca certificate error")
}
server.TLSConfig.ClientCAs = caCertPool
server.TLSConfig.ClientAuth = tls.RequireAndVerifyClientCert
log.WithFields(log.Fields{
"ca_cert": roamingConfig.API.CACert,
}).Info("api/roaming: roaming api is configured with client-certificate authentication")
}
go func() {
err := server.ListenAndServeTLS(roamingConfig.API.TLSCert, roamingConfig.API.TLSKey)
log.WithError(err).Fatal("api/roaming: api server error")
}()
return nil
}
// API implements the roaming API.
type API struct {
netID lorawan.NetID
}
// NewAPI creates a new API.
func NewAPI(netID lorawan.NetID) *API {
return &API{
netID: netID,
}
}
// ServeHTTP handles a HTTP request.
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// read request body
b, err := ioutil.ReadAll(r.Body)
if err != nil {
log.WithError(err).Error("api/roaming: read request body error")
w.WriteHeader(http.StatusInternalServerError)
return
}
// decode the BasePayload part of the request
var basePL backend.BasePayload
if err := json.Unmarshal(b, &basePL); err != nil {
log.WithError(err).Error("api/roaming: unmarshal request error")
w.WriteHeader(http.StatusBadRequest)
return
}
// set ctx id
ctxID, err := uuid.NewV4()
if err != nil {
log.WithError(err).Error("api/roaming: get uuid error")
w.WriteHeader(http.StatusInternalServerError)
return
}
ctx := context.WithValue(r.Context(), logging.ContextIDKey, ctxID)
// validate SenderID
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
if r.TLS.PeerCertificates[0].Subject.CommonName != basePL.SenderID {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": basePL.SenderID,
"common_name": r.TLS.PeerCertificates[0].Subject.CommonName,
}).Error("roaming: SenderID does not match client-certificate CommonName")
w.WriteHeader(http.StatusUnauthorized)
return
}
}
// Parse Receiver ID (NetID).
var receiverID lorawan.NetID
if err := receiverID.UnmarshalText([]byte(basePL.ReceiverID)); err != nil {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"receiver_id": basePL.ReceiverID,
}).WithError(err).Error("api/roaming: unmarshal ReceiverID as NetID error")
w.WriteHeader(http.StatusBadRequest)
return
}
// validate ReceiverID
if receiverID.String() != a.netID.String() {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"receiver_id": basePL.ReceiverID,
"net_id": a.netID.String(),
}).Error("roaming: ReceiverID does not match NetID of network-server")
w.WriteHeader(http.StatusBadRequest)
return
}
var client backend.Client
if len(basePL.SenderID) >= 16 {
// Parse Sender ID (NetID).
var senderID lorawan.EUI64
if err := senderID.UnmarshalText([]byte(basePL.SenderID)); err != nil {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": basePL.SenderID,
}).WithError(err).Error("api/roaming: unmarshal SenderID as EUI64 error")
w.WriteHeader(http.StatusBadRequest)
return
}
// Get ClientID for Sender ID (JoinEUI)
client, err = joinserver.GetClientForJoinEUI(senderID)
if err != nil {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": basePL.SenderID,
}).WithError(err).Error("api/roaming: get client for JoinEUI error")
w.WriteHeader(http.StatusInternalServerError)
return
}
} else {
// Parse Sender ID (NetID).
var senderID lorawan.NetID
if err := senderID.UnmarshalText([]byte(basePL.SenderID)); err != nil {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": basePL.SenderID,
}).WithError(err).Error("api/roaming: unmarshal SenderID as NetID error")
w.WriteHeader(http.StatusBadRequest)
return
}
// Get ClientID for Sender ID (NetID)
client, err = roaming.GetClientForNetID(senderID)
if err != nil {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": basePL.SenderID,
}).WithError(err).Error("api/roaming: get client for NetID error")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"message_type": basePL.MessageType,
"sender_id": basePL.SenderID,
"receiver_id": basePL.ReceiverID,
"async_client": client.IsAsync(),
"transaction_id": basePL.TransactionID,
}).Info("roaming: api request received")
// handle request
if client.IsAsync() {
newCtx := context.Background()
newCtx = context.WithValue(newCtx, logging.ContextIDKey, ctx.Value(logging.ContextIDKey))
go a.handleAsync(newCtx, client, basePL, b)
} else {
a.handleSync(ctx, client, w, basePL, b)
}
}
func (a *API) handleAsync(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) {
ans, err := a.handleRequest(ctx, client, basePL, b)
if err != nil {
ans = a.getBasePayloadResult(basePL, a.errToResultCode(err), err.Error())
}
if ans == nil {
return
}
if err := client.SendAnswer(ctx, ans); err != nil {
log.WithError(err).WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": client.GetSenderID(),
"receiver_id": client.GetReceiverID(),
"transaction_id": ans.GetBasePayload().TransactionID,
}).Error("api/roaming: sending async response error")
} else {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": ans.GetBasePayload().SenderID,
"receiver_id": ans.GetBasePayload().ReceiverID,
"message_type": ans.GetBasePayload().MessageType,
"result_code": ans.GetBasePayload().Result.ResultCode,
"transaction_id": ans.GetBasePayload().TransactionID,
}).Info("api/roaming: returned async response")
}
}
func (a *API) handleSync(ctx context.Context, client backend.Client, w http.ResponseWriter, basePL backend.BasePayload, b []byte) {
ans, err := a.handleRequest(ctx, client, basePL, b)
if err != nil {
ans = a.getBasePayloadResult(basePL, a.errToResultCode(err), err.Error())
}
if ans == nil {
return
}
bb, err := json.Marshal(ans)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": ans.GetBasePayload().SenderID,
"receiver_id": ans.GetBasePayload().ReceiverID,
"message_type": ans.GetBasePayload().MessageType,
"result_code": ans.GetBasePayload().Result.ResultCode,
"transaction_id": ans.GetBasePayload().TransactionID,
}).Error("api/roaming: marshal json error")
return
}
_, err = w.Write(bb)
if err != nil {
log.WithError(err).WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": ans.GetBasePayload().SenderID,
"receiver_id": ans.GetBasePayload().ReceiverID,
"message_type": ans.GetBasePayload().MessageType,
"result_code": ans.GetBasePayload().Result.ResultCode,
"transaction_id": ans.GetBasePayload().TransactionID,
}).Error("api/roaming: write respone error")
} else {
log.WithFields(log.Fields{
"ctx_id": ctx.Value(logging.ContextIDKey),
"sender_id": ans.GetBasePayload().SenderID,
"receiver_id": ans.GetBasePayload().ReceiverID,
"message_type": ans.GetBasePayload().MessageType,
"result_code": ans.GetBasePayload().Result.ResultCode,
"transaction_id": ans.GetBasePayload().TransactionID,
}).Info("api/roaming: returned response")
}
}
func (a *API) handleRequest(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) (backend.Answer, error) {
var ans backend.Answer
var err error
switch basePL.MessageType {
case backend.PRStartReq:
ans, err = a.handlePRStartReq(ctx, basePL, b)
case backend.PRStartAns:
err = a.handlePRStartAns(ctx, client, basePL, b)
case backend.PRStopReq:
ans, err = a.handlePRStopReq(ctx, basePL, b)
case backend.PRStopAns:
err = a.handlePRStopAns(ctx, client, basePL, b)
case backend.ProfileReq:
ans, err = a.handleProfileReq(ctx, basePL, b)
case backend.ProfileAns:
err = a.handleProfileAns(ctx, client, basePL, b)
case backend.XmitDataReq:
ans, err = a.handleXmitDataReq(ctx, basePL, b)
case backend.XmitDataAns:
err = a.handleXmitDataAns(ctx, client, basePL, b)
case backend.HomeNSAns:
err = a.handleHomeNSAns(ctx, client, basePL, b)
default:
ans = a.getBasePayloadResult(basePL, backend.MalformedRequest, fmt.Sprintf("MessageType %s is not expected", basePL.MessageType))
}
return ans, err
}
func (a *API) handlePRStartAns(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) error {
var pl backend.PRStartAnsPayload
if err := json.Unmarshal(b, &pl); err != nil {
return errors.Wrap(err, "unmarshal json error")
}
if err := client.HandleAnswer(ctx, pl); err != nil {
return errors.Wrap(err, "handle answer error")
}
return nil
}
func (a *API) handlePRStartReq(ctx context.Context, basePL backend.BasePayload, b []byte) (backend.Answer, error) {
// payload
var pl backend.PRStartReqPayload
if err := json.Unmarshal(b, &pl); err != nil {
return nil, errors.Wrap(err, "unmarshal json error")
}
// phypayload
var phy lorawan.PHYPayload
if err := phy.UnmarshalBinary(pl.PHYPayload[:]); err != nil {
return nil, errors.Wrap(err, "unmarshal phypayload error")
}
if phy.MHDR.MType == lorawan.JoinRequest {
return a.handlePRStartReqJoin(ctx, basePL, pl, phy)
} else {
return a.handlePRStartReqData(ctx, basePL, pl, phy)
}
}
func (a *API) handlePRStartReqData(ctx context.Context, basePL backend.BasePayload, pl backend.PRStartReqPayload, phy lorawan.PHYPayload) (backend.Answer, error) {
// decode requester netid
var netID lorawan.NetID
if err := netID.UnmarshalText([]byte(basePL.SenderID)); err != nil {
return nil, errors.Wrap(err, "unmarshal netid error")
}
// frequency in hz
var freq uint32
if pl.ULMetaData.ULFreq != nil {
freq = uint32(*pl.ULMetaData.ULFreq * 1000000)
}
// data-rate
var dr int
if pl.ULMetaData.DataRate != nil {
dr = *pl.ULMetaData.DataRate
}
// channel index
ch, err := band.Band().GetUplinkChannelIndexForFrequencyDR(freq, dr)
if err != nil {
return nil, errors.Wrap(err, "get uplink channel index for frequency and dr error")
}
// get device-session
ds, err := storage.GetDeviceSessionForPHYPayload(ctx, phy, dr, ch)
if err != nil {
return nil, errors.Wrap(err, "get device-session for phypayload error")
}
// lifetime
lifetime := int(roaming.GetPassiveRoamingLifetime(netID) / time.Second)
var fNwkSIntKey *backend.KeyEnvelope
var nwkSKey *backend.KeyEnvelope
if lifetime != 0 {
// sess keys
kekLabel := roaming.GetPassiveRoamingKEKLabel(netID)
var kekKey []byte
if kekLabel != "" {
kekKey, err = roaming.GetKEKKey(kekLabel)
if err != nil {
return nil, errors.Wrap(err, "get kek key error")
}
}
if ds.GetMACVersion() == lorawan.LoRaWAN1_0 {
nwkSKey, err = backend.NewKeyEnvelope(kekLabel, kekKey, ds.NwkSEncKey)
if err != nil {
return nil, errors.Wrap(err, "new key envelope error")
}
} else {
fNwkSIntKey, err = backend.NewKeyEnvelope(kekLabel, kekKey, ds.FNwkSIntKey)
if err != nil {
return nil, errors.Wrap(err, "new key envelope error")
}
}
} else {
// In case of stateless, the payload is directly handled
if err := updata.HandleRoamingHNS(ctx, pl.PHYPayload[:], pl.BasePayload, pl.ULMetaData); err != nil {
return nil, errors.Wrap(err, "handle passive-roaming uplink error")
}
}
ans := backend.PRStartAnsPayload{
BasePayloadResult: a.getBasePayloadResult(basePL, backend.Success, ""),
DevEUI: &ds.DevEUI,
Lifetime: &lifetime,
FNwkSIntKey: fNwkSIntKey,
NwkSKey: nwkSKey,
FCntUp: &ds.FCntUp,
}
return ans, nil
}
func (a *API) handlePRStartReqJoin(ctx context.Context, basePL backend.BasePayload, pl backend.PRStartReqPayload, phy lorawan.PHYPayload) (backend.Answer, error) {
rxInfo, err := roaming.ULMetaDataToRXInfo(pl.ULMetaData)
if err != nil {
return nil, errors.Wrap(err, "ULMetaData to RXInfo error")
}
txInfo, err := roaming.ULMetaDataToTXInfo(pl.ULMetaData)
if err != nil {
return nil, errors.Wrap(err, "ULMetaData to TXInfo error")
}
rxPacket := models.RXPacket{
PHYPayload: phy,
TXInfo: txInfo,
RXInfoSet: rxInfo,
}
if pl.ULMetaData.DataRate != nil {
rxPacket.DR = *pl.ULMetaData.DataRate
}
ans, err := join.HandleStartPRHNS(ctx, pl, rxPacket)
if err != nil {
return nil, errors.Wrap(err, "handle otaa error")
}
bpl := a.getBasePayloadResult(basePL, backend.Success, "")
ans.BasePayload = bpl.BasePayload
ans.Result = bpl.Result
return ans, nil
}
func (a *API) handlePRStopAns(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) error {
var pl backend.PRStopAnsPayload
if err := json.Unmarshal(b, &pl); err != nil {
return errors.Wrap(err, "unmarshal json error")
}
if err := client.HandleAnswer(ctx, pl); err != nil {
return errors.Wrap(err, "handle answer error")
}
return nil
}
func (a *API) handlePRStopReq(ctx context.Context, basePL backend.BasePayload, pl []byte) (backend.Answer, error) {
return nil, nil
}
func (a *API) handleProfileAns(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) error {
var pl backend.ProfileAnsPayload
if err := json.Unmarshal(b, &pl); err != nil {
return errors.Wrap(err, "unmarshal json error")
}
if err := client.HandleAnswer(ctx, pl); err != nil {
return errors.Wrap(err, "handle answer error")
}
return nil
}
func (a *API) handleProfileReq(ctx context.Context, basePL backend.BasePayload, pl []byte) (backend.Answer, error) {
return nil, nil
}
func (a *API) handleXmitDataAns(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) error {
var pl backend.XmitDataAnsPayload
if err := json.Unmarshal(b, &pl); err != nil {
return errors.Wrap(err, "unmarshal json error")
}
if err := client.HandleAnswer(ctx, pl); err != nil {
return errors.Wrap(err, "handle answer error")
}
return nil
}
func (a *API) handleHomeNSAns(ctx context.Context, client backend.Client, basePL backend.BasePayload, b []byte) error {
var pl backend.HomeNSAnsPayload
if err := json.Unmarshal(b, &pl); err != nil {
return errors.Wrap(err, "unmarshal json error")
}
if err := client.HandleAnswer(ctx, pl); err != nil {
return errors.Wrap(err, "handle answer error")
}
return nil
}
func (a *API) handleXmitDataReq(ctx context.Context, basePL backend.BasePayload, b []byte) (backend.Answer, error) {
var pl backend.XmitDataReqPayload
if err := json.Unmarshal(b, &pl); err != nil {
return nil, errors.Wrap(err, "unmarshal json error")
}
if len(pl.PHYPayload[:]) != 0 && pl.ULMetaData != nil {
// Passive Roaming uplink
if err := updata.HandleRoamingHNS(ctx, pl.PHYPayload[:], pl.BasePayload, *pl.ULMetaData); err != nil {
return nil, errors.Wrap(err, "handle passive-roaming uplink error")
}
} else if len(pl.PHYPayload[:]) != 0 && pl.DLMetaData != nil {
// Passive Roaming downlink
if err := downdata.HandleRoamingFNS(ctx, pl); err != nil {
return nil, errors.Wrap(err, "handle passive-roaming downlink error")
}
} else {
return nil, errors.New("unexpected payload")
}
return a.getBasePayloadResult(basePL, backend.Success, ""), nil
}
func (a *API) getBasePayloadResult(basePLReq backend.BasePayload, resCode backend.ResultCode, resDesc string) backend.BasePayloadResult {
var mType backend.MessageType
switch basePLReq.MessageType {
case backend.PRStartReq:
mType = backend.PRStartAns
case backend.PRStopReq:
mType = backend.PRStopAns
case backend.ProfileReq:
mType = backend.ProfileAns
case backend.XmitDataReq:
mType = backend.XmitDataAns
}
return backend.BasePayloadResult{
BasePayload: backend.BasePayload{
ProtocolVersion: basePLReq.ProtocolVersion,
SenderID: basePLReq.ReceiverID,
ReceiverID: basePLReq.SenderID,
TransactionID: basePLReq.TransactionID,
MessageType: mType,
},
Result: backend.Result{
ResultCode: resCode,
Description: resDesc,
},
}
}
func (a *API) errToResultCode(err error) backend.ResultCode {
switch {
case errors.Is(err, storage.ErrDoesNotExist):
return backend.UnknownDevAddr
case errors.Is(err, storage.ErrFrameCounterReset),
errors.Is(err, storage.ErrFrameCounterRetransmission),
errors.Is(err, storage.ErrInvalidMIC):
return backend.MICFailed
default:
return backend.Other
}
}