Integrate neard post 0.6 changes - handover code
[profile/ivi/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 #include <linux/nfc.h>
33
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 /* MAD1 sector structure. Start at block 0x00 */
114 struct MAD_1 {
115         uint8_t man_info[16];
116         uint16_t crc_dir;
117         uint16_t aids[MAD_V1_AIDS_LEN];
118         /* Trailer */
119         uint8_t key_A[MAD_KEY_LEN];
120         uint8_t access_cond[3];
121         uint8_t GPB;
122         uint8_t key_B[MAD_KEY_LEN];
123 } __attribute__((packed));
124
125 /* MAD2 sector structure. Start at block 0x40 */
126 struct MAD_2 {
127         uint16_t crc_dir;
128         uint16_t aids[MAD_V2_AIDS_LEN];
129         /* Trailer */
130         uint8_t key_A[MAD_KEY_LEN];
131         uint8_t access_cond[3];
132         uint8_t GPB;
133         uint8_t key_B[MAD_KEY_LEN];
134 } __attribute__((packed));
135
136 struct mifare_cookie {
137         uint32_t adapter_idx;
138         uint32_t target_idx;
139         uint8_t *nfcid1;
140         uint8_t nfcid1_len;
141
142         struct near_tag *tag;
143         near_tag_io_cb cb;
144         near_recv next_far_func;
145         int (*command)(void *data); /* read or write after unlocking sector */
146
147         /* For MAD access */
148         struct MAD_1 *mad_1;
149         struct MAD_2 *mad_2;
150         GSList *g_sect_list;            /* Global sectors list */
151
152         /* For read and write functions */
153         near_recv rws_next_fct;         /* next function */
154         int rws_block_start;            /* first block */
155         int rws_block_end;              /* last block */
156         int rws_completed;              /* read blocks */
157
158
159         /* For read only */
160         int rs_length;                  /* read length */
161         uint8_t *rs_pmem;               /* Stored read sector */
162         int rs_max_length;              /* available size */
163         uint8_t *nfc_data;
164         size_t nfc_data_length;
165
166         /* For write only */
167         struct near_ndef_message *ndef; /* message to write */
168         size_t ndef_length;             /* message length */
169 };
170
171 struct type2_cmd {
172         uint8_t cmd;
173         uint8_t block;
174         uint8_t data[];
175 } __attribute__((packed));
176
177 struct mf_write_cmd {
178         uint8_t cmd;
179         uint8_t block;
180         uint8_t data[DEFAULT_BLOCK_SIZE];
181 } __attribute__((packed));
182
183 struct mifare_cmd {
184         uint8_t cmd;
185         uint8_t block;
186         uint8_t key[MAD_KEY_LEN];
187         uint8_t nfcid[NFC_NFCID1_MAXSIZE];
188 } __attribute__((packed));
189
190 static int mifare_release(int err, void *data)
191 {
192         struct mifare_cookie *cookie = data;
193
194         DBG("%p", cookie);
195
196         if (cookie == NULL)
197                 return err;
198
199         if (err < 0 && cookie->cb) {
200                 cookie->cb(cookie->adapter_idx, cookie->target_idx, err);
201                 near_adapter_disconnect(cookie->adapter_idx);
202         }
203
204         /* Now free allocs */
205         g_free(cookie->nfcid1);
206         g_slist_free(cookie->g_sect_list);
207         g_free(cookie->mad_1);
208         g_free(cookie->mad_2);
209
210         if (cookie->ndef)
211                 g_free(cookie->ndef->data);
212
213         g_free(cookie->ndef);
214         g_free(cookie);
215         cookie = NULL;
216
217         return err;
218 }
219
220 /*
221  * Mifare_generic MAD unlock block function
222  * This function send unlock code to the tag, and so, allow access
223  * to the complete related sector.
224  */
225 static int mifare_unlock_sector(int block_id,
226                                 near_recv next_far_fct,
227                                 void *data)
228 {
229         struct mifare_cmd cmd;
230         struct mifare_cookie *cookie = data;
231         uint8_t *key_ref;
232
233         /*
234          * For MADs sectors we use public key A (a0a1a2a3a4a5) but
235 -        * for NFC sectors we use NFC_KEY_A (d3f7d3f7d3f7)
236          */
237         if ((block_id == MAD1_1ST_BLOCK) || (block_id == MAD2_1ST_BLOCK))
238                 key_ref = MAD_public_key;
239         else
240                 key_ref = MAD_NFC_key;
241
242          /* CMD AUTHENTICATION */
243         cmd.cmd = MF_CMD_AUTH_KEY_A;
244
245         /* Authenticate will be on the 1st block of the sector */
246         cmd.block = block_id;
247
248         /* Store the AUTH KEY */
249         memcpy(&cmd.key, key_ref, MAD_KEY_LEN);
250
251         /* add the UID */
252         memcpy(&cmd.nfcid, cookie->nfcid1, cookie->nfcid1_len);
253
254         return near_adapter_send(cookie->adapter_idx, (uint8_t *)&cmd,
255                 sizeof(cmd) - NFC_NFCID1_MAXSIZE + cookie->nfcid1_len,
256                 next_far_fct,
257                 cookie);
258 }
259
260 /*
261  * Common MIFARE Block read:
262  * Each call will read 16 bytes from tag... so to read 1 sector,
263  * it has to be called it 4 times or 16 times
264  * (minus 1 or not for the trailer block)
265  *
266  * data: mifare_cookie *mf_ck
267  * mf_ck->read_block: block number to read
268  */
269 static int mifare_read_block(uint8_t block_id,
270                                 void *data,
271                                 near_recv far_func)
272 {
273         struct type2_cmd cmd;
274         struct mifare_cookie *mf_ck = data;
275
276         cmd.cmd = MF_CMD_READ; /* MIFARE READ */
277         cmd.block = block_id;
278
279         return near_adapter_send(mf_ck->adapter_idx,
280                         (uint8_t *) &cmd, 2,
281                         far_func, data);
282 }
283
284 static int mifare_read_sector_cb(uint8_t *resp, int length, void *data)
285 {
286         struct mifare_cookie *mf_ck = data;
287         int err = -1;
288
289         if (length < 0) {
290                 err = length;
291                 goto out_err;
292         }
293
294         /* Save the data */
295         length = length - 1; /* ignore first byte - Reader byte */
296
297         /* save the length: */
298         mf_ck->rs_length = mf_ck->rs_length + length;
299
300         memcpy(mf_ck->rs_pmem + mf_ck->rws_completed * DEFAULT_BLOCK_SIZE,
301                         resp + 1,/* ignore reader byte */
302                         length);
303
304         /* Next block */
305         mf_ck->rws_completed = mf_ck->rws_completed + 1;
306
307         if ((mf_ck->rws_block_start + mf_ck->rws_completed)
308                                                 < mf_ck->rws_block_end)
309                 err = mifare_read_block(
310                                 (mf_ck->rws_block_start + mf_ck->rws_completed),
311                                 data,
312                                 mifare_read_sector_cb);
313         else {
314                 /* Now Process the callback ! */
315                 err = (*mf_ck->rws_next_fct)(mf_ck->rs_pmem,
316                                                 mf_ck->rs_length, data);
317         }
318
319         if (err < 0)
320                 goto out_err;
321         return err;
322
323 out_err:
324         return mifare_release(err, mf_ck);
325 }
326
327 static int mifare_read_sector_unlocked(uint8_t *resp, int length, void *data)
328 {
329         struct mifare_cookie *mf_ck = data;
330         int err;
331
332         if (length < 0) {
333                 err = length;
334                 return err;
335         }
336         /* And run the read process on the first block of the sector */
337         err = mifare_read_block(mf_ck->rws_block_start, data,
338                                 mifare_read_sector_cb);
339
340         if (err < 0)
341                 goto out_err;
342         return err;
343
344 out_err:
345         return err;
346 }
347
348 /*
349  * This function reads a complete sector, using block per block function.
350  * sector sizes can be:
351  * Sectors 0 to 31:
352  *      48 bytes: 3*16 no trailer
353  *      64 bytes: 4*16 with trailer
354  * Sectors 32 to 39:
355  *      240 bytes: 15*16 no trailer
356  *      256 bytes: 16*16 with trailer
357  *
358  * Unlock is done at the beginning of first sector.
359  */
360 static int mifare_read_sector(void *cookie,
361                         uint8_t *pmem,          /* memory to fill */
362                         uint16_t memsize,       /* remaining free size */
363                         uint8_t sector_id,      /* sector to read */
364                         near_bool_t trailer,    /* Add trailer or not */
365                         near_recv next_func)
366 {
367         struct mifare_cookie *mf_ck = cookie;
368         int err;
369         int blocks_count;
370
371         DBG("");
372
373         /* Prepare call values */
374         mf_ck->rs_pmem = pmem;                  /* where to store */
375         mf_ck->rs_max_length = memsize;         /* max size to store */
376         mf_ck->rs_length = 0;                   /* no bytes yet */
377         mf_ck->rws_completed = 0;               /* blocks read */
378
379         /* According to tag size, compute the correct block offset */
380         if (sector_id < T4K_BOUNDARY)
381                 mf_ck->rws_block_start = sector_id * 4;  /* 1st block to read */
382         else
383                 mf_ck->rws_block_start =
384                                 (sector_id - T4K_BOUNDARY) * 16 + T4K_BLK_OFF;
385
386         /* Find blocks_per_sect, according to position and trailer or not */
387         if (sector_id < T4K_BOUNDARY)
388                 blocks_count = (STD_BLK_PER_SECT + trailer);
389         else
390                 blocks_count = (EXT_BLK_PER_SECT + trailer);
391
392         mf_ck->rws_block_end = mf_ck->rws_block_start + blocks_count;
393
394         mf_ck->rws_next_fct = next_func;                /* leaving function */
395
396         /* Being on the first block of a sector, unlock it */
397         err = mifare_unlock_sector(mf_ck->rws_block_start,
398                         mifare_read_sector_unlocked, mf_ck);
399
400         return err;
401 }
402
403 static int mifare_read_NFC_loop(uint8_t *resp, int length, void *data)
404 {
405         struct mifare_cookie *mf_ck = data;
406         int err = 0;
407
408         DBG("");
409
410         if (length < 0) {
411                 err = length;
412                 return err;
413         }
414
415         /* ptr to the next read ptr */
416         mf_ck->nfc_data = mf_ck->nfc_data + length;
417
418         /* remaining free mem */
419         mf_ck->nfc_data_length = mf_ck->nfc_data_length - length;
420
421
422         /* Additional sectors to read ? */;
423         if (mf_ck->g_sect_list->next != NULL) {
424
425                 err = mifare_read_sector(data,  /* cookie */
426                         mf_ck->nfc_data,                /* where to store */
427                         (int) mf_ck->nfc_data_length,   /* global length */
428                         GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* id */
429                         NO_TRAILER,                     /* Trailer ? */
430                         mifare_read_NFC_loop);          /* next function */
431
432                 mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
433                                                 mf_ck->g_sect_list->data);
434
435                 if (err < 0)
436                         goto out_err;
437                 return err;
438         } else {
439                 GList *records;
440                 uint8_t *nfc_data;
441                 size_t nfc_data_length;
442
443                 DBG("Done reading");
444
445                 nfc_data = near_tag_get_data(mf_ck->tag, &nfc_data_length);
446                 if (nfc_data == NULL) {
447                         err = -ENOMEM;
448                         goto out_err;
449                 }
450
451                 records = near_tlv_parse(nfc_data, nfc_data_length);
452                 near_tag_add_records(mf_ck->tag, records, mf_ck->cb, 0);
453
454                 err = 0;
455         }
456
457 out_err:
458         return mifare_release(err, mf_ck);
459 }
460
461 /* Prepare read NFC loop */
462 static int mifare_read_NFC(void *data)
463 {
464         struct mifare_cookie *mf_ck = data;
465         int err;
466
467         /* save tag memory pointer to data_block */
468         mf_ck->nfc_data = near_tag_get_data(mf_ck->tag,
469                                         &mf_ck->nfc_data_length);
470
471         /* First read here: */
472         err = mifare_read_sector(data,          /* cookie */
473                 mf_ck->nfc_data,                /* where to store */
474                 mf_ck->nfc_data_length,         /* global length */
475                 GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* sector id */
476                 NO_TRAILER,                     /* Don't want Trailer */
477                 mifare_read_NFC_loop);          /* next function */
478
479         mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
480                                                 mf_ck->g_sect_list->data);
481         if (err < 0)
482                 goto out_err;
483         return err;
484
485 out_err:
486         return mifare_release(err, mf_ck);
487 }
488
489 static int mifare_process_MADs(void *data)
490 {
491         struct mifare_cookie *mf_ck = data;
492         int err;
493         int i;
494         int global_tag_size = 0;
495         int ioffset;
496
497         DBG("");
498
499         /* Parse MAD entries to get the global size and fill the array */
500         if (mf_ck->mad_1 == NULL) {
501                 err = -EINVAL;
502                 goto out_err;
503         }
504
505         for (i = 0; i < MAD_V1_AIDS_LEN; i++) {
506                 if (mf_ck->mad_1->aids[i] != NFC_AID_TAG)
507                         continue;
508
509                 /* Save in the global list */
510                 mf_ck->g_sect_list = g_slist_append(mf_ck->g_sect_list,
511                                                 GINT_TO_POINTER(i + 1));
512                 global_tag_size += SECTOR_SIZE;
513         }
514
515         /* Now MAD 2 */
516         ioffset = MAD_V1_AIDS_LEN + 1 + 1; /* skip 0x10 */
517         if (mf_ck->mad_2 == NULL)
518                 goto done_mad;
519
520         for (i = 0; i < MAD_V2_AIDS_LEN; i++) {
521                 if (mf_ck->mad_2->aids[i] != NFC_AID_TAG)
522                         continue;
523
524                 mf_ck->g_sect_list = g_slist_append( mf_ck->g_sect_list,
525                                                 GINT_TO_POINTER(ioffset + i));
526                 if (i < EXT_BLK_PER_SECT)
527                         global_tag_size += SECTOR_SIZE;
528                 else
529                         global_tag_size += BIG_SECTOR_SIZE;
530         }
531
532 done_mad:
533         /* n sectors, each sector is 3 blocks, each block is 16 bytes */
534         DBG("TAG Global size: [%d]", global_tag_size);
535
536         err = near_tag_add_data(mf_ck->adapter_idx,
537                                                 mf_ck->target_idx,
538                                                 NULL, /* Empty */
539                                                 global_tag_size);
540         if (err < 0)
541                 goto out_err;
542
543         mf_ck->tag = near_tag_get_tag(mf_ck->adapter_idx, mf_ck->target_idx);
544         if (mf_ck->tag == NULL) {
545                 err = -ENOMEM;
546                 goto out_err;
547         }
548
549         /* Time to read or write the NFC data */
550         err = mf_ck->command(mf_ck);
551
552         return err;
553
554 out_err:
555         return mifare_release(err, mf_ck);
556 }
557
558 /* Transitional function - async */
559 static int read_MAD2_complete(uint8_t *empty, int iempty, void *data)
560 {
561         return mifare_process_MADs(data);
562 }
563
564 /* This function reads the MAD2 sector */
565 static int mifare_read_MAD2(void *data)
566 {
567         struct mifare_cookie *mf_ck = data;
568         int err = 0;
569
570         DBG("");
571
572         /* As auth is ok, allocate Mifare Access Directory v1 */
573         mf_ck->mad_2 = g_try_malloc0(STD_SECTOR_SIZE);
574         if (mf_ck->mad_2 == NULL) {
575                 near_error("Memory allocation failed (MAD2)");
576                 err = -ENOMEM;
577                 goto out_err;
578         }
579
580         err = mifare_read_sector(data,
581                         (uint8_t *) mf_ck->mad_2,
582                         (int) STD_SECTOR_SIZE,
583                         MAD2_SECTOR,                    /* sector 0x10 */
584                         WITH_TRAILER,                   /* Want Trailer */
585                         read_MAD2_complete);
586
587         if (err < 0)
588                 goto out_err;
589         return err;
590
591 out_err:
592         return mifare_release(err, mf_ck);
593 }
594
595 /*
596  * This function checks, in MAD1, if there's a MAD2 directory
597  * available. This is is the case for 2K and 4K tag
598  * If MAD2 exists, read it, elsewhere process the current MAD
599  */
600 static int read_MAD1_complete(uint8_t *empty, int iempty, void *data)
601 {
602         struct mifare_cookie *mf_ck = data;
603         int err;
604
605         DBG("");
606
607         /* Check if there's a need to get MAD2 sector */
608         if ((mf_ck->mad_1->GPB & 0x03) == MAD2_GPB_BITS)
609                 err = mifare_read_MAD2(mf_ck);
610         else
611                 err = mifare_process_MADs(data);
612
613         return err;
614 }
615
616 /*
617  * Function called to read the first MAD sector
618  * MAD is mandatory
619  */
620 static int mifare_read_MAD1(uint8_t *resp, int length, void *data)
621 {
622         struct mifare_cookie *mf_ck = data;
623         int err = 0;
624
625         DBG("%p %d", data, length);
626
627         if (length < 0) {
628                 err = length;
629                 return err;
630         }
631
632         /*
633          * As auth is ok, allocate Mifare Access Directory v1
634          * allocated size is also STD_SECTOR_SIZE
635          */
636         mf_ck->mad_1 = g_try_malloc0(STD_SECTOR_SIZE);
637         if (mf_ck->mad_1 == NULL) {
638                 near_error("Memory allocation failed (MAD1)");
639                 err = -ENOMEM;
640                 goto out_err;
641         }
642
643         /* Call to mifare_read_sector */
644         err = mifare_read_sector(data,
645                         (uint8_t *)mf_ck->mad_1,        /* where to store */
646                         (int) STD_SECTOR_SIZE,          /* allocated size */
647                         MAD1_SECTOR,                    /* sector 0 */
648                         WITH_TRAILER,                   /* Want Trailer */
649                         read_MAD1_complete);
650
651         if (err < 0)
652                 goto out_err;
653         return err;
654
655 out_err:
656         return mifare_release(err, mf_ck);
657 }
658
659 /*
660  * MIFARE: entry point:
661  * Read all the MAD sectors (0x00, 0x10) to get the Application Directory
662  * entries.
663  * On sector 0x00, App. directory is on block 0x01 & block 0x02
664  * On sector 0x10, App. directory is on block 0x40, 0x41 & 0x42
665  * On reading, CRC is ignored.
666  */
667 int mifare_read(uint32_t adapter_idx, uint32_t target_idx,
668                 near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
669 {
670         struct mifare_cookie *cookie;
671         int err;
672
673         DBG("");
674
675         /*Check supported and tested Mifare type */
676         switch (tgt_subtype) {
677         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
678         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
679                 break;
680         default:
681                 near_error("Mifare tag type [%d] not supported.", tgt_subtype);
682                 return -1;
683         }
684
685         /* Alloc global cookie */
686         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
687         if (cookie == NULL)
688                 return -ENOMEM;
689
690         /* Get the nfcid1 */
691         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
692                                 &cookie->nfcid1_len);
693         cookie->adapter_idx = adapter_idx;
694         cookie->target_idx = target_idx;
695         cookie->cb = cb;
696         cookie->command = mifare_read_NFC;
697
698         /*
699          * Need to unlock before reading
700          * This will check if public keys are allowed (and, so, NDEF could
701          * be "readable"...
702          */
703         err = mifare_unlock_sector(MAD1_1ST_BLOCK,      /* related block */
704                                 mifare_read_MAD1,       /* callback function */
705                                 cookie);                /* target data */
706         if (err < 0)
707                 return mifare_release(err, cookie);
708
709         return 0;
710 }
711
712 static int check_presence(uint8_t *resp, int length, void *data)
713 {
714         struct mifare_cookie *cookie = data;
715         int err = 0;
716
717         DBG("%d", length);
718
719         if (length < 0)
720                 err = -EIO;
721
722         if (cookie->cb)
723                 cookie->cb(cookie->adapter_idx, cookie->target_idx, err);
724
725         return err;
726 }
727
728 int mifare_check_presence(uint32_t adapter_idx, uint32_t target_idx,
729                         near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
730 {
731         struct mifare_cmd cmd;
732         struct mifare_cookie *cookie;
733         uint8_t *key_ref = MAD_public_key;
734         int err;
735
736         DBG("");
737
738         /* Check supported and tested Mifare type */
739         switch (tgt_subtype) {
740         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
741         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
742                 break;
743         default:
744                 near_error("Mifare tag type %d not supported.", tgt_subtype);
745                 return -1;
746         }
747
748         /* Alloc global cookie */
749         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
750         if (cookie == NULL)
751                 return -ENOMEM;
752
753         /* Get the nfcid1 */
754         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
755                                         &cookie->nfcid1_len);
756         cookie->adapter_idx = adapter_idx;
757         cookie->target_idx = target_idx;
758         cookie->cb = cb;
759
760         /*
761          * To check presence of Mifare Classic Tag,
762          * send authentication command instead of read one
763          */
764         cmd.cmd = MF_CMD_AUTH_KEY_A;
765
766         /* Authenticate the 1st block of the MAD sector */
767         cmd.block = MAD1_1ST_BLOCK;
768
769         /* Store the AUTH KEY */
770         memcpy(&cmd.key, key_ref, MAD_KEY_LEN);
771
772         /* add the UID */
773         memcpy(&cmd.nfcid, cookie->nfcid1, cookie->nfcid1_len);
774
775         err = near_adapter_send(cookie->adapter_idx,
776                         (uint8_t *) &cmd,
777                         sizeof(cmd) - NFC_NFCID1_MAXSIZE + cookie->nfcid1_len,
778                         check_presence,
779                         cookie);
780
781         if (err < 0)
782                 goto out_err;
783
784         return err;
785
786 out_err:
787         mifare_release(err, cookie);
788
789         return err;
790 }
791
792 /*
793  * Common MIFARE Block write:
794  * Each call will write 16 bytes to tag... so to write 1 sector,
795  * it has to be called it 4 or 16 times (minus 1 for the trailer block)
796  */
797 static int mifare_write_block(uint8_t block_id, void *data,
798                                 near_recv far_func)
799 {
800         struct mf_write_cmd cmd;
801         struct mifare_cookie *mf_ck = data;
802
803         memset(&cmd, 0, sizeof(cmd));
804         cmd.cmd = MF_CMD_WRITE; /* MIFARE WRITE */
805         cmd.block = block_id;
806
807         if ((mf_ck->ndef->offset + DEFAULT_BLOCK_SIZE) <
808                         mf_ck->ndef->length) {
809                 memcpy(cmd.data, mf_ck->ndef->data +
810                                 mf_ck->ndef->offset, DEFAULT_BLOCK_SIZE);
811                 mf_ck->ndef->offset += DEFAULT_BLOCK_SIZE;
812         } else {
813                 memcpy(cmd.data, mf_ck->ndef->data + mf_ck->ndef->offset,
814                                 mf_ck->ndef->length - mf_ck->ndef->offset);
815                 mf_ck->ndef->offset = mf_ck->ndef->length + 1;
816         }
817
818         return near_adapter_send(mf_ck->adapter_idx,
819                                 (uint8_t *) &cmd, sizeof(cmd),
820                                 far_func, data);
821 }
822
823 static int mifare_correct_length_cb(uint8_t *resp, int length, void *data)
824 {
825         struct mifare_cookie *mf_ck = data;
826
827         DBG("Done writing");
828
829         if (mf_ck->cb)
830                 mf_ck->cb(mf_ck->adapter_idx, mf_ck->target_idx, 0);
831
832         return mifare_release(0, mf_ck);
833 }
834
835 /* After writing ndef message, its length has to be updated */
836 static int mifare_correct_length(uint8_t *resp, int length, void *data)
837 {
838         struct mifare_cookie *mf_ck = data;
839
840         DBG("");
841
842         /* Correct length field */
843         mf_ck->ndef->data[1] = mf_ck->ndef_length;
844         /* and ndef offset so it points to the beginning */
845         mf_ck->ndef->offset = 0;
846
847         /* Run the write process only on the first block of the sector */
848         return mifare_write_block(NFC_1ST_BLOCK, mf_ck,
849                                         mifare_correct_length_cb);
850 }
851
852 static int mifare_write_sector_cb(uint8_t *resp, int length, void *data)
853 {
854         struct mifare_cookie *mf_ck = data;
855         int err;
856
857         /* Next block */
858         mf_ck->rws_completed = mf_ck->rws_completed + 1;
859
860         /* Check if it's the last block */
861         if ((mf_ck->rws_block_start + mf_ck->rws_completed)
862                         < mf_ck->rws_block_end) {
863                 /* then check if there's still data to write */
864                 if (mf_ck->ndef->offset < mf_ck->ndef->length)
865                         err = mifare_write_block(
866                                 mf_ck->rws_block_start + mf_ck->rws_completed,
867                                 data, mifare_write_sector_cb);
868                 else
869                         /* No more Data to write */
870                         /* Correct length of the ndef message */
871                         err = mifare_unlock_sector(NFC_1ST_BLOCK,
872                                                 mifare_correct_length, mf_ck);
873         } else {
874                 /* Process the callback */
875                 err = (*mf_ck->rws_next_fct)(resp, length, data);
876         }
877
878         if (err < 0)
879                 return mifare_release(err, mf_ck);
880
881         return err;
882
883 }
884
885 static int mifare_write_sector_unlocked(uint8_t *resp, int length, void *data)
886 {
887         struct mifare_cookie *mf_ck = data;
888
889         /* Run the write process on the first block of the sector */
890         return mifare_write_block(mf_ck->rws_block_start, data,
891                                         mifare_write_sector_cb);
892 }
893
894 /*
895  * This function writes a complete sector, using block per block function.
896  * sector sizes can be:
897  * Sectors 0 to 31:
898  *      48 bytes: 3*16 (no trailer)
899  * Sectors 32 to 39:
900  *      240 bytes: 15*16 (no trailer)
901  *
902  * Unlock is done at the beginning of each sector.
903  */
904 static int mifare_write_sector(void *cookie,
905                                 uint8_t sector_id,      /* sector to write */
906                                 near_recv next_func)
907 {
908         struct mifare_cookie *mf_ck = cookie;
909         int blocks_count;
910
911         DBG("");
912
913         /* Prepare call values */
914
915         /* According to tag size, compute the correct block offset */
916         if (sector_id < T4K_BOUNDARY)
917                 mf_ck->rws_block_start = sector_id * STD_BLK_SECT_TRAILER;
918         else
919                 mf_ck->rws_block_start = T4K_BLK_OFF +
920                         (sector_id - T4K_BOUNDARY) * EXT_BLK_SECT_TRAILER;
921
922         /* Find blocks_per_sect, according to position, no trailer */
923         if (sector_id < T4K_BOUNDARY)
924                 blocks_count = STD_BLK_PER_SECT;
925         else
926                 blocks_count = EXT_BLK_PER_SECT;
927
928         mf_ck->rws_block_end = mf_ck->rws_block_start + blocks_count;
929         mf_ck->rws_completed = 0;
930         mf_ck->rws_next_fct = next_func;
931
932         /* Being on the first block of the sector, unlock it */
933         return mifare_unlock_sector(mf_ck->rws_block_start,
934                                         mifare_write_sector_unlocked, mf_ck);
935 }
936
937 static int mifare_write_NFC_loop(uint8_t *resp, int length, void *data)
938 {
939         struct mifare_cookie *mf_ck = data;
940         int err = 0;
941
942         if (length < 0 || resp[0] != 0) {
943                 err = -EIO;
944                 goto out_err;
945         }
946
947         /* Something more to write? */;
948         if (mf_ck->ndef->offset < mf_ck->ndef->length) {
949                 err = mifare_write_sector(data,         /* cookie */
950                                 GPOINTER_TO_INT(mf_ck->g_sect_list->data),
951                                 mifare_write_NFC_loop); /* next function */
952
953                 mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
954                                                 mf_ck->g_sect_list->data);
955
956                 if (err < 0)
957                         goto out_err;
958
959         } else {
960                 /* Correct length of an NDEF message */
961                 err = mifare_unlock_sector(NFC_1ST_BLOCK,
962                                         mifare_correct_length, mf_ck);
963
964                 if (err < 0)
965                         goto out_err;
966         }
967
968         return err;
969 out_err:
970         return mifare_release(err, mf_ck);
971 }
972
973 static int mifare_write_NFC(void *data)
974 {
975         struct mifare_cookie *mf_ck = data;
976         int err;
977
978         DBG("");
979
980         mf_ck->rws_completed = 0;       /* written blocks */
981
982         /* First write here: */
983         err = mifare_write_sector(data,         /* cookie */
984                 GPOINTER_TO_INT(mf_ck->g_sect_list->data), /* sector id */
985                 mifare_write_NFC_loop);         /* next function */
986
987         mf_ck->g_sect_list = g_slist_remove(mf_ck->g_sect_list,
988                                                 mf_ck->g_sect_list->data);
989
990         if (err < 0)
991                 return mifare_release(err, mf_ck);
992
993         return err;
994 }
995
996 int mifare_write(uint32_t adapter_idx, uint32_t target_idx,
997                         struct near_ndef_message *ndef,
998                         near_tag_io_cb cb, enum near_tag_sub_type tgt_subtype)
999 {
1000         struct mifare_cookie *cookie;
1001         struct near_tag *tag;
1002         size_t tag_size;
1003         int err;
1004
1005         DBG("");
1006
1007         /* Check supported and tested Mifare type */
1008         switch (tgt_subtype) {
1009         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_1K:
1010         case NEAR_TAG_NFC_T2_MIFARE_CLASSIC_4K:
1011                 break;
1012         default:
1013                 near_error("Mifare tag type %d not supported.", tgt_subtype);
1014                 return -1;
1015         }
1016
1017         /* Check if there's enough space on tag */
1018         tag = near_tag_get_tag(adapter_idx, target_idx);
1019         near_tag_get_data(tag, &tag_size);
1020
1021         if (tag_size < ndef->length) {
1022                 near_error("Not enough space on tag");
1023                 return -ENOSPC;
1024         }
1025
1026         /* Alloc global cookie */
1027         cookie = g_try_malloc0(sizeof(struct mifare_cookie));
1028         if (cookie == NULL)
1029                 return -ENOMEM;
1030
1031         /* Get the nfcid1 */
1032         cookie->nfcid1 = near_tag_get_nfcid(adapter_idx, target_idx,
1033                         &cookie->nfcid1_len);
1034         cookie->adapter_idx = adapter_idx;
1035         cookie->target_idx = target_idx;
1036         cookie->cb = cb;
1037
1038         cookie->command = mifare_write_NFC;
1039         cookie->ndef = ndef;
1040         /* Save ndef length */
1041         cookie->ndef_length = cookie->ndef->data[1];
1042         cookie->ndef->data[1] = 0;
1043         /*
1044          * Mifare Classic Tag needs to be unlocked before writing
1045          * This will check if public keys are allowed (NDEF could be "readable")
1046          */
1047         err = mifare_unlock_sector(MAD1_1ST_BLOCK,      /* related block */
1048                                         mifare_read_MAD1,       /* callback */
1049                                         cookie);        /* target data */
1050
1051         if (err < 0)
1052                 return mifare_release(err, cookie);
1053
1054         return 0;
1055 }