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