aboutsummaryrefslogtreecommitdiff
path: root/src/gnunet/service/gns/block_handler.go
blob: b00fac2a1bfca05a34cb048e854c6d2086c5e1ad (plain) (blame)
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
603
604
605
606
607
608
609
610
611
612
613
614
615
// This file is part of gnunet-go, a GNUnet-implementation in Golang.
// Copyright (C) 2019-2022 Bernd Fix  >Y<
//
// gnunet-go is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// gnunet-go is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL3.0-or-later

package gns

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"

	"gnunet/crypto"
	"gnunet/enums"
	"gnunet/service/dht/blocks"
	"gnunet/service/gns/rr"
	"gnunet/util"

	"github.com/bfix/gospel/logger"
)

// HdlrInst is the type for functions that instantiate custom block handlers.
type HdlrInst func(*blocks.ResourceRecord, []string) (BlockHandler, error)

// Error codes
var (
	ErrInvalidRecordType = fmt.Errorf("invalid resource record type")
	ErrInvalidRecordBody = fmt.Errorf("invalid resource record body")
	ErrInvalidZoneKey    = fmt.Errorf("invalid zone key resource record")
	ErrInvalidCNAME      = fmt.Errorf("invalid CNAME resource record")
	ErrInvalidVPN        = fmt.Errorf("invalid VPN resource record")
	ErrInvalidRecordMix  = fmt.Errorf("invalid mix of RR types in block")
	ErrBlockHandler      = fmt.Errorf("internal block handler failure")
)

// Mapping of RR types to BlockHandler instanciation functions
var (
	customHandler = map[enums.GNSType]HdlrInst{
		enums.GNS_TYPE_PKEY:      NewZoneHandler,
		enums.GNS_TYPE_EDKEY:     NewZoneHandler,
		enums.GNS_TYPE_GNS2DNS:   NewGns2DnsHandler,
		enums.GNS_TYPE_BOX:       NewBoxHandler,
		enums.GNS_TYPE_LEHO:      NewLehoHandler,
		enums.GNS_TYPE_DNS_CNAME: NewCnameHandler,
		enums.GNS_TYPE_VPN:       NewVpnHandler,
	}
)

//======================================================================
// GNS blocks that contain special records (PKEY, GNS2DNS, BOX, LEHO...)
// require special treatment with respect to other resource records with
// different types in the same block. Usually only certain other types
// (or none at all) are allowed.
//======================================================================

// BlockHandler interface.
type BlockHandler interface {
	// AddRecord inserts an associated RR into the BlockHandler for (later)
	// processing. The handler can inspect the remaining labels in a path
	// if required. The method returns an error if a record is not accepted
	// by the block handler (RR not of required type).
	AddRecord(rr *blocks.ResourceRecord, labels []string) error

	// Coexist checks if a custom block handler can co-exist with other
	// resource records in the same block. 'cm' maps the resource type
	// to an integer count (how many records of a type are present in the
	// GNS block).
	Coexist(cm util.Counter[enums.GNSType]) bool

	// Records returns a list of RR of the given types associated with
	// the custom handler
	Records(kind RRTypeList) *blocks.RecordSet

	// Name returns the human-readable name of the handler
	Name() string
}

//----------------------------------------------------------------------
// Manage list of block handlers
// Under normal circumstances there is only one (or none) block handler
// per block, but future constructs may allow multiple block handlers
// to be present. The block handler list implements the BlockHandler
// interface.
// The BlockHandlerList maintains a map of actually instantiated handlers
// (indexed by record type) and a list of record types (with occurrence
// count) in the block.
// The instance is also responsible for any required post-processing like
// filtering out expired records (and eventually "activating" associated
// shadow records collect from the same block).
//----------------------------------------------------------------------

// BlockHandlerList is a list of block handlers instantiated.
type BlockHandlerList struct {
	list   map[enums.GNSType]BlockHandler // list of handler instances
	counts util.Counter[enums.GNSType]    // count number of RRs by type
}

// NewBlockHandlerList instantiates an a list of active block handlers
// for a given set of records (GNS block).
func NewBlockHandlerList(records []*blocks.ResourceRecord, labels []string) (*BlockHandlerList, []*blocks.ResourceRecord, error) {
	// initialize block handler list
	hl := &BlockHandlerList{
		list:   make(map[enums.GNSType]BlockHandler),
		counts: make(util.Counter[enums.GNSType]),
	}

	// first pass: build list of shadow records in this block
	shadows := make([]*blocks.ResourceRecord, 0)
	for _, rec := range records {
		// filter out shadow records...
		if (rec.Flags & enums.GNS_FLAG_SHADOW) != 0 {
			shadows = append(shadows, rec)
		}
	}
	// second pass: normalize block by filtering out expired records (and
	// replacing them with shadow records if available
	active := make([]*blocks.ResourceRecord, 0)
	for _, rec := range records {
		// don't process shadow records again
		if (rec.Flags & enums.GNS_FLAG_SHADOW) != 0 {
			continue
		}
		// check for expired record
		if rec.Expire.Expired() {
			// do we have an associated shadow record?
			for _, shadow := range shadows {
				if shadow.RType == rec.RType && !shadow.Expire.Expired() {
					// deliver un-expired shadow record instead.
					shadow.Flags &^= enums.GNS_FLAG_SHADOW
					active = append(active, shadow)
				}
			}
		} else {
			active = append(active, rec)
		}
	}

	// Third pass: Traverse active list and build list of handler instances.
	for _, rec := range active {
		// update counter map for non-supplemental records
		if (rec.Flags & enums.GNS_FLAG_SUPPL) != 0 {
			logger.Printf(logger.DBG, "[gns] handler_list: skip %v\n", rec)
			continue
		}
		rrType := rec.RType
		hl.counts.Add(rrType)

		// check for custom handler type
		if creat, ok := customHandler[rrType]; ok {
			// check if a handler for given type already exists
			var (
				hdlr BlockHandler
				err  error
			)
			if hdlr, ok = hl.list[rrType]; ok {
				// add record to existing handler
				if err = hdlr.AddRecord(rec, labels); err != nil {
					return nil, active, err
				}
				continue
			}
			// create a new handler instance
			if hdlr, err = creat(rec, labels); err != nil {
				return nil, active, err
			}
			// store handler in list
			hl.list[rrType] = hdlr
		}
	}

	// Check if all registered handlers in list can co-exist with
	// all the other records of varying type
	for _, hdlr := range hl.list {
		if !hdlr.Coexist(hl.counts) {
			logger.Printf(logger.ERROR, "[gns] %s.Coexist() failed!\n", hdlr.Name())
			return nil, active, ErrInvalidRecordMix
		}
	}
	// return assembled handler list
	return hl, active, nil
}

// GetHandler returns a BlockHandler for the given GNS block type.
// If more than one type is given, the first matching handler is
// returned.
func (hl *BlockHandlerList) GetHandler(types ...enums.GNSType) BlockHandler {
	for _, t := range types {
		// return handler for given type if it exists
		if hdlr, ok := hl.list[t]; ok {
			return hdlr
		}
	}
	return nil
}

// FinalizeRecord post-processes records
func (hl *BlockHandlerList) FinalizeRecord(rec *blocks.ResourceRecord) *blocks.ResourceRecord {
	// no implementation yet
	return rec
}

//----------------------------------------------------------------------
// Zone key handler: Only one zone key as sole record in a block
//----------------------------------------------------------------------

// ZoneKeyHandler implementing the BlockHandler interface
type ZoneKeyHandler struct {
	ztype enums.GNSType          // zone type
	zkey  *crypto.ZoneKey        // Zone key
	rec   *blocks.ResourceRecord // associated recource record
}

// NewZoneHandler returns a new BlockHandler instance
func NewZoneHandler(rec *blocks.ResourceRecord, labels []string) (BlockHandler, error) {
	// check if we have an implementation for the zone type
	if crypto.GetImplementation(rec.RType) == nil {
		return nil, ErrInvalidRecordType
	}
	// assemble handler
	h := &ZoneKeyHandler{
		ztype: rec.RType,
		zkey:  nil,
	}
	// add the record to the handler
	if err := h.AddRecord(rec, labels); err != nil {
		return nil, err
	}
	return h, nil
}

// AddRecord inserts a PKEY record into the handler.
func (h *ZoneKeyHandler) AddRecord(rec *blocks.ResourceRecord, labels []string) (err error) {
	// check record type
	if rec.RType != h.ztype {
		return ErrInvalidRecordType
	}
	// check for sole zone key record in block
	if h.zkey != nil {
		return ErrInvalidZoneKey
	}
	// set zone key
	h.zkey, err = crypto.NewZoneKey(rec.Data)
	if err != nil {
		return
	}
	h.rec = rec
	return
}

// Coexist return a flag indicating how a resource record of a given type
// is to be treated (see BlockHandler interface)
func (h *ZoneKeyHandler) Coexist(cm util.Counter[enums.GNSType]) bool {
	// only one type (GNS_TYPE_PKEY) is present
	return len(cm) == 1 && cm.Num(enums.GNS_TYPE_PKEY) == 1
}

// Records returns a list of RR of the given type associated with this handler
func (h *ZoneKeyHandler) Records(kind RRTypeList) *blocks.RecordSet {
	rs := blocks.NewRecordSet()
	if kind.HasType(enums.GNS_TYPE_PKEY) {
		rs.AddRecord(h.rec)
	}
	return rs
}

// Name returns the human-readable name of the handler.
func (h *ZoneKeyHandler) Name() string {
	return "PKEY_Handler"
}

//----------------------------------------------------------------------
// GNS2DNS handler
//----------------------------------------------------------------------

// Gns2DnsHandler implementing the BlockHandler interface
type Gns2DnsHandler struct {
	Query   string                   // DNS query name
	Servers []string                 // DNS servers to ask
	recs    []*blocks.ResourceRecord // list of rersource records
}

// NewGns2DnsHandler returns a new BlockHandler instance
func NewGns2DnsHandler(rec *blocks.ResourceRecord, labels []string) (BlockHandler, error) {
	if rec.RType != enums.GNS_TYPE_GNS2DNS {
		return nil, ErrInvalidRecordType
	}
	h := &Gns2DnsHandler{
		Query:   "",
		Servers: make([]string, 0),
		recs:    make([]*blocks.ResourceRecord, 0),
	}
	if err := h.AddRecord(rec, labels); err != nil {
		return nil, err
	}
	return h, nil
}

// AddRecord inserts a GNS2DNS record into the handler.
func (h *Gns2DnsHandler) AddRecord(rec *blocks.ResourceRecord, labels []string) error {
	if rec.RType != enums.GNS_TYPE_GNS2DNS {
		return ErrInvalidRecordType
	}
	logger.Printf(logger.DBG, "[gns] GNS2DNS data: %s\n", hex.EncodeToString(rec.Data))

	// extract list of names in DATA block:
	next, dnsQuery := DNSNameFromBytes(rec.Data, 0)
	dnsServer := string(rec.Data[next : len(rec.Data)-1])
	logger.Printf(logger.DBG, "[gns] GNS2DNS query '%s'@'%s'\n", dnsQuery, dnsServer)
	if len(dnsServer) == 0 || len(dnsQuery) == 0 {
		return ErrInvalidRecordBody
	}

	// check if all GNS2DNS records refer to the same query name
	if len(h.Servers) == 0 {
		h.Query = dnsQuery
	}
	if dnsQuery != h.Query {
		return ErrInvalidRecordBody
	}
	h.Servers = append(h.Servers, dnsServer)
	h.recs = append(h.recs, rec)
	return nil
}

// Coexist return a flag indicating how a resource record of a given type
// is to be treated (see BlockHandler interface)
func (h *Gns2DnsHandler) Coexist(cm util.Counter[enums.GNSType]) bool {
	// only one type (GNS_TYPE_GNS2DNS) is present
	return len(cm) == 1 && cm.Num(enums.GNS_TYPE_GNS2DNS) > 0
}

// Records returns a list of RR of the given type associated with this handler
func (h *Gns2DnsHandler) Records(kind RRTypeList) *blocks.RecordSet {
	rs := blocks.NewRecordSet()
	if kind.HasType(enums.GNS_TYPE_GNS2DNS) {
		for _, rec := range h.recs {
			rs.AddRecord(rec)
		}
	}
	return rs
}

// Name returns the human-readable name of the handler.
func (h *Gns2DnsHandler) Name() string {
	return "GNS2DNS_Handler"
}

//----------------------------------------------------------------------
// BOX handler
//----------------------------------------------------------------------

// Box record for handler logic
type Box struct {
	rr.BOX
	key string                 // map key for box instance
	rec *blocks.ResourceRecord // originating RR
}

// BoxHandler implementing the BlockHandler interface
type BoxHandler struct {
	boxes map[string]*Box // map of found boxes
}

// NewBoxHandler returns a new BlockHandler instance
func NewBoxHandler(rec *blocks.ResourceRecord, labels []string) (BlockHandler, error) {
	if rec.RType != enums.GNS_TYPE_BOX {
		return nil, ErrInvalidRecordType
	}
	h := &BoxHandler{
		boxes: make(map[string]*Box),
	}
	if err := h.AddRecord(rec, labels); err != nil {
		return nil, err
	}
	return h, nil
}

// AddRecord inserts a BOX record into the handler.
func (h *BoxHandler) AddRecord(rec *blocks.ResourceRecord, labels []string) error {
	if rec.RType != enums.GNS_TYPE_BOX {
		return ErrInvalidRecordType
	}
	logger.Printf(logger.DBG, "[box-rr] for labels %v\n", labels)
	// check if we need to process the BOX record:
	// (1) only two remaining labels
	if len(labels) != 2 {
		return nil
	}
	// (2) remaining labels must start with '_'
	if labels[0][0] != '_' || labels[1][0] != '_' {
		return nil
	}
	// (3) check of "svc" and "proto" match values in the BOX
	hsh := sha256.Sum256(rec.Data)
	box := &Box{
		BOX: *rr.NewBOX(rec.Data),
		key: hex.EncodeToString(hsh[:8]),
		rec: rec,
	}
	if box.Matches(labels) {
		logger.Println(logger.DBG, "[box-rr] MATCH -- adding record")
		h.boxes[box.key] = box
	}
	return nil
}

// Coexist return a flag indicating how a resource record of a given type
// is to be treated (see BlockHandler interface)
func (h *BoxHandler) Coexist(cm util.Counter[enums.GNSType]) bool {
	// anything goes...
	return true
}

// Records returns a list of RR of the given type associated with this handler
func (h *BoxHandler) Records(kind RRTypeList) *blocks.RecordSet {
	rs := blocks.NewRecordSet()
	for _, box := range h.boxes {
		if kind.HasType(box.Type) {
			// valid box found: assemble new resource record.
			rr := new(blocks.ResourceRecord)
			rr.Expire = box.rec.Expire
			rr.Flags = box.rec.Flags
			rr.RType = box.Type
			rr.Size = uint32(len(box.RR))
			rr.Data = box.RR
			rs.AddRecord(rr)
		}
	}
	return rs
}

// Name returns the human-readable name of the handler.
func (h *BoxHandler) Name() string {
	return "BOX_Handler"
}

//----------------------------------------------------------------------
// LEHO handler
//----------------------------------------------------------------------

// LehoHandler implementing the BlockHandler interface
type LehoHandler struct {
	name string
	rec  *blocks.ResourceRecord
}

// NewLehoHandler returns a new BlockHandler instance
func NewLehoHandler(rec *blocks.ResourceRecord, labels []string) (BlockHandler, error) {
	if rec.RType != enums.GNS_TYPE_LEHO {
		return nil, ErrInvalidRecordType
	}
	h := &LehoHandler{
		name: "",
	}
	if err := h.AddRecord(rec, labels); err != nil {
		return nil, err
	}
	return h, nil
}

// AddRecord inserts a LEHO record into the handler.
func (h *LehoHandler) AddRecord(rec *blocks.ResourceRecord, labels []string) error {
	if rec.RType != enums.GNS_TYPE_LEHO {
		return ErrInvalidRecordType
	}
	h.name = string(rec.Data)
	h.rec = rec
	return nil
}

// Coexist return a flag indicating how a resource record of a given type
// is to be treated (see BlockHandler interface)
func (h *LehoHandler) Coexist(cm util.Counter[enums.GNSType]) bool {
	// requires exactly one LEHO and any number of other records.
	return cm.Num(enums.GNS_TYPE_LEHO) == 1
}

// Records returns a list of RR of the given type associated with this handler
func (h *LehoHandler) Records(kind RRTypeList) *blocks.RecordSet {
	rs := blocks.NewRecordSet()
	if kind.HasType(enums.GNS_TYPE_LEHO) {
		rs.AddRecord(h.rec)
	}
	return rs
}

// Name returns the human-readable name of the handler.
func (h *LehoHandler) Name() string {
	return "LEHO_Handler"
}

//----------------------------------------------------------------------
// CNAME handler
//----------------------------------------------------------------------

// CnameHandler implementing the BlockHandler interface
type CnameHandler struct {
	name string
	rec  *blocks.ResourceRecord
}

// NewCnameHandler returns a new BlockHandler instance
func NewCnameHandler(rec *blocks.ResourceRecord, labels []string) (BlockHandler, error) {
	if rec.RType != enums.GNS_TYPE_DNS_CNAME {
		return nil, ErrInvalidRecordType
	}
	h := &CnameHandler{
		name: "",
	}
	if err := h.AddRecord(rec, labels); err != nil {
		return nil, err
	}
	return h, nil
}

// AddRecord inserts a CNAME record into the handler.
func (h *CnameHandler) AddRecord(rec *blocks.ResourceRecord, labels []string) error {
	if rec.RType != enums.GNS_TYPE_DNS_CNAME {
		return ErrInvalidRecordType
	}
	if h.rec != nil {
		return ErrInvalidCNAME
	}
	_, h.name = DNSNameFromBytes(rec.Data, 0)
	h.rec = rec
	return nil
}

// Coexist return a flag indicating how a resource record of a given type
// is to be treated (see BlockHandler interface)
func (h *CnameHandler) Coexist(cm util.Counter[enums.GNSType]) bool {
	// only a single CNAME allowed
	return len(cm) == 1 && cm.Num(enums.GNS_TYPE_DNS_CNAME) == 1
}

// Records returns a list of RR of the given type associated with this handler
func (h *CnameHandler) Records(kind RRTypeList) *blocks.RecordSet {
	rs := blocks.NewRecordSet()
	if kind.HasType(enums.GNS_TYPE_DNS_CNAME) {
		rs.AddRecord(h.rec)
	}
	return rs
}

// Name returns the human-readable name of the handler.
func (h *CnameHandler) Name() string {
	return "CNAME_Handler"
}

//----------------------------------------------------------------------
// VPN handler
//----------------------------------------------------------------------

// VpnHandler implementing the BlockHandler interface
type VpnHandler struct {
	rec *blocks.ResourceRecord
}

// NewVpnHandler returns a new BlockHandler instance
func NewVpnHandler(rec *blocks.ResourceRecord, labels []string) (BlockHandler, error) {
	if rec.RType != enums.GNS_TYPE_VPN {
		return nil, ErrInvalidRecordType
	}
	h := &VpnHandler{}
	if err := h.AddRecord(rec, labels); err != nil {
		return nil, err
	}
	return h, nil
}

// AddRecord inserts a VPN record into the handler.
func (h *VpnHandler) AddRecord(rec *blocks.ResourceRecord, labels []string) error {
	if rec.RType != enums.GNS_TYPE_VPN {
		return ErrInvalidRecordType
	}
	if h.rec != nil {
		return ErrInvalidVPN
	}
	h.rec = rec
	return nil
}

// Coexist return a flag indicating how a resource record of a given type
// is to be treated (see BlockHandler interface)
func (h *VpnHandler) Coexist(cm util.Counter[enums.GNSType]) bool {
	// anything goes
	return true
}

// Records returns a list of RR of the given type associated with this handler
func (h *VpnHandler) Records(kind RRTypeList) *blocks.RecordSet {
	rs := blocks.NewRecordSet()
	if kind.HasType(enums.GNS_TYPE_VPN) {
		rs.AddRecord(h.rec)
	}
	return rs
}

// Name returns the human-readable name of the handler.
func (h *VpnHandler) Name() string {
	return "VPN_Handler"
}