Add packaging directory
[platform/upstream/neard.git] / plugins / mifare.c
1 /*
2  *
3  *  neard - Near Field Communication manager
4  *
5  *  Copyright (C) 2012  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdint.h>
27 #include <errno.h>
28 #include <stdbool.h>
29 #include <string.h>
30 #include <sys/socket.h>
31
32 #include <linux/socket.h>
33
34 #include <near/nfc_copy.h>
35 #include <near/plugin.h>
36 #include <near/log.h>
37 #include <near/types.h>
38 #include <near/adapter.h>
39 #include <near/tag.h>
40 #include <near/ndef.h>
41 #include <near/tlv.h>
42
43 /*
44  * NXP Application Notes:
45  * AN1304, AN1305, ...
46  * http://www.nxp.com/technical-support-portal/53420/71108/application-notes
47  */
48
49 /* Prototypes */
50 int mifare_read(uint32_t adapter_idx, uint32_t target_idx,
51                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype);
52
53 int mifare_check_presence(uint32_t adapter_idx, uint32_t target_idx,
54                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype);
55
56 int mifare_write(uint32_t adapter_idx, uint32_t target_idx,
57                 struct near_ndef_message *ndef,
58                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype);
59
60 /* MIFARE command set */
61 #define MF_CMD_WRITE            0xA0
62 #define MF_CMD_READ             0x30
63 #define MF_CMD_AUTH_KEY_A       0x60
64
65 #define NFC_AID_TAG             0xE103
66
67 /*
68  * Define boundaries for 1K / 2K / 4K
69  * 1K:   sector 0 to 15 (3 blocks each + trailer block )
70  * 2K:   sector 0 to 31 (3 blocks each + trailer block )
71  * 4K:   sector 0 to 31 (3 blocks each + trailer block )
72  *      and sector 32 to 39 (15 blocks each + trailer block )
73  */
74 #define DEFAULT_BLOCK_SIZE      16      /* MF_CMD_READ */
75
76 #define STD_BLK_SECT_TRAILER    4       /* bl per sect with trailer 1K/2K */
77 #define EXT_BLK_SECT_TRAILER    16      /* bl per sect with trailer 4K */
78
79 #define STD_BLK_PER_SECT        3       /* 1 sect == 3blocks */
80 #define EXT_BLK_PER_SECT        15      /* for 4K tags */
81
82 /* Usual sector size, including trailer */
83 #define STD_SECTOR_SIZE         (4 * DEFAULT_BLOCK_SIZE)        /* 00-31 */
84 #define EXT_SECTOR_SIZE         (16 * DEFAULT_BLOCK_SIZE)       /* 32-39 */
85
86 /* Usual sector size, without trailer */
87 #define SECTOR_SIZE             (3 * DEFAULT_BLOCK_SIZE)
88 #define BIG_SECTOR_SIZE         (15 * DEFAULT_BLOCK_SIZE)
89
90 #define T4K_BOUNDARY            32
91 #define T4K_BLK_OFF             0x80    /* blocks count before sector 32 */
92
93 #define NO_TRAILER      0
94 #define WITH_TRAILER    1
95 #define SECT_IS_NFC     1
96
97 /* Default MAD keys. Key length = 6 bytes */
98 #define MAD_KEY_LEN     6
99 static uint8_t MAD_public_key[] = {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5};
100 static uint8_t MAD_NFC_key[] = {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7};
101
102 #define MAD1_SECTOR             0x00    /* Sector 0 is for MAD1 */
103 #define MAD1_1ST_BLOCK          0x00    /* 1st block of sector 0 */
104 #define MAD2_GPB_BITS           0x02    /* MAD v2 flag */
105
106 #define MAD2_SECTOR             0x10    /* Sector 16 is for MAD2 */
107 #define MAD2_1ST_BLOCK          0x40    /* 1st block of MAD2 */
108
109 #define MAD_V1_AIDS_LEN         15      /* 1 to 0x0F */
110 #define MAD_V2_AIDS_LEN         23      /*0x11 to 0x27 */
111
112 #define NFC_1ST_BLOCK           0x04    /* Sectors from 1 are for NFC */
113
114 #define ACC_BITS_LEN            3
115
116 /* Access bits for data blocks mask */
117 static uint8_t DATA_access_mask[] = {0x77, 0x77, 0x77};
118
119 /* Write with key A access bits configuration */
120 static uint8_t WRITE_with_key_A[] = {0x77, 0x07, 0x00};
121
122 /* MAD1 sector structure. Start at block 0x00 */
123 struct MAD_1 {
124         uint8_t man_info[16];
125         uint16_t crc_dir;
126         uint16_t aids[MAD_V1_AIDS_LEN];
127         /* Trailer */
128         uint8_t key_A[MAD_KEY_LEN];
129         uint8_t access_cond[3];
130         uint8_t GPB;
131         uint8_t key_B[MAD_KEY_LEN];
132 } __attribute__((packed));
133
134 /* MAD2 sector structure. Start at block 0x40 */
135 struct MAD_2 {
136         uint16_t crc_dir;
137         uint16_t aids[MAD_V2_AIDS_LEN];
138         /* Trailer */
139         uint8_t key_A[MAD_KEY_LEN];
140         uint8_t access_cond[3];
141         uint8_t GPB;
142         uint8_t key_B[MAD_KEY_LEN];
143 } __attribute__((packed));
144
145 struct mifare_cookie {
146         uint32_t adapter_idx;
147         uint32_t target_idx;
148         uint8_t *nfcid1;
149         uint8_t nfcid1_len;
150
151         struct near_tag *tag;
152         near_tag_io_cb cb;
153         near_recv next_far_func;
154
155         /* For MAD access */
156         struct MAD_1 *mad_1;
157         struct MAD_2 *mad_2;
158         GSList *g_sect_list;            /* Global sectors list */
159
160         /* For read and write functions */
161         near_recv rws_next_fct;         /* next function */
162         int rws_block_start;            /* first block */
163         int rws_block_end;              /* last block */
164         int rws_completed;              /* read blocks */
165
166
167         /* For read only */
168         int rs_length;                  /* read length */
169         uint8_t *rs_pmem;               /* Stored read sector */
170         int rs_max_length;              /* available size */
171         uint8_t *nfc_data;
172         size_t nfc_data_length;
173
174         /* For write only */
175         struct near_ndef_message *ndef; /* message to write */
176         size_t ndef_length;             /* message length */
177
178         /* For access check */
179         int (*acc_check_function)(void *data);  /* acc check fnc */
180         uint8_t *acc_bits_mask;                 /* blocks to check */
181         uint8_t *acc_rights;                    /* condition */
182         int (*acc_denied_fct)(void *data);/* fnc to call on access denial */
183         GSList *acc_sect;                 /* sector from g_sect_list to check */
184 };
185
186 struct type2_cmd {
187         uint8_t cmd;
188         uint8_t block;
189         uint8_t data[];
190 } __attribute__((packed));
191
192 struct mf_write_cmd {
193         uint8_t cmd;
194         uint8_t block;
195         uint8_t data[DEFAULT_BLOCK_SIZE];
196 } __attribute__((packed));
197
198 struct mifare_cmd {
199         uint8_t cmd;
200         uint8_t block;
201         uint8_t key[MAD_KEY_LEN];
202         uint8_t nfcid[NFC_NFCID1_MAXSIZE];
203 } __attribute__((packed));
204
205 static int mifare_release(int err, void *data)
206 {
207         struct mifare_cookie *cookie = data;
208
209         DBG("%p", cookie);
210
211         if (!cookie)
212                 return err;
213
214         if (err < 0 && cookie->cb) {
215                 cookie->cb(cookie->adapter_idx, cookie->target_idx, err);
216                 near_adapter_disconnect(cookie->adapter_idx);
217         }
218
219         /* Now free allocs */
220         g_free(cookie->nfcid1);
221         g_slist_free(cookie->g_sect_list);
222         g_free(cookie->mad_1);
223         g_free(cookie->mad_2);
224
225         if (cookie->ndef)
226                 g_free(cookie->ndef->data);
227
228         g_free(cookie->ndef);
229         g_free(cookie);
230         cookie = NULL;
231
232         return err;
233 }
234
235 /*
236  * Mifare_generic MAD unlock block function
237  * This function send unlock code to the tag, and so, allow access
238  * to the complete related sector.
239  */
240 static int mifare_unlock_sector(int block_id,
241                                 near_recv next_far_fct,
242                                 void *data)
243 {
244         struct mifare_cmd cmd;
245         struct mifare_cookie *cookie = data;
246         uint8_t *key_ref;
247
248         /*
249          * For MADs sectors we use public key A (a0a1a2a3a4a5) but
250 -        * for NFC sectors we use NFC_KEY_A (d3f7d3f7d3f7)
251          */
252         if ((block_id == MAD1_1ST_BLOCK) || (block_id == MAD2_1ST_BLOCK))
253                 key_ref = MAD_public_key;
254         else
255                 key_ref = MAD_NFC_key;
256
257          /* CMD AUTHENTICATION */
258         cmd.cmd = MF_CMD_AUTH_KEY_A;
259
260         /* Authenticate will be on the 1st block of the sector */
261         cmd.block = block_id;
262
263         /* Store the AUTH KEY */
264         memcpy(&cmd.key, key_ref, MAD_KEY_LEN);
265
266         /* add the UID */
267         memcpy(&cmd.nfcid, cookie->nfcid1, cookie->nfcid1_len);
268
269         return near_adapter_send(cookie->adapter_idx, (uint8_t *)&cmd,
270                 sizeof(cmd) - NFC_NFCID1_MAXSIZE + cookie->nfcid1_len,
271                 next_far_fct, cookie, mifare_release);
272 }
273
274 /*
275  * Common MIFARE Block read:
276  * Each call will read 16 bytes from tag... so to read 1 sector,
277  * it has to be called it 4 times or 16 times
278  * (minus 1 or not for the trailer block)
279  *
280  * data: mifare_cookie *mf_ck
281  * mf_ck->read_block: block number to read
282  */
283 static int mifare_read_block(uint8_t block_id,
284                                 void *data,
285                                 near_recv far_func)
286 {
287         struct type2_cmd cmd;
288         struct mifare_cookie *mf_ck = data;
289
290         cmd.cmd = MF_CMD_READ; /* MIFARE READ */
291         cmd.block = block_id;
292
293         return near_adapter_send(mf_ck->adapter_idx, (uint8_t *) &cmd, 2,
294                                         far_func, mf_ck, mifare_release);
295 }
296
297 /*
298  * Check access rights
299  * Function processes sector trailer received from tag and checks access rights.
300  * In case specified access isn't granted it calls appropriate
301  * access denial function.
302  * If access is granted, previous action (e.g. read, write) is continued.
303  */
304 static int mifare_check_rights_cb(uint8_t *resp, int length, void *data)
305 {
306         struct mifare_cookie *mf_ck = data;
307         int err;
308         uint8_t *c;
309         int i;
310
311         if (length < 0) {
312                 err = length;
313                 goto out_err;
314         }
315
316         /* skip reader byte and key A */
317          c = resp + 1 + MAD_KEY_LEN;
318
319         for (i = 0; i < ACC_BITS_LEN; i++) {
320                 if ((c[i] & mf_ck->acc_bits_mask[i]) != mf_ck->acc_rights[i]) {
321                         (*mf_ck->acc_denied_fct)(data);
322                         return 0;
323                 }
324         }
325
326         /* Continue previous action (read/write) */
327         err = (*mf_ck->rws_next_fct)(resp, length, data);
328
329         if (err < 0)
330                 goto out_err;
331
332         return err;
333
334 out_err:
335         return mifare_release(err, mf_ck);
336 }
337
338 /* Calls to mifare_read_block to get sector trailer */
339 static int mifare_check_rights(uint8_t *resp, int length, void *data)
340 {
341         struct mifare_cookie *mf_ck = data;
342         int err;
343
344         err = mifare_read_block(mf_ck->rws_block_start, mf_ck,
345                         mifare_check_rights_cb);
346
347         if (err < 0)
348                 return mifare_release(err, mf_ck);
349
350         return err;
351 }
352
353 static int mifare_read_sector_cb(uint8_t *resp, int length, void *data)
354 {
355         struct mifare_cookie *mf_ck = data;
356         int err = -1;
357
358         if (length < 0) {
359                 err = length;
360                 goto out_err;
361         }
362
363         /* Save the data */
364         length = length - 1; /* ignore first byte - Reader byte */
365
366         /* save the length: */
367         mf_ck->rs_length = mf_ck->rs_length + length;
368
369         memcpy(mf_ck->rs_pmem + mf_ck->rws_completed * DEFAULT_BLOCK_SIZE,
370                         resp + 1,/* ignore reader byte */
371                         length);
372
373         /* Next block */
374         mf_ck->rws_completed = mf_ck->rws_completed + 1;
375
376         if ((mf_ck->rws_block_start + mf_ck->rws_completed)
377                                                 < mf_ck->rws_block_end)
378                 err = mifare_read_block(
379                                 (mf_ck->rws_block_start + mf_ck->rws_completed),
380                                 data,
381                                 mifare_read_sector_cb);
382         else {
383                 /* Now Process the callback ! */
384                 err = (*mf_ck->rws_next_fct)(mf_ck->rs_pmem,
385                                                 mf_ck->rs_length, data);
386         }
387
388         if (err < 0)
389                 goto out_err;
390         return err;
391
392 out_err:
393         return mifare_release(err, mf_ck);
394 }
395
396 static int mifare_read_sector_unlocked(uint8_t *resp, int length, void *data)
397 {
398         struct mifare_cookie *mf_ck = data;
399         int err;
400
401         if (length < 0) {
402                 err = length;
403                 goto out_err;
404         }
405         /* And run the read process on the first block of the sector */
406         err = mifare_read_block(mf_ck->rws_block_start, data,
407                                 mifare_read_sector_cb);
408
409         if (err < 0)
410                 goto out_err;
411         return err;
412
413 out_err:
414         return mifare_release(err, mf_ck);
415 }
416
417 /*
418  * This function reads a complete sector, using block per block function.
419  * sector sizes can be:
420  * Sectors 0 to 31:
421  *      48 bytes: 3*16 no trailer
422  *      64 bytes: 4*16 with trailer
423  * Sectors 32 to 39:
424  *      240 bytes: 15*16 no trailer
425  *      256 bytes: 16*16 with trailer
426  *
427  * Unlock is done at the beginning of first sector.
428  */
429 static int mifare_read_sector(void *cookie,
430                         uint8_t *pmem,          /* memory to fill */
431                         uint16_t memsize,       /* remaining free size */
432                         uint8_t sector_id,      /* sector to read */
433                         bool trailer,   /* Add trailer or not */
434                         near_recv next_func)
435 {
436         struct mifare_cookie *mf_ck = cookie;
437         int err;
438         int blocks_count;
439
440         DBG("");
441
442         /* Prepare call values */
443         mf_ck->rs_pmem = pmem;                  /* where to store */
444         mf_ck->rs_max_length = memsize;         /* max size to store */
445         mf_ck->rs_length = 0;                   /* no bytes yet */
446         mf_ck->rws_completed = 0;               /* blocks read */
447
448         /* According to tag size, compute the correct block offset */
449         if (sector_id < T4K_BOUNDARY)
450                 mf_ck->rws_block_start = sector_id * 4;  /* 1st block to read */
451         else
452                 mf_ck->rws_block_start =
453                                 (sector_id - T4K_BOUNDARY) * 16 + T4K_BLK_OFF;
454
455         /* Find blocks_per_sect, according to position and trailer or not */
456         if (sector_id < T4K_BOUNDARY)
457                 blocks_count = (STD_BLK_PER_SECT + trailer);
458         else
459                 blocks_count = (EXT_BLK_PER_SECT + trailer);
460
461         mf_ck->rws_block_end = mf_ck->rws_block_start + blocks_count;
462
463         mf_ck->rws_next_fct = next_func;                /* leaving function */
464
465         /* Being on the first block of a sector, unlock it */
466         err = mifare_unlock_sector(mf_ck->rws_block_start,
467                         mifare_read_sector_unlocked, mf_ck);
468
469         return err;
470 }
471
472 static int mifare_read_NFC_loop(uint8_t *resp, int length, void *data)
473 {
474         struct mifare_cookie *mf_ck = data;
475         int err = 0;
476
477         DBG("");
478
479         if (length < 0) {
480                 err = length;
481                 goto out_err;
482         }
483
484         /* ptr to the next read ptr */
485         mf_ck->nfc_data = mf_ck->nfc_data + length;
486
487         /* remaining free mem */
488         mf_ck->nfc_data_length = mf_ck->nfc_data_length - length;
489
490
491         /* Additional sectors to read ? */;
492         if (mf_ck->g_sect_list && mf_ck->g_sect_list->next) {
493
494                 err = mifare_read_sector(data,  /* cookie */
495                         mf_ck->nfc_data,                /* where to store */
496                         (int) mf_ck->nfc_data_length,   /* global length */
497                         GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* id */
498                         NO_TRAILER,                     /* Trailer ? */
499                         mifare_read_NFC_loop);          /* next function */
500
501                 mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
502                                                 mf_ck->g_sect_list->data);
503
504                 if (err < 0)
505                         goto out_err;
506                 return err;
507         } else {
508                 GList *records;
509                 uint8_t *nfc_data;
510                 size_t nfc_data_length;
511
512                 DBG("Done reading");
513
514                 nfc_data = near_tag_get_data(mf_ck->tag, &nfc_data_length);
515                 if (!nfc_data) {
516                         err = -ENOMEM;
517                         goto out_err;
518                 }
519
520                 records = near_tlv_parse(nfc_data, nfc_data_length);
521                 near_tag_add_records(mf_ck->tag, records, mf_ck->cb, 0);
522
523                 err = 0;
524         }
525
526 out_err:
527         return mifare_release(err, mf_ck);
528 }
529
530 /* Prepare read NFC loop */
531 static int mifare_read_NFC(uint8_t *resp, int length, void *data)
532 {
533         struct mifare_cookie *mf_ck = data;
534         int err;
535
536         /* save tag memory pointer to data_block */
537         mf_ck->nfc_data = near_tag_get_data(mf_ck->tag,
538                                         &mf_ck->nfc_data_length);
539
540         /* First read here: */
541         err = mifare_read_sector(data,          /* cookie */
542                 mf_ck->nfc_data,                /* where to store */
543                 mf_ck->nfc_data_length,         /* global length */
544                 GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* sector id */
545                 NO_TRAILER,                     /* Don't want Trailer */
546                 mifare_read_NFC_loop);          /* next function */
547
548         mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
549                                                 mf_ck->g_sect_list->data);
550         if (err < 0)
551                 goto out_err;
552         return err;
553
554 out_err:
555         return mifare_release(err, mf_ck);
556 }
557
558 static int mifare_process_MADs(void *data)
559 {
560         struct mifare_cookie *mf_ck = data;
561         int err;
562         int i;
563         int global_tag_size = 0;
564         int ioffset;
565         uint8_t *tag_data;
566         size_t data_size;
567
568         DBG("");
569
570         /* Parse MAD entries to get the global size and fill the array */
571         if (!mf_ck->mad_1) {
572                 err = -EINVAL;
573                 goto out_err;
574         }
575
576         /* Skip non-NFC sectors at the beginning of the tag, if any */
577         for (i = 0 ; i < MAD_V1_AIDS_LEN; i++) {
578                 if (mf_ck->mad_1->aids[i] == NFC_AID_TAG)
579                         break;
580         }
581
582         /*
583          * NFC sectors have to be continuous,
584          * so only some sectors at the beginning and at the end of tag
585          * can be non-NFC.
586          */
587         for (; i < MAD_V1_AIDS_LEN; i++) {
588                 if (mf_ck->mad_1->aids[i] != NFC_AID_TAG)
589                         goto done_mad;
590
591                 /* Save in the global list */
592                 mf_ck->g_sect_list = g_slist_append(mf_ck->g_sect_list,
593                                                 GINT_TO_POINTER(i + 1));
594                 global_tag_size += SECTOR_SIZE;
595         }
596
597         /* Now MAD 2 */
598         ioffset = MAD_V1_AIDS_LEN + 1 + 1; /* skip 0x10 */
599         if (!mf_ck->mad_2)
600                 goto done_mad;
601
602         /*
603          * If all sectors from MAD1 were non-NFC,
604          * skip initial non-NFC sectors from MAD2
605          */
606         i = 0;
607
608         if (global_tag_size == 0)
609                 for (; i < MAD_V2_AIDS_LEN; i++)
610                         if (mf_ck->mad_2->aids[i] == NFC_AID_TAG)
611                                 break;
612
613         for (; i < MAD_V2_AIDS_LEN; i++) {
614                 if (mf_ck->mad_2->aids[i] != NFC_AID_TAG)
615                         goto done_mad;
616
617                 mf_ck->g_sect_list = g_slist_append(mf_ck->g_sect_list,
618                                                 GINT_TO_POINTER(ioffset + i));
619                 if (i < EXT_BLK_PER_SECT)
620                         global_tag_size += SECTOR_SIZE;
621                 else
622                         global_tag_size += BIG_SECTOR_SIZE;
623         }
624
625 done_mad:
626         if (global_tag_size == 0) {
627
628                 /* no NFC sectors - mark tag as blank */
629                 near_error("TAG Global size: [%d], not valid NFC tag.",
630                                 global_tag_size);
631                 return -ENODEV;
632         }
633
634         /* n sectors, each sector is 3 blocks, each block is 16 bytes */
635         DBG("TAG Global size: [%d]", global_tag_size);
636
637         mf_ck->tag = near_tag_get_tag(mf_ck->adapter_idx, mf_ck->target_idx);
638         if (!mf_ck->tag) {
639                 err = -ENOMEM;
640                 goto out_err;
641         }
642
643         /* don't allocate new data before writing */
644         tag_data = near_tag_get_data(mf_ck->tag, &data_size);
645         if (!tag_data) {
646                 err = near_tag_add_data(mf_ck->adapter_idx,
647                                                 mf_ck->target_idx,
648                                                 NULL, /* Empty */
649                                                 global_tag_size);
650
651                 if (err < 0)
652                         goto out_err;
653         }
654
655         /* Check access rights */
656         err = mf_ck->acc_check_function(data);
657
658         if (err < 0)
659                 goto out_err;
660
661         return err;
662
663 out_err:
664         return mifare_release(err, mf_ck);
665 }
666
667 /* Transitional function - async */
668 static int read_MAD2_complete(uint8_t *empty, int iempty, void *data)
669 {
670         return mifare_process_MADs(data);
671 }
672
673 /* This function reads the MAD2 sector */
674 static int mifare_read_MAD2(void *data)
675 {
676         struct mifare_cookie *mf_ck = data;
677         int err = 0;
678
679         DBG("");
680
681         /* As auth is ok, allocate Mifare Access Directory v1 */
682         mf_ck->mad_2 = g_try_malloc0(STD_SECTOR_SIZE);
683         if (!mf_ck->mad_2) {
684                 near_error("Memory allocation failed (MAD2)");
685                 err = -ENOMEM;
686                 goto out_err;
687         }
688
689         err = mifare_read_sector(data,
690                         (uint8_t *) mf_ck->mad_2,
691                         (int) STD_SECTOR_SIZE,
692                         MAD2_SECTOR,                    /* sector 0x10 */
693                         WITH_TRAILER,                   /* Want Trailer */
694                         read_MAD2_complete);
695
696         if (err < 0)
697                 goto out_err;
698         return err;
699
700 out_err:
701         return mifare_release(err, mf_ck);
702 }
703
704 /*
705  * This function checks, in MAD1, if there's a MAD2 directory
706  * available. This is is the case for 2K and 4K tag
707  * If MAD2 exists, read it, elsewhere process the current MAD
708  */
709 static int read_MAD1_complete(uint8_t *empty, int iempty, void *data)
710 {
711         struct mifare_cookie *mf_ck = data;
712         int err;
713
714         DBG("");
715
716         /* Check if there's a need to get MAD2 sector */
717         if ((mf_ck->mad_1->GPB & 0x03) == MAD2_GPB_BITS)
718                 err = mifare_read_MAD2(mf_ck);
719         else
720                 err = mifare_process_MADs(data);
721
722         return err;
723 }
724
725 /*
726  * Function called to read the first MAD sector
727  * MAD is mandatory
728  */
729 static int mifare_read_MAD1(uint8_t *resp, int length, void *data)
730 {
731         struct mifare_cookie *mf_ck = data;
732         int err = 0;
733
734         DBG("%p %d", data, length);
735
736         if (length < 0) {
737                 err = length;
738                 return err;
739         }
740
741         /*
742          * As auth is ok, allocate Mifare Access Directory v1
743          * allocated size is also STD_SECTOR_SIZE
744          */
745         mf_ck->mad_1 = g_try_malloc0(STD_SECTOR_SIZE);
746         if (!mf_ck->mad_1) {
747                 near_error("Memory allocation failed (MAD1)");
748                 err = -ENOMEM;
749                 goto out_err;
750         }
751
752         /* Call to mifare_read_sector */
753         err = mifare_read_sector(data,
754                         (uint8_t *)mf_ck->mad_1,        /* where to store */
755                         (int) STD_SECTOR_SIZE,          /* allocated size */
756                         MAD1_SECTOR,                    /* sector 0 */
757                         WITH_TRAILER,                   /* Want Trailer */
758                         read_MAD1_complete);
759
760         if (err < 0)
761                 goto out_err;
762         return err;
763
764 out_err:
765         return mifare_release(err, mf_ck);
766 }
767
768 /* If first NFC sector isn't writable, mark whole tag as read only */
769 static int is_read_only(void *data)
770 {
771         struct mifare_cookie *mf_ck = data;
772
773         DBG("Tag is read only");
774
775         near_tag_set_ro(mf_ck->tag, TRUE);
776
777         /* Continue previous action (read) */
778         (*mf_ck->rws_next_fct)(NULL, 0, data);
779
780         return 0;
781 }
782
783
784 static int mifare_check_read_only(void *data)
785 {
786         struct mifare_cookie *mf_ck = data;
787         int err;
788
789         DBG("");
790
791         /*
792          * As authorisation with key B is not supported,
793          * in case writing with key A is not permitted, tag is read-only
794          */
795         mf_ck->acc_bits_mask = DATA_access_mask;
796         mf_ck->acc_rights = WRITE_with_key_A;
797
798         /* Check acces rights of first NFC sector */
799         mf_ck->rws_block_start = NFC_1ST_BLOCK + STD_BLK_PER_SECT;
800         /* Afterwards read tag */
801         mf_ck->rws_next_fct = mifare_read_NFC;
802         /* In case of writing access denial, set read only */
803         mf_ck->acc_denied_fct = is_read_only;
804
805         err = mifare_unlock_sector(mf_ck->rws_block_start,
806                         mifare_check_rights, mf_ck);
807
808         if (err < 0)
809                 return mifare_release(err, mf_ck);
810
811         return err;
812 }
813
814 /*
815  * MIFARE: entry point:
816  * Read all the MAD sectors (0x00, 0x10) to get the Application Directory
817  * entries.
818  * On sector 0x00, App. directory is on block 0x01 & block 0x02
819  * On sector 0x10, App. directory is on block 0x40, 0x41 & 0x42
820  * On reading, CRC is ignored.
821  */
822 int mifare_read(uint32_t adapter_idx, uint32_t target_idx,
823                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
824 {
825         struct mifare_cookie *cookie;
826         int err;
827
828         DBG("");
829
830         /*Check supported and tested Mifare type */
831         switch (tgt_subtype) {
832         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
833         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
834                 break;
835         default:
836                 near_error("Mifare tag type [%d] not supported.", tgt_subtype);
837                 return -1;
838         }
839
840         /* Alloc global cookie */
841         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
842         if (!cookie)
843                 return -ENOMEM;
844
845         /* Get the nfcid1 */
846         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
847                                 &cookie->nfcid1_len);
848         cookie->adapter_idx = adapter_idx;
849         cookie->target_idx = target_idx;
850         cookie->cb = cb;
851
852         /* check access rights - while reading just check read only */
853         cookie->acc_check_function = mifare_check_read_only;
854
855         /*
856          * Need to unlock before reading
857          * This will check if public keys are allowed (and, so, NDEF could
858          * be "readable"...
859          */
860         err = mifare_unlock_sector(MAD1_1ST_BLOCK,      /* related block */
861                                 mifare_read_MAD1,       /* callback function */
862                                 cookie);                /* target data */
863         if (err < 0)
864                 return mifare_release(err, cookie);
865
866         return 0;
867 }
868
869 static int check_presence(uint8_t *resp, int length, void *data)
870 {
871         struct mifare_cookie *cookie = data;
872         int err = 0;
873
874         DBG("%d", length);
875
876         if (length < 0) {
877                 err = -EIO;
878                 goto out;
879         }
880
881         if (cookie->cb)
882                 cookie->cb(cookie->adapter_idx, cookie->target_idx, err);
883
884 out:
885         return mifare_release(err, cookie);
886 }
887
888 int mifare_check_presence(uint32_t adapter_idx, uint32_t target_idx,
889                         near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
890 {
891         struct mifare_cmd cmd;
892         struct mifare_cookie *cookie;
893         uint8_t *key_ref = MAD_public_key;
894
895         DBG("");
896
897         /* Check supported and tested Mifare type */
898         switch (tgt_subtype) {
899         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
900         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
901                 break;
902         default:
903                 near_error("Mifare tag type %d not supported.", tgt_subtype);
904                 return -1;
905         }
906
907         /* Alloc global cookie */
908         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
909         if (!cookie)
910                 return -ENOMEM;
911
912         /* Get the nfcid1 */
913         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
914                                         &cookie->nfcid1_len);
915         cookie->adapter_idx = adapter_idx;
916         cookie->target_idx = target_idx;
917         cookie->cb = cb;
918
919         /*
920          * To check presence of Mifare Classic Tag,
921          * send authentication command instead of read one
922          */
923         cmd.cmd = MF_CMD_AUTH_KEY_A;
924
925         /* Authenticate the 1st block of the MAD sector */
926         cmd.block = MAD1_1ST_BLOCK;
927
928         /* Store the AUTH KEY */
929         memcpy(&cmd.key, key_ref, MAD_KEY_LEN);
930
931         /* add the UID */
932         memcpy(&cmd.nfcid, cookie->nfcid1, cookie->nfcid1_len);
933
934         return near_adapter_send(cookie->adapter_idx,
935                         (uint8_t *) &cmd,
936                         sizeof(cmd) - NFC_NFCID1_MAXSIZE + cookie->nfcid1_len,
937                         check_presence,
938                         cookie, mifare_release);
939 }
940
941 /*
942  * Common MIFARE Block write:
943  * Each call will write 16 bytes to tag... so to write 1 sector,
944  * it has to be called it 4 or 16 times (minus 1 for the trailer block)
945  */
946 static int mifare_write_block(uint8_t block_id, void *data,
947                                 near_recv far_func)
948 {
949         struct mf_write_cmd cmd;
950         struct mifare_cookie *mf_ck = data;
951
952         memset(&cmd, 0, sizeof(cmd));
953         cmd.cmd = MF_CMD_WRITE; /* MIFARE WRITE */
954         cmd.block = block_id;
955
956         if ((mf_ck->ndef->offset + DEFAULT_BLOCK_SIZE) <
957                         mf_ck->ndef->length) {
958                 memcpy(cmd.data, mf_ck->ndef->data +
959                                 mf_ck->ndef->offset, DEFAULT_BLOCK_SIZE);
960                 mf_ck->ndef->offset += DEFAULT_BLOCK_SIZE;
961         } else {
962                 memcpy(cmd.data, mf_ck->ndef->data + mf_ck->ndef->offset,
963                                 mf_ck->ndef->length - mf_ck->ndef->offset);
964                 mf_ck->ndef->offset = mf_ck->ndef->length + 1;
965         }
966
967         return near_adapter_send(mf_ck->adapter_idx,
968                                 (uint8_t *) &cmd, sizeof(cmd),
969                                 far_func, data, NULL);
970 }
971
972 static int mifare_correct_length_cb(uint8_t *resp, int length, void *data)
973 {
974         struct mifare_cookie *mf_ck = data;
975
976         DBG("Done writing");
977
978         if (mf_ck->cb)
979                 mf_ck->cb(mf_ck->adapter_idx, mf_ck->target_idx, 0);
980
981         return mifare_release(0, mf_ck);
982 }
983
984 /* After writing ndef message, its length has to be updated */
985 static int mifare_correct_length(uint8_t *resp, int length, void *data)
986 {
987         struct mifare_cookie *mf_ck = data;
988
989         DBG("");
990
991         /* Correct length field */
992         mf_ck->ndef->data[1] = mf_ck->ndef_length;
993         /* and ndef offset so it points to the beginning */
994         mf_ck->ndef->offset = 0;
995
996         /* Run the write process only on the first block of the sector */
997         return mifare_write_block(NFC_1ST_BLOCK, mf_ck,
998                                         mifare_correct_length_cb);
999 }
1000
1001 static int mifare_write_sector_cb(uint8_t *resp, int length, void *data)
1002 {
1003         struct mifare_cookie *mf_ck = data;
1004         int err;
1005
1006         /* Next block */
1007         mf_ck->rws_completed = mf_ck->rws_completed + 1;
1008
1009         /* Check if it's the last block */
1010         if ((mf_ck->rws_block_start + mf_ck->rws_completed)
1011                         < mf_ck->rws_block_end) {
1012                 /* then check if there's still data to write */
1013                 if (mf_ck->ndef->offset < mf_ck->ndef->length)
1014                         err = mifare_write_block(
1015                                 mf_ck->rws_block_start + mf_ck->rws_completed,
1016                                 data, mifare_write_sector_cb);
1017                 else
1018                         /* No more Data to write */
1019                         /* Correct length of the ndef message */
1020                         err = mifare_unlock_sector(NFC_1ST_BLOCK,
1021                                                 mifare_correct_length, mf_ck);
1022         } else {
1023                 /* Process the callback */
1024                 err = (*mf_ck->rws_next_fct)(resp, length, data);
1025         }
1026
1027         if (err < 0)
1028                 return mifare_release(err, mf_ck);
1029
1030         return err;
1031
1032 }
1033
1034 static int mifare_write_sector_unlocked(uint8_t *resp, int length, void *data)
1035 {
1036         struct mifare_cookie *mf_ck = data;
1037         int err;
1038
1039         if (length < 0) {
1040                 err = length;
1041                 goto out_err;
1042         }
1043
1044         /* Run the write process on the first block of the sector */
1045         err = mifare_write_block(mf_ck->rws_block_start, data,
1046                         mifare_write_sector_cb);
1047
1048         if (err < 0)
1049                 goto out_err;
1050         return err;
1051
1052 out_err:
1053         return mifare_release(err, mf_ck);
1054 }
1055
1056 /*
1057  * This function writes a complete sector, using block per block function.
1058  * sector sizes can be:
1059  * Sectors 0 to 31:
1060  *      48 bytes: 3*16 (no trailer)
1061  * Sectors 32 to 39:
1062  *      240 bytes: 15*16 (no trailer)
1063  *
1064  * Unlock is done at the beginning of each sector.
1065  */
1066 static int mifare_write_sector(void *cookie,
1067                                 uint8_t sector_id,      /* sector to write */
1068                                 near_recv next_func)
1069 {
1070         struct mifare_cookie *mf_ck = cookie;
1071         int blocks_count;
1072
1073         DBG("");
1074
1075         /* Prepare call values */
1076
1077         /* According to tag size, compute the correct block offset */
1078         if (sector_id < T4K_BOUNDARY)
1079                 mf_ck->rws_block_start = sector_id * STD_BLK_SECT_TRAILER;
1080         else
1081                 mf_ck->rws_block_start = T4K_BLK_OFF +
1082                         (sector_id - T4K_BOUNDARY) * EXT_BLK_SECT_TRAILER;
1083
1084         /* Find blocks_per_sect, according to position, no trailer */
1085         if (sector_id < T4K_BOUNDARY)
1086                 blocks_count = STD_BLK_PER_SECT;
1087         else
1088                 blocks_count = EXT_BLK_PER_SECT;
1089
1090         mf_ck->rws_block_end = mf_ck->rws_block_start + blocks_count;
1091         mf_ck->rws_completed = 0;
1092         mf_ck->rws_next_fct = next_func;
1093
1094         /* Being on the first block of the sector, unlock it */
1095         return mifare_unlock_sector(mf_ck->rws_block_start,
1096                                         mifare_write_sector_unlocked, mf_ck);
1097 }
1098
1099 static int mifare_write_NFC_loop(uint8_t *resp, int length, void *data)
1100 {
1101         struct mifare_cookie *mf_ck = data;
1102         int err = 0;
1103
1104         if (length < 0 || resp[0] != 0) {
1105                 err = -EIO;
1106                 goto out_err;
1107         }
1108
1109         /* Something more to write? */;
1110         if (mf_ck->ndef->offset < mf_ck->ndef->length) {
1111                 err = mifare_write_sector(data,         /* cookie */
1112                                 GPOINTER_TO_INT(mf_ck->g_sect_list->data),
1113                                 mifare_write_NFC_loop); /* next function */
1114
1115                 mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
1116                                                 mf_ck->g_sect_list->data);
1117
1118                 if (err < 0)
1119                         goto out_err;
1120
1121         } else {
1122                 /* Correct length of an NDEF message */
1123                 err = mifare_unlock_sector(NFC_1ST_BLOCK,
1124                                         mifare_correct_length, mf_ck);
1125
1126                 if (err < 0)
1127                         goto out_err;
1128         }
1129
1130         return err;
1131 out_err:
1132         return mifare_release(err, mf_ck);
1133 }
1134
1135 static int mifare_write_NFC(void *data)
1136 {
1137         struct mifare_cookie *mf_ck = data;
1138         int err;
1139
1140         DBG("");
1141
1142         mf_ck->rws_completed = 0;       /* written blocks */
1143
1144         /* First write here: */
1145         err = mifare_write_sector(data,         /* cookie */
1146                 GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* sector id */
1147                 mifare_write_NFC_loop);         /* next function */
1148
1149         mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
1150                                                 mf_ck->g_sect_list->data);
1151
1152         if (err < 0)
1153                 return mifare_release(err, mf_ck);
1154
1155         return err;
1156 }
1157
1158 static int mifare_check_rights_loop(uint8_t *resp, int length, void *data)
1159 {
1160         struct mifare_cookie *mf_ck = data;
1161         int err;
1162         int sector_id;
1163
1164         if (mf_ck->acc_sect->next) {
1165
1166                 mf_ck->acc_sect = mf_ck->acc_sect->next;
1167                 sector_id = GPOINTER_TO_INT(mf_ck->acc_sect->data);
1168
1169                 if (sector_id < T4K_BOUNDARY)
1170                         mf_ck->rws_block_start = sector_id * 4
1171                                                         + STD_BLK_PER_SECT;
1172                 else
1173                         mf_ck->rws_block_start = T4K_BLK_OFF + EXT_BLK_PER_SECT
1174                                 + (sector_id - T4K_BOUNDARY) * 16;
1175
1176                 err = mifare_unlock_sector(mf_ck->rws_block_start,
1177                                 mifare_check_rights, mf_ck);
1178         } else {
1179                 /* Full access granted, start writing */
1180                 err = mifare_write_NFC(data);
1181         }
1182
1183         if (err < 0)
1184                 return mifare_release(err, mf_ck);
1185
1186         return err;
1187 }
1188
1189
1190 /*
1191  * If one of NFC sectors isn't writable,
1192  * tag size for writing is smaller than actual memory size,
1193  * so calculate it and check if it is enough for ndef message.
1194  */
1195 static int writing_not_permitted(void *data)
1196 {
1197         struct mifare_cookie *mf_ck = data;
1198         unsigned int new_tag_size = 0;
1199         int sector_id;
1200         int i;
1201
1202         sector_id = GPOINTER_TO_INT(mf_ck->acc_sect->data);
1203         DBG("Writing sector %i not permitted", sector_id);
1204
1205         /* Read only sector found, calculate new tag size */
1206         if (sector_id <= MAD_V1_AIDS_LEN) {
1207                 for (i = GPOINTER_TO_INT(mf_ck->g_sect_list->data);
1208                                 i < sector_id; i++)
1209                         new_tag_size += SECTOR_SIZE;
1210         } else {
1211                 /* Start from first NFC sector */
1212                 for (i = GPOINTER_TO_INT(mf_ck->g_sect_list->data);
1213                                 i <= MAD_V1_AIDS_LEN; i++)
1214                         new_tag_size += SECTOR_SIZE;
1215
1216                 /*
1217                  * If any of previous sector was NFC, skip MAD2
1218                  * If not, leave "i" as it was
1219                  */
1220                 if (i < MAD2_SECTOR)
1221                         i = MAD2_SECTOR + 1;
1222
1223                 for (; i < sector_id; i++) {
1224                         if (i < T4K_BOUNDARY)
1225                                 new_tag_size += SECTOR_SIZE;
1226                         else
1227                                 new_tag_size += BIG_SECTOR_SIZE;
1228                 }
1229         }
1230
1231         DBG("TAG writable sectors' size: [%d].", new_tag_size);
1232
1233         /* Check if there's enough space on tag */
1234         if (new_tag_size < mf_ck->ndef->length) {
1235                 near_error("Not enough space on tag");
1236
1237                 if (mf_ck->cb)
1238                         mf_ck->cb(mf_ck->adapter_idx,
1239                                         mf_ck->target_idx, -ENOSPC);
1240
1241                 mifare_release(0, data);
1242                 return -ENOSPC;
1243         }
1244
1245         /* Enough space on tag, continue writing */
1246         mifare_write_NFC(data);
1247
1248         return 0;
1249 }
1250
1251 static int mifare_check_rights_NFC(void *data)
1252 {
1253         struct mifare_cookie *mf_ck = data;
1254         int err;
1255
1256         DBG("");
1257
1258         /*
1259          * As authorisation with key B is not supported,
1260          * in case writing with key A is not permitted, tag is read-only
1261          */
1262         mf_ck->acc_bits_mask = DATA_access_mask;
1263         mf_ck->acc_rights = WRITE_with_key_A;
1264
1265         mf_ck->acc_sect = mf_ck->g_sect_list;
1266         mf_ck->rws_block_start = NFC_1ST_BLOCK + STD_BLK_PER_SECT;
1267         mf_ck->rws_next_fct = mifare_check_rights_loop;
1268
1269         mf_ck->acc_denied_fct = writing_not_permitted;
1270         err = mifare_unlock_sector(mf_ck->rws_block_start,
1271                         mifare_check_rights, mf_ck);
1272
1273         if (err < 0)
1274                 return mifare_release(err, mf_ck);
1275
1276         return err;
1277 }
1278
1279 int mifare_write(uint32_t adapter_idx, uint32_t target_idx,
1280                         struct near_ndef_message *ndef,
1281                         near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
1282 {
1283         struct mifare_cookie *cookie;
1284         struct near_tag *tag;
1285         size_t tag_size;
1286         int err;
1287
1288         DBG("");
1289
1290         /* Check supported and tested Mifare type */
1291         switch (tgt_subtype) {
1292         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
1293         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
1294                 break;
1295         default:
1296                 near_error("Mifare tag type %d not supported.", tgt_subtype);
1297                 return -1;
1298         }
1299
1300         /* Check if there's enough space on tag */
1301         tag = near_tag_get_tag(adapter_idx, target_idx);
1302         near_tag_get_data(tag, &tag_size);
1303
1304         if (tag_size < ndef->length) {
1305                 near_error("Not enough space on tag");
1306                 return -ENOSPC;
1307         }
1308
1309         /* Alloc global cookie */
1310         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
1311         if (!cookie)
1312                 return -ENOMEM;
1313
1314         /* Get the nfcid1 */
1315         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
1316                         &cookie->nfcid1_len);
1317         cookie->adapter_idx = adapter_idx;
1318         cookie->target_idx = target_idx;
1319         cookie->cb = cb;
1320
1321         cookie->ndef = ndef;
1322         /* Save ndef length */
1323         cookie->ndef_length = cookie->ndef->data[1];
1324         cookie->ndef->data[1] = 0;
1325
1326         /*
1327          * Check if all sectors are writable
1328          * if not, message may be too long to be written
1329          */
1330         cookie->acc_check_function = mifare_check_rights_NFC;
1331
1332         /*
1333          * Mifare Classic Tag needs to be unlocked before writing
1334          * This will check if public keys are allowed (NDEF could be "readable")
1335          */
1336         err = mifare_unlock_sector(MAD1_1ST_BLOCK,      /* related block */
1337                                         mifare_read_MAD1,       /* callback */
1338                                         cookie);        /* target data */
1339
1340         if (err < 0)
1341                 return mifare_release(err, cookie);
1342
1343         return 0;
1344 }