-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfelica.go
More file actions
698 lines (571 loc) · 21.6 KB
/
felica.go
File metadata and controls
698 lines (571 loc) · 21.6 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// Copyright 2026 The Zaparoo Project Contributors.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pn532
import (
"context"
"errors"
"fmt"
)
// FeliCa command constants based on JIS X 6319-4 specification
const (
feliCaCmdPolling = 0x00
feliCaCmdReadWithoutEncryption = 0x06
feliCaCmdWriteWithoutEncryption = 0x08
feliCaCmdAuthentication = 0x0A
feliCaCmdRequestResponse = 0x04
feliCaCmdRequestService = 0x02
)
// FeliCa system codes
const (
feliCaSystemCodeNDEF = 0x12FC // NFC Forum Type 3 Tag
feliCaSystemCodeCommon = 0xFFFF // Common system code for polling
feliCaSystemCodeWildcard = 0xFFFF // Wildcard for polling all cards
)
// FeliCa service codes for NDEF operations
const (
feliCaServiceCodeNDEFRead = 0x000B // NDEF read service
feliCaServiceCodeNDEFWrite = 0x0009 // NDEF write service
)
// FeliCa constants
const (
feliCaBlockSize = 16 // FeliCa uses 16-byte blocks
feliCaIDmLength = 8 // IDm (Manufacture ID) is 8 bytes
feliCaPMmLength = 8 // PMm (Manufacture Parameter) is 8 bytes
)
// FeliCaTag represents a FeliCa NFC tag implementing the Tag interface
// Field ordering optimized for memory alignment to reduce struct size from 96 to 80 bytes
type FeliCaTag struct {
idm []byte
pmm []byte
BaseTag
blockSize int
systemCode uint16
serviceCode uint16
}
// NewFeliCaTag creates a new FeliCa tag instance from polling response data
// targetData should contain the FeliCa polling response (POL_RES)
func NewFeliCaTag(device *Device, targetData []byte) (*FeliCaTag, error) {
if len(targetData) < 18 {
return nil, fmt.Errorf("FeliCa target data too short: %d bytes, need at least 18", len(targetData))
}
// Parse FeliCa polling response structure:
// Byte 0: Response Code (0x01 for polling response)
// Byte 1: IDm[0]
// ...
// Byte 8: IDm[7]
// Byte 9: PMm[0]
// ...
// Byte 16: PMm[7]
// Byte 17-18: System Code (optional, depends on response length)
// Extract IDm (8 bytes) - starts at byte 1
idm := make([]byte, feliCaIDmLength)
copy(idm, targetData[1:9])
// Extract PMm (8 bytes) - starts at byte 9
pmm := make([]byte, feliCaPMmLength)
copy(pmm, targetData[9:17])
// Extract system code if present (last 2 bytes, big endian)
systemCode := uint16(0xFFFF) // Default wildcard
if len(targetData) >= 19 {
systemCode = uint16(targetData[17])<<8 | uint16(targetData[18])
}
tag := &FeliCaTag{
BaseTag: BaseTag{
device: device,
tagType: TagTypeFeliCa,
uid: idm, // Use IDm as UID for FeliCa
sak: 0, // FeliCa doesn't use SAK
},
blockSize: feliCaBlockSize,
idm: idm,
pmm: pmm,
systemCode: systemCode,
serviceCode: feliCaServiceCodeNDEFRead, // Default to NDEF read
}
return tag, nil
}
// GetIDm returns the Manufacture ID (IDm) of the FeliCa tag
func (f *FeliCaTag) GetIDm() []byte {
return f.idm
}
// GetPMm returns the Manufacture Parameter (PMm) of the FeliCa tag
func (f *FeliCaTag) GetPMm() []byte {
return f.pmm
}
// GetSystemCode returns the current system code
func (f *FeliCaTag) GetSystemCode() uint16 {
return f.systemCode
}
// SetSystemCode sets the system code for operations
func (f *FeliCaTag) SetSystemCode(systemCode uint16) {
f.systemCode = systemCode
}
// GetServiceCode returns the current service code
func (f *FeliCaTag) GetServiceCode() uint16 {
return f.serviceCode
}
// SetServiceCode sets the service code for operations
func (f *FeliCaTag) SetServiceCode(serviceCode uint16) {
f.serviceCode = serviceCode
}
// ReadBlock reads a single block from the FeliCa tag
// For FeliCa, block numbers are 16-bit, but we use uint8 for interface compatibility
// TODO: Consider extending interface for 16-bit block addressing
func (f *FeliCaTag) ReadBlock(ctx context.Context, block uint8) ([]byte, error) {
return f.ReadBlockExtended(ctx, uint16(block))
}
// ReadBlockExtended reads a single block using 16-bit block addressing
func (f *FeliCaTag) ReadBlockExtended(ctx context.Context, block uint16) ([]byte, error) {
// FeliCa Read Without Encryption command structure:
// Command: 0x06
// IDm: 8 bytes (card identifier)
// Service Count: 1 byte (number of services)
// Service Code List: 2 bytes per service
// Block Count: 1 byte (number of blocks to read)
// Block List: 2 or 3 bytes per block depending on format
cmd := make([]byte, 0, 1+len(f.idm)+7)
cmd = append(cmd, feliCaCmdReadWithoutEncryption)
// Add IDm (8 bytes)
cmd = append(cmd, f.idm...)
// Service count, service code, block count, and block list element
cmd = append(cmd, 0x01, // Service count (1 service)
byte(f.serviceCode&0xFF), byte((f.serviceCode>>8)&0xFF), // Service code (2 bytes, little endian)
0x01, // Block count (1 block)
// Block list element (3 bytes for 16-bit block addressing)
// Format: 0x80 | (block >> 8), block & 0xFF, 0x00
0x80|byte((block>>8)&0x0F), byte(block&0xFF), 0x00)
// Send command via data exchange
response, err := f.device.SendDataExchange(ctx, cmd)
if err != nil {
return nil, fmt.Errorf("FeliCa read command failed: %w", err)
}
// Check response format
if len(response) < 12 {
return nil, fmt.Errorf("FeliCa read response too short: %d bytes", len(response))
}
// Response format:
// Response Code: 1 byte (0x07 for Read Without Encryption response)
// IDm: 8 bytes
// Status Flag 1: 1 byte
// Status Flag 2: 1 byte
// Block Data: 16 bytes per block
if response[0] != 0x07 {
return nil, fmt.Errorf("invalid FeliCa read response code: 0x%02X", response[0])
}
// Check status flags
statusFlag1 := response[9]
statusFlag2 := response[10]
if statusFlag1 != 0x00 || statusFlag2 != 0x00 {
return nil, fmt.Errorf("FeliCa read failed with status: 0x%02X%02X", statusFlag1, statusFlag2)
}
// Extract block data (starts at byte 11)
if len(response) < 11+feliCaBlockSize {
return nil, errors.New("FeliCa read response missing block data")
}
blockData := make([]byte, feliCaBlockSize)
copy(blockData, response[11:11+feliCaBlockSize])
return blockData, nil
}
// WriteBlock writes a single block to the FeliCa tag
// For FeliCa, block numbers are 16-bit, but we use uint8 for interface compatibility
func (f *FeliCaTag) WriteBlock(ctx context.Context, block uint8, data []byte) error {
return f.WriteBlockExtended(ctx, uint16(block), data)
}
// WriteBlockExtended writes a single block using 16-bit block addressing
func (f *FeliCaTag) WriteBlockExtended(ctx context.Context, block uint16, data []byte) error {
// Validate data length
if len(data) != feliCaBlockSize {
return fmt.Errorf("FeliCa block data must be exactly %d bytes, got %d", feliCaBlockSize, len(data))
}
// FeliCa Write Without Encryption command structure:
// Command: 0x08
// IDm: 8 bytes (card identifier)
// Service Count: 1 byte (number of services)
// Service Code List: 2 bytes per service
// Block Count: 1 byte (number of blocks to write)
// Block List: 2 or 3 bytes per block depending on format
// Block Data: 16 bytes per block
cmd := make([]byte, 0, 1+len(f.idm)+7+len(data))
cmd = append(cmd, feliCaCmdWriteWithoutEncryption)
// Add IDm (8 bytes)
cmd = append(cmd, f.idm...)
// Service count, service code, block count, and block list element
cmd = append(cmd, 0x01, // Service count (1 service)
byte(f.serviceCode&0xFF), byte((f.serviceCode>>8)&0xFF), // Service code (2 bytes, little endian)
0x01, // Block count (1 block)
// Block list element (3 bytes for 16-bit block addressing)
// Format: 0x80 | (block >> 8), block & 0xFF, 0x00
0x80|byte((block>>8)&0x0F), byte(block&0xFF), 0x00)
// Add block data (16 bytes)
cmd = append(cmd, data...)
// Send command via data exchange
response, err := f.device.SendDataExchange(ctx, cmd)
if err != nil {
return fmt.Errorf("FeliCa write command failed: %w", err)
}
// Check response format
if len(response) < 11 {
return fmt.Errorf("FeliCa write response too short: %d bytes", len(response))
}
// Response format:
// Response Code: 1 byte (0x09 for Write Without Encryption response)
// IDm: 8 bytes
// Status Flag 1: 1 byte
// Status Flag 2: 1 byte
if response[0] != 0x09 {
return fmt.Errorf("invalid FeliCa write response code: 0x%02X", response[0])
}
// Check status flags
statusFlag1 := response[9]
statusFlag2 := response[10]
if statusFlag1 != 0x00 || statusFlag2 != 0x00 {
return fmt.Errorf("FeliCa write failed with status: 0x%02X%02X", statusFlag1, statusFlag2)
}
return nil
}
// ReadNDEF reads NDEF data from the FeliCa tag
// Uses system code 0x12FC and service code 0x000B for NFC Forum Type 3 compliance
func (f *FeliCaTag) ReadNDEF(ctx context.Context) (*NDEFMessage, error) {
// Switch to NDEF system code and read service code
originalSystemCode := f.systemCode
originalServiceCode := f.serviceCode
f.systemCode = feliCaSystemCodeNDEF
f.serviceCode = feliCaServiceCodeNDEFRead
// Restore original codes when done
defer func() {
f.systemCode = originalSystemCode
f.serviceCode = originalServiceCode
}()
// Step 1: Read Attribute Information Block (Block 0)
aibData, err := f.ReadBlockExtended(ctx, 0)
if err != nil {
return nil, fmt.Errorf("failed to read attribute information block: %w", err)
}
// Step 2: Validate AIB structure and checksum
if len(aibData) < 16 {
return nil, fmt.Errorf("attribute information block too short: %d bytes", len(aibData))
}
if !f.validateAIB(aibData) {
return nil, errors.New("invalid attribute information block or checksum mismatch")
}
// Step 3: Check version and permissions
version := aibData[0]
if version != 0x10 {
return nil, fmt.Errorf("unsupported NDEF version: 0x%02X", version)
}
rwFlag := aibData[10]
// Note: rwFlag indicates read-only status, but we can still read NDEF regardless
_ = rwFlag
// Step 4: Extract NDEF length (Ln) - 3 bytes big endian at bytes 11-13
ndefLength := uint32(aibData[11])<<16 | uint32(aibData[12])<<8 | uint32(aibData[13])
if ndefLength == 0 {
// Empty NDEF message
return &NDEFMessage{Records: []NDEFRecord{}}, nil
}
// Step 5: Calculate blocks needed to read
blocksNeeded := (ndefLength + feliCaBlockSize - 1) / feliCaBlockSize
// Step 6: Read NDEF data blocks starting from Block 1
if blocksNeeded > 0xFFFF {
return nil, fmt.Errorf("NDEF data too large: requires %d blocks but maximum is %d", blocksNeeded, 0xFFFF)
}
ndefData := make([]byte, 0, blocksNeeded*feliCaBlockSize)
for block := uint16(1); uint32(block) <= blocksNeeded; block++ {
blockData, err := f.ReadBlockExtended(ctx, block)
if err != nil {
return nil, fmt.Errorf("failed to read NDEF block %d: %w", block, err)
}
ndefData = append(ndefData, blockData...)
}
// Step 7: Trim to actual NDEF length
if len(ndefData) < int(ndefLength) {
return nil, fmt.Errorf("read insufficient NDEF data: got %d bytes, expected %d", len(ndefData), ndefLength)
}
actualNdefData := ndefData[:ndefLength]
// Step 8: Parse NDEF data using existing parser
return ParseNDEFMessage(actualNdefData)
}
// WriteNDEF writes NDEF data to the FeliCa tag
// Uses system code 0x12FC and service code 0x0009 for NFC Forum Type 3 compliance
func (f *FeliCaTag) WriteNDEF(ctx context.Context, message *NDEFMessage) error {
if message == nil {
return errors.New("NDEF message cannot be nil")
}
// Switch to NDEF system code and write service code
originalSystemCode, originalServiceCode := f.systemCode, f.serviceCode
f.systemCode = feliCaSystemCodeNDEF
defer f.restoreSystemCodes(originalSystemCode, originalServiceCode)
return f.executeNDEFWrite(ctx, message)
}
// restoreSystemCodes restores the original system and service codes
func (f *FeliCaTag) restoreSystemCodes(systemCode, serviceCode uint16) {
f.systemCode = systemCode
f.serviceCode = serviceCode
}
// executeNDEFWrite performs the NDEF write operation
func (f *FeliCaTag) executeNDEFWrite(ctx context.Context, message *NDEFMessage) error {
// Step 1: Read and validate current AIB
currentAIB, err := f.readAndValidateAIB(ctx)
if err != nil {
return err
}
// Step 2: Validate write permissions
if writeErr := f.validateWritePermissions(currentAIB); writeErr != nil {
return writeErr
}
// Step 3: Build and validate NDEF data
ndefData, err := f.buildAndValidateNDEFData(message, currentAIB)
if err != nil {
return err
}
// Step 4: Write NDEF data to blocks
if err := f.writeNDEFDataToBlocks(ctx, ndefData); err != nil {
return err
}
// Step 5: Update AIB with new length
return f.updateAIBWithNDEFLength(ctx, currentAIB, len(ndefData))
}
// readAndValidateAIB reads and validates the Attribute Information Block
func (f *FeliCaTag) readAndValidateAIB(ctx context.Context) ([]byte, error) {
f.serviceCode = feliCaServiceCodeNDEFRead
currentAIB, err := f.ReadBlockExtended(ctx, 0)
if err != nil {
return nil, fmt.Errorf("failed to read current attribute information block: %w", err)
}
if !f.validateAIB(currentAIB) {
return nil, errors.New("current attribute information block is invalid")
}
return currentAIB, nil
}
// buildAndValidateNDEFData builds NDEF message data and validates size constraints
func (f *FeliCaTag) buildAndValidateNDEFData(message *NDEFMessage, currentAIB []byte) ([]byte, error) {
var ndefData []byte
if len(message.Records) > 0 {
data, err := BuildNDEFMessageEx(message.Records)
if err != nil {
return nil, fmt.Errorf("failed to build NDEF message: %w", err)
}
ndefData = data
}
// Validate data size against tag capacity
maxBlocks := uint16(currentAIB[3])<<8 | uint16(currentAIB[4])
maxBytes := uint32(maxBlocks) * feliCaBlockSize
if err := f.validateDataSize(ndefData, maxBytes); err != nil {
return nil, err
}
return ndefData, nil
}
// writeNDEFDataToBlocks writes NDEF data to the FeliCa blocks
func (f *FeliCaTag) writeNDEFDataToBlocks(ctx context.Context, ndefData []byte) error {
// Pad NDEF data to block boundary
paddedLength := ((len(ndefData) + feliCaBlockSize - 1) / feliCaBlockSize) * feliCaBlockSize
paddedData := make([]byte, paddedLength)
copy(paddedData, ndefData)
// Write NDEF data blocks
f.serviceCode = feliCaServiceCodeNDEFWrite
return f.writeNDEFBlocks(ctx, paddedData)
}
// updateAIBWithNDEFLength updates and writes the AIB with new NDEF length
func (f *FeliCaTag) updateAIBWithNDEFLength(ctx context.Context, currentAIB []byte, ndefDataLen int) error {
if ndefDataLen < 0 || ndefDataLen > 0xFFFFFF {
return fmt.Errorf("NDEF data length out of range: %d bytes (must be 0-16777215)", ndefDataLen)
}
newAIB := f.updateAIBWithLength(currentAIB, uint32(ndefDataLen))
if err := f.WriteBlockExtended(ctx, 0, newAIB); err != nil {
return fmt.Errorf("failed to write updated attribute information block: %w", err)
}
return nil
}
// Polling performs a FeliCa polling operation to detect and initialize the tag
// This is a FeliCa-specific operation for card detection and system code discovery
func (f *FeliCaTag) Polling(ctx context.Context, systemCode uint16) error {
// FeliCa Polling command structure:
// Command: 0x00
// System Code: 2 bytes (big endian)
// Request Code: 1 byte (0x01 for system code and time slot)
// Time Slot: 1 byte (0x03 for maximum time slots)
cmd := make([]byte, 0, 5)
// Add command, system code (2 bytes, big endian), request code, and time slot
cmd = append(cmd,
feliCaCmdPolling,
byte((systemCode>>8)&0xFF), byte(systemCode&0xFF), // System code (2 bytes, big endian)
0x01, // Request code (0x01)
0x03, // Time slot (0x03 for maximum slots)
)
// Send command via data exchange
response, err := f.device.SendDataExchange(ctx, cmd)
if err != nil {
return fmt.Errorf("FeliCa polling command failed: %w", err)
}
// Check response format
if len(response) < 19 {
return fmt.Errorf("FeliCa polling response too short: %d bytes", len(response))
}
// Response format:
// Response Code: 1 byte (0x01 for polling response)
// IDm: 8 bytes
// PMm: 8 bytes
// Request Data: variable (2 bytes system code if requested)
if response[0] != 0x01 {
return fmt.Errorf("invalid FeliCa polling response code: 0x%02X", response[0])
}
// Update IDm and PMm from polling response
copy(f.idm, response[1:9])
copy(f.pmm, response[9:17])
// Update UID in BaseTag
f.uid = make([]byte, len(f.idm))
copy(f.uid, f.idm)
// Update system code if present in response
if len(response) >= 19 {
responseSystemCode := uint16(response[17])<<8 | uint16(response[18])
f.systemCode = responseSystemCode
}
return nil
}
// RequestService requests service information from the FeliCa tag
// This is used to check if specific service codes are available
func (f *FeliCaTag) RequestService(ctx context.Context, serviceCodes []uint16) ([]byte, error) {
if len(serviceCodes) == 0 || len(serviceCodes) > 32 {
return nil, fmt.Errorf("invalid service code count: %d (must be 1-32)", len(serviceCodes))
}
// FeliCa Request Service command structure:
// Command: 0x02
// IDm: 8 bytes (card identifier)
// Node Count: 1 byte (number of service codes)
// Node Code List: 2 bytes per service code
cmd := []byte{feliCaCmdRequestService}
// Add IDm (8 bytes)
cmd = append(cmd, f.idm...)
// Node count (number of service codes)
cmd = append(cmd, byte(len(serviceCodes)))
// Add service codes (2 bytes each, little endian)
for _, serviceCode := range serviceCodes {
cmd = append(cmd, byte(serviceCode&0xFF), byte((serviceCode>>8)&0xFF))
}
// Send command via data exchange
response, err := f.device.SendDataExchange(ctx, cmd)
if err != nil {
return nil, fmt.Errorf("FeliCa request service command failed: %w", err)
}
// Check response format
expectedMinLen := 10 + len(serviceCodes)*2
if len(response) < expectedMinLen {
return nil, fmt.Errorf("FeliCa request service response too short: %d bytes", len(response))
}
// Response format:
// Response Code: 1 byte (0x03 for Request Service response)
// IDm: 8 bytes
// Node Count: 1 byte
// Node Key Version List: 2 bytes per service code
if response[0] != 0x03 {
return nil, fmt.Errorf("invalid FeliCa request service response code: 0x%02X", response[0])
}
nodeCount := response[9]
if int(nodeCount) != len(serviceCodes) {
return nil, fmt.Errorf("service count mismatch: expected %d, got %d", len(serviceCodes), nodeCount)
}
// Extract node key version list
nodeKeyVersions := make([]byte, len(serviceCodes)*2)
copy(nodeKeyVersions, response[10:10+len(serviceCodes)*2])
return nodeKeyVersions, nil
}
// validateWritePermissions checks if the tag allows NDEF writing
func (*FeliCaTag) validateWritePermissions(aib []byte) error {
// Check write permissions
writeFlag := aib[9]
if writeFlag == 0x0F {
return errors.New("tag is write-protected")
}
rwFlag := aib[10]
if rwFlag == 0x01 {
return errors.New("NDEF data area is read-only")
}
return nil
}
// validateDataSize checks if NDEF data fits within tag capacity
func (*FeliCaTag) validateDataSize(ndefData []byte, maxBytes uint32) error {
if len(ndefData) > int(maxBytes) {
return fmt.Errorf("NDEF message too large: %d bytes, max %d bytes", len(ndefData), maxBytes)
}
if len(ndefData) > 0xFFFFFF {
return fmt.Errorf("NDEF data too large: %d bytes exceeds 24-bit limit", len(ndefData))
}
return nil
}
// writeNDEFBlocks writes the NDEF data blocks to the tag
func (f *FeliCaTag) writeNDEFBlocks(ctx context.Context, paddedData []byte) error {
blocksToWrite := len(paddedData) / feliCaBlockSize
if blocksToWrite > 0xFFFE {
return fmt.Errorf("NDEF data too large: requires %d blocks but maximum is %d", blocksToWrite, 0xFFFE)
}
for block := range blocksToWrite {
blockData := paddedData[block*feliCaBlockSize : (block+1)*feliCaBlockSize]
if block >= 0xFFFE {
return fmt.Errorf("block index too large: %d", block)
}
blockIndex := uint16(block) + 1 //nolint:gosec // Already bounds-checked above
writeErr := f.WriteBlockExtended(ctx, blockIndex, blockData)
if writeErr != nil {
return fmt.Errorf("failed to write NDEF block %d: %w", block+1, writeErr)
}
}
return nil
}
// updateAIBWithLength creates a new AIB with updated NDEF length and checksum
func (*FeliCaTag) updateAIBWithLength(currentAIB []byte, ndefLength uint32) []byte {
newAIB := make([]byte, 16)
copy(newAIB, currentAIB)
// Update NDEF length (Ln) - 3 bytes big endian at bytes 11-13
newAIB[11] = byte((ndefLength >> 16) & 0xFF)
newAIB[12] = byte((ndefLength >> 8) & 0xFF)
newAIB[13] = byte(ndefLength & 0xFF)
// Recalculate checksum for first 14 bytes
var sum uint16
for i := range 14 {
sum += uint16(newAIB[i])
}
newAIB[14] = byte((sum >> 8) & 0xFF)
newAIB[15] = byte(sum & 0xFF)
return newAIB
}
// validateAIB validates the Attribute Information Block checksum
// The checksum is a 16-bit sum of the first 14 bytes
func (*FeliCaTag) validateAIB(aib []byte) bool {
if len(aib) < 16 {
return false
}
// Calculate checksum of first 14 bytes
var sum uint16
for i := range 14 {
sum += uint16(aib[i])
}
// Extract stored checksum (big endian, bytes 14-15)
storedChecksum := uint16(aib[14])<<8 | uint16(aib[15])
return sum == storedChecksum
}
// DebugInfo returns detailed debug information about the FeliCa tag
func (f *FeliCaTag) DebugInfo(ctx context.Context) string {
return f.DebugInfoWithNDEF(ctx, f)
}
// WriteText writes a simple text record to the FeliCa tag
func (f *FeliCaTag) WriteText(ctx context.Context, text string) error {
message := &NDEFMessage{
Records: []NDEFRecord{
{
Type: NDEFTypeText,
Text: text,
},
},
}
return f.WriteNDEF(ctx, message)
}