Implement 14443-4 (T=CL) PPS
[librfid] / rfid_proto_tcl.c
1 /* ISO 14443-4 (T=CL) implementation, PCD side.
2  *
3  * (C) 2005 by Harald Welte <laforge@gnumonks.org>
4  *
5  */
6
7 /*
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License version 2 
10  *  as published by the Free Software Foundation
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <errno.h>
27
28 #include <rfid/rfid.h>
29 #include <rfid/rfid_protocol_tcl.h>
30 #include <rfid/rfid_protocol.h>
31 #include <rfid/rfid_layer2.h>
32 #include <rfid/rfid_layer2_iso14443b.h>
33
34 #include <rfid/rfid_asic.h>
35 #include <rfid/rfid_reader.h>
36
37 #include "rfid_iso14443_common.h"
38
39
40 static unsigned int sfgi_to_sfgt(struct rfid_protocol_handle *h, 
41                                  unsigned char sfgi)
42 {
43         unsigned int multiplier;
44         unsigned int tmp;
45
46         if (sfgi > 14)
47                 sfgi = 14;
48
49         multiplier = 1 << sfgi; /* 2 to the power of sfgi */
50
51         /* ISO 14443-4:2000(E) Section 5.2.5:
52          * (256 * 16 / h->l2h->rh->ah->fc) * (2 ^ sfgi) */
53         tmp = (unsigned int) 1000000 * 256 * 16;
54
55         return (tmp / h->l2h->rh->ah->fc) * multiplier;
56 }
57
58 static unsigned int fwi_to_fwt(struct rfid_protocol_handle *h, 
59                                 unsigned char fwi)
60 {
61         unsigned int multiplier, tmp;
62
63         if (fwi > 14)
64                 fwi = 14;
65
66         multiplier  = 1 << fwi; /* 2 to the power of fwi */
67
68         /* ISO 14443-4:2000(E) Section 7.2.:
69          * (256*16 / h->l2h->rh->ah->fc) * (2 ^ fwi) */
70
71         tmp = (unsigned int) 1000000 * 256 * 16;
72
73         return (tmp / h->l2h->rh->ah->fc) * multiplier;
74 }
75
76 /* 4.9seconds as microseconds (4.9 billion seconds) exceeds 2^32 */
77 #define activation_fwt(x) (((u_int64_t)1000000 * 65536 / x->l2h->rh->ah->fc))
78 #define deactivation_fwt(x) activation_fwt(x)
79
80 static int
81 tcl_parse_ats(struct rfid_protocol_handle *h, 
82                 unsigned char *ats, unsigned int size)
83 {
84         unsigned char len = ats[0];
85         unsigned char t0;
86         unsigned char *cur;
87
88         if (len == 0 || size == 0) 
89                 return -1;
90
91         if (size < len)
92                 len = size;
93
94         h->priv.tcl.ta = 0;
95
96         if (len == 1) {
97                 /* FIXME: assume some default values */
98                 h->priv.tcl.fsc = 32;
99                 h->priv.tcl.ta = 0x80;  /* 0x80 (same d for both dirs) */
100                 h->priv.tcl.sfgt = sfgi_to_sfgt(h, 0);
101                 if (h->l2h->l2->id == RFID_LAYER2_ISO14443A) {
102                         /* Section 7.2: fwi default for type A is 4 */
103                         h->priv.tcl.fwt = fwi_to_fwt(h, 4);
104                 } else {
105                         /* Section 7.2: fwi for type B is always in ATQB */
106                         /* Value is assigned in tcl_connect() */
107                         /* This function is never called for Type B, since it has no (R)ATS */
108                 }
109                 return 0;
110         }
111
112         /* guarateed to be at least 2 bytes in size */
113
114         t0 = ats[1];
115         cur = &ats[2];
116
117         iso14443_fsdi_to_fsd(&h->priv.tcl.fsc, t0 & 0x0f);
118
119         if (t0 & (1 << 4)) {
120                 /* TA is transmitted */
121                 h->priv.tcl.ta = *cur++;
122         }
123
124         if (t0 & (1 << 5)) {
125                 /* TB is transmitted */
126                 h->priv.tcl.sfgt = sfgi_to_sfgt(h, *cur & 0x0f);
127                 h->priv.tcl.fwt = fwi_to_fwt(h, (*cur & 0xf0) >> 4);
128                 cur++;
129         }
130
131         if (t0 & (1 << 6)) {
132                 /* TC is transmitted */
133                 if (*cur & 0x01)
134                         h->priv.tcl.flags |= TCL_HANDLE_F_NAD_SUPPORTED;
135                 if (*cur & 0x02)
136                         h->priv.tcl.flags |= TCL_HANDLE_F_CID_SUPPORTED;
137                 cur++;
138         }
139
140         h->priv.tcl.historical_len = (ats+len) - cur;
141         h->priv.tcl.historical_bytes = cur;
142
143         return 0;
144 }
145
146
147 /* request an ATS from the PICC */
148 static int
149 tcl_request_ats(struct rfid_protocol_handle *h)
150 {
151         int ret;
152         unsigned char rats[2];
153         unsigned char fsdi;
154
155         if (h->priv.tcl.state != TCL_STATE_INITIAL)
156                 return -1;
157
158         ret = iso14443_fsd_to_fsdi(&fsdi, h->priv.tcl.fsd);
159         if (ret < 0) {
160                 DEBUGP("unable to encode FSD of %u as FSDI\n", h->priv.tcl.fsd);
161                 return ret;
162         }
163
164         rats[0] = 0xe0;
165         rats[1] = (h->priv.tcl.cid & 0x0f) | ((fsdi << 4) & 0xf0);
166
167         /* transcieve (with CRC) */
168         ret = h->l2h->l2->fn.transcieve(h->l2h, rats, 2, h->priv.tcl.ats,
169                                        &h->priv.tcl.ats_len, activation_fwt(h),
170                                        TCL_TRANSP_F_TX_CRC);
171         if (ret < 0) {
172                 DEBUGP("transcieve of rats failed\n");
173                 h->priv.tcl.state = TCL_STATE_RATS_SENT;
174                 /* FIXME: retransmit */
175                 return ret;
176         }
177         h->priv.tcl.state = TCL_STATE_ATS_RCVD;
178
179         ret = tcl_parse_ats(h, h->priv.tcl.ats, h->priv.tcl.ats_len);
180         if (ret < 0) {
181                 DEBUGP("parsing of ats failed\n");
182                 return ret;
183         }
184
185         return 0;
186 }
187
188 #define ATS_TA_DIV_2    1
189 #define ATS_TA_DIV_4    2
190 #define ATS_TA_DIV_8    4
191
192 #define PPS_DIV_8       3
193 #define PPS_DIV_4       2
194 #define PPS_DIV_2       1
195 #define PPS_DIV_1       0
196 static unsigned char d_to_di(struct rfid_protocol_handle *h, unsigned char D)
197 {
198         static char DI;
199         unsigned int speed = h->l2h->rh->reader->iso14443a.speed;
200         
201         if ((D & ATS_TA_DIV_8) && (speed & RFID_READER_SPEED_848K))
202                 DI = PPS_DIV_8;
203         else if ((D & ATS_TA_DIV_4) && (speed & RFID_READER_SPEED_424K))
204                 DI = PPS_DIV_4;
205         else if ((D & ATS_TA_DIV_2) && (speed & RFID_READER_SPEED_212K))
206                 DI = PPS_DIV_2;
207         else
208                 DI = PPS_DIV_1;
209
210         return DI;
211 }
212
213
214 /* start a PSS run (autimatically configure highest possible speed */
215 static int 
216 tcl_do_pps(struct rfid_protocol_handle *h)
217 {
218         int ret;
219         unsigned char ppss[3];
220         unsigned char pps_response[1];
221         unsigned int rx_len = 1;
222         unsigned char Dr, Ds, DrI, DsI;
223
224         if (h->priv.tcl.state != TCL_STATE_ATS_RCVD)
225                 return -1;
226
227         Dr = h->priv.tcl.ta & 0x07;
228         Ds = h->priv.tcl.ta & 0x70 >> 4;
229
230         if (Dr != Ds && !(h->priv.tcl.ta & 0x80)) {
231                 /* device supports different divisors for rx and tx, but not ?!? */
232                 DEBUGP("PICC has contradictory TA, aborting PPS\n");
233                 return -1;
234         };
235
236         /* ISO 14443-4:2000(E) Section 5.3. */
237
238         ppss[0] = 0xd0 & (h->priv.tcl.cid & 0x0f);
239         ppss[1] = 0x11;
240
241         /* FIXME: deal with different speed for each direction */
242         DrI = d_to_di(h, Dr);
243         DsI = d_to_di(h, Ds);
244
245         ppss[2] = (ppss[2] & 0xf0) | (DrI | DsI << 2);
246
247         ret = h->l2h->l2->fn.transcieve(h->l2h, ppss, 3, pps_response,
248                                         &rx_len, h->priv.tcl.fwt,
249                                         TCL_TRANSP_F_TX_CRC);
250         if (ret < 0)
251                 return ret;
252
253         if (pps_response[0] != ppss[0]) {
254                 DEBUGP("PPS Response != PPSS\n");
255                 return -1;
256         }
257         
258         h->priv.tcl.state = TCL_STATE_ESTABLISHED;
259
260         return 0;
261 }
262
263
264 static int
265 tcl_build_prologue2(struct tcl_handle *th, 
266                     unsigned char *prlg, unsigned int *prlg_len, 
267                     unsigned char pcb)
268 {
269         *prlg_len = 1;
270
271         *prlg = pcb;
272
273         if (th->toggle) {
274                 /* we've sent a toggle bit last time */
275                 th->toggle = 0;
276         } else {
277                 /* we've not sent a toggle last time: send one */
278                 th->toggle = 1;
279                 *prlg |= 0x01;
280         }
281
282         if (th->flags & TCL_HANDLE_F_CID_USED) {
283                 /* ISO 14443-4:2000(E) Section 7.1.1.2 */
284                 *prlg |= TCL_PCB_CID_FOLLOWING;
285                 (*prlg_len)++;
286                 prlg[*prlg_len] = th->cid & 0x0f;
287         }
288
289         /* nad only for I-block (0xc0 == 00) */
290         if ((th->flags & TCL_HANDLE_F_NAD_USED) &&
291             ((pcb & 0xc0) == 0x00)) {
292                 /* ISO 14443-4:2000(E) Section 7.1.1.3 */
293                 /* FIXME: in case of chaining only for first frame */
294                 *prlg |= TCL_PCB_NAD_FOLLOWING;
295                 prlg[*prlg_len] = th->nad;
296                 (*prlg_len)++;
297         }
298
299         return 0;
300 }
301
302 static int
303 tcl_build_prologue_i(struct tcl_handle *th,
304                      unsigned char *prlg, unsigned int *prlg_len)
305 {
306         /* ISO 14443-4:2000(E) Section 7.1.1.1 */
307         return tcl_build_prologue2(th, prlg, prlg_len, 0x02);
308 }
309
310 static int
311 tcl_build_prologue_r(struct tcl_handle *th,
312                      unsigned char *prlg, unsigned int *prlg_len,
313                      unsigned int nak)
314 {
315         unsigned char pcb = 0xa2;
316         /* ISO 14443-4:2000(E) Section 7.1.1.1 */
317
318         if (nak)
319                 pcb |= 0x10;
320
321         return tcl_build_prologue2(th, prlg, prlg_len, pcb);
322 }
323
324 static int
325 tcl_build_prologue_s(struct tcl_handle *th,
326                      unsigned char *prlg, unsigned int *prlg_len)
327 {
328         /* ISO 14443-4:2000(E) Section 7.1.1.1 */
329
330         /* the only S-block from PCD->PICC is DESELECT,
331          * well, actually there is the S(WTX) response. */
332         return tcl_build_prologue2(th, prlg, prlg_len, 0xc2);
333 }
334
335 /* FIXME: WTXM implementation */
336
337 static int tcl_prlg_len(struct tcl_handle *th)
338 {
339         int prlg_len = 1;
340
341         if (th->flags & TCL_HANDLE_F_CID_USED)
342                 prlg_len++;
343
344         if (th->flags & TCL_HANDLE_F_NAD_USED)
345                 prlg_len++;
346
347         return prlg_len;
348 }
349
350 #define max_net_tx_framesize(x) (x->fsc - tcl_prlg_len(x))
351
352 static int
353 tcl_connect(struct rfid_protocol_handle *h)
354 {
355         int ret; 
356
357         if (h->priv.tcl.state != TCL_STATE_DESELECTED &&
358             h->priv.tcl.state != TCL_STATE_INITIAL)
359                 return -1;
360
361         switch (h->l2h->l2->id) {
362         case RFID_LAYER2_ISO14443A:
363                 /* Start Type A T=CL Activation Sequence */
364                 ret = tcl_request_ats(h);
365                 if (ret < 0)
366                         return ret;
367
368                 /* Only do PPS if any non-default divisors supported */
369                 if (h->priv.tcl.ta & 0x77) {
370                         ret = tcl_do_pps(h);
371                         if (ret < 0)
372                                 return ret;
373                 }
374                 break;
375         case RFID_LAYER2_ISO14443B:
376                 /* initialized T=CL state from Type B Activation Data */
377                 h->priv.tcl.cid = h->l2h->priv.iso14443b.cid;
378                 h->priv.tcl.fsc = h->l2h->priv.iso14443b.fsc;
379                 h->priv.tcl.fsd = h->l2h->priv.iso14443b.fsd;
380                 h->priv.tcl.fwt = h->l2h->priv.iso14443b.fwt;
381
382                 /* what about ta? sfgt? */
383
384                 if (h->l2h->priv.iso14443b.flags & ISO14443B_CID_SUPPORTED)
385                         h->priv.tcl.flags |= TCL_HANDLE_F_CID_SUPPORTED;
386                 if (h->l2h->priv.iso14443b.flags & ISO14443B_NAD_SUPPORTED)
387                         h->priv.tcl.flags |= TCL_HANDLE_F_NAD_SUPPORTED;
388
389                 switch (h->l2h->priv.iso14443b.state) {
390                         case ISO14443B_STATE_SELECTED:
391                                 h->priv.tcl.state = TCL_STATE_ATS_RCVD;
392                                 break;
393                         case ISO14443B_STATE_ATTRIB_SENT:
394                                 h->priv.tcl.state = TCL_STATE_RATS_SENT;
395                                 break;
396                 }
397
398                 /* PUPI will be presented as ATS/historical bytes */
399                 memcpy(h->priv.tcl.ats, h->l2h->priv.iso14443b.pupi, 4);
400                 h->priv.tcl.ats_len = 4;
401                 h->priv.tcl.historical_bytes = h->priv.tcl.ats;
402
403                 break;
404         default:
405                 DEBUGP("unsupported l2: %u\n", h->l2h->l2->id);
406                 return -1;
407                 break;
408         }
409
410         return 0;
411 }
412
413 static int
414 tcl_deselect(struct rfid_protocol_handle *h)
415 {
416         /* ISO 14443-4:2000(E) Section 8 */
417         int ret;
418         unsigned char frame[3];         /* 3 bytes prologue, no information */
419         unsigned char rx[3];
420         unsigned int rx_len = sizeof(rx);
421         unsigned int prlg_len;
422         struct tcl_handle *th = &h->priv.tcl;
423
424         if (th->state != TCL_STATE_ESTABLISHED) {
425                 /* FIXME: not sure whether deselect is possible here,
426                  * probably better send a HLTA? */
427         }
428
429         /* build DESELECT S-block */
430         ret = tcl_build_prologue_s(th, frame, &prlg_len);
431         if (ret < 0)
432                 return ret;
433
434         ret = h->l2h->l2->fn.transcieve(h->l2h, frame, prlg_len, rx,
435                                      &rx_len, deactivation_fwt(h),
436                                      TCL_TRANSP_F_TX_CRC);
437         if (ret < 0) {
438                 /* FIXME: retransmit, HLT(A|B) */
439                 return ret;
440         }
441
442         th->state = TCL_STATE_DESELECTED;
443
444         return 0;
445 }
446
447 #define is_s_block(x) ((x & 0xc0) == 0xc0)
448 #define is_r_block(x) ((x & 0xc0) == 0x80)
449 #define is_i_block(x) ((x & 0xc0) == 0x00)
450
451 static int
452 tcl_transcieve(struct rfid_protocol_handle *h,
453                 const unsigned char *tx_data, unsigned int tx_len,
454                 unsigned char *rx_data, unsigned int *rx_len,
455                 unsigned int timeout, unsigned int flags)
456 {
457         int ret;
458         unsigned char *tx_buf, *rx_buf;
459         unsigned int prlg_len;
460         struct tcl_handle *th = &h->priv.tcl;
461
462         unsigned char *_tx;
463         unsigned int _tx_len, _timeout;
464         unsigned char wtx_resp[3];
465
466         if (tx_len > max_net_tx_framesize(th)) {
467                 /* slow path: we need to use chaining */
468                 return -1;
469         }
470
471         tx_buf = malloc(tcl_prlg_len(th) + tx_len);
472         if (!tx_buf) {
473                 ret = -ENOMEM;
474                 goto out;
475         }
476         rx_buf = malloc(tcl_prlg_len(th) + *rx_len);
477         if (!rx_buf) {
478                 ret = -ENOMEM;
479                 goto out_txb;
480         }
481
482         if (tcl_build_prologue_i(th, tx_buf, &prlg_len) < 0) {
483                 ret = -1;
484                 goto out_rxb;
485         }
486         memcpy(tx_buf + prlg_len, tx_data, tx_len);
487
488         /* intialize to data-to-be-transferred */
489         _tx = tx_buf;
490         _tx_len = tx_len+prlg_len;
491         _timeout = th->fwt;
492
493 do_tx:
494         ret = h->l2h->l2->fn.transcieve(h->l2h, _tx, _tx_len,
495                                         rx_buf, rx_len, _timeout, 0);
496         if (ret < 0)
497                 goto out_rxb;
498
499         if ((*rx_buf & 0x01) != h->priv.tcl.toggle) {
500                 DEBUGP("response with wrong toggle bit\n");
501                 goto out_rxb;
502         }
503
504         //if (*rx_len )
505         //
506
507         if (is_r_block(*rx_buf)) {
508                 unsigned int txed = _tx - tx_buf;
509                 /* Handle ACK frame in case of chaining */
510                 if (*rx_buf & TCL_PCB_CID_FOLLOWING) {
511                         if (*(rx_buf+1) != h->priv.tcl.cid) {
512                                 DEBUGP("CID %u is not valid\n", *(rx_buf)+1);
513                                 goto out_rxb;
514                         }
515                 }
516                 /* set up parameters for next frame in chain */
517                 if (txed < tx_len) {
518                         /* move tx pointer by the amount of bytes transferred
519                          * in last frame */
520                         _tx += _tx_len;
521                         _tx_len = (tx_len - txed);
522                         if (_tx_len > max_net_tx_framesize(th)) {
523                                 /* not last frame in chain */
524                                 _tx_len = max_net_tx_framesize(th);
525                         } else {
526                                 /* last frame in chain */
527                         }
528                         goto do_tx;
529                 } else {
530                         DEBUGP("Received ACK in response to last frame in "
531                                "chain?!? Expected I-frame.\n");
532                         ret = -1;
533                         goto out_rxb;
534                 }
535         } else if (is_s_block(*rx_buf)) {
536                 unsigned char inf;
537                 unsigned int prlg_len;
538
539                 /* Handle Wait Time Extension */
540                 if (*rx_buf & TCL_PCB_CID_FOLLOWING) {
541                         if (*rx_len < 3) {
542                                 DEBUGP("S-Block with CID but short len\n");
543                                 ret = -1;
544                                 goto out_rxb;
545                         }
546                         if (*(rx_buf+1) != h->priv.tcl.cid) {
547                                 DEBUGP("CID %u is not valid\n", *(rx_buf)+1);
548                                 goto out_rxb;
549                         }
550                         inf = *(rx_buf+2);
551                 } else
552                         inf = *(rx_buf+1);
553
554                 if ((*rx_buf & 0x30) != 0x30) {
555                         DEBUGP("S-Block but not WTX?\n");
556                         ret = -1;
557                         goto out_rxb;
558                 }
559                 inf &= 0x3f;    /* only lower 6 bits code WTXM */
560                 if (inf == 0 || (inf >= 60 && inf <= 63)) {
561                         DEBUGP("WTXM %u is RFU!\n", inf);
562                         ret = -1;
563                         goto out_rxb;
564                 }
565                 
566                 /* Acknowledge WTXM */
567                 tcl_build_prologue_s(&h->priv.tcl, wtx_resp, &prlg_len);
568                 /* set two bits that make this block a wtx */
569                 wtx_resp[0] |= 0x30;
570                 wtx_resp[prlg_len] = inf;
571                 _tx = wtx_resp;
572                 _tx_len = prlg_len+1;
573                 _timeout = th->fwt * inf;
574
575                 /* start over with next transcieve */
576                 goto do_tx; /* FIXME: do transcieve locally since we use
577                                 totally different buffer */
578
579         } else if (is_i_block(*rx_buf)) {
580                 unsigned char *inf = rx_buf+1;
581                 /* we're actually receiving payload data */
582
583                 if (*rx_buf & TCL_PCB_CID_FOLLOWING) {
584                         if (*(rx_buf+1) != h->priv.tcl.cid) {
585                                 DEBUGP("CID %u is not valid\n", *(rx_buf)+1);
586                                 goto out_rxb;
587                         }
588                         inf++;
589                 }
590                 if (*rx_buf & TCL_PCB_NAD_FOLLOWING) {
591                         inf++;
592                 }
593                 memcpy(rx_data, inf, *rx_len - (inf - rx_buf));
594
595                 if (*rx_buf & 0x10) {
596                         /* we're not the last frame in the chain, continue */
597                         goto do_tx;
598                 }
599         }
600
601 out_rxb:
602         free(rx_buf);
603 out_txb:
604         free(tx_buf);
605 out:
606         return ret;
607 }
608
609 #if 0
610 int
611 tcl_send(struct tcl_handle *th)
612 {
613         return -1;
614 }
615
616 int
617 tcl_recv()
618 {
619         return -1;
620 }
621 #endif
622
623 static struct rfid_protocol_handle *
624 tcl_init(struct rfid_layer2_handle *l2h)
625 {
626         struct rfid_protocol_handle *th;
627         unsigned int mru = l2h->rh->ah->mru;
628
629         th = malloc(sizeof(struct rfid_protocol_handle) + mru);
630         if (!th)
631                 return NULL;
632
633         /* FIXME: mru should be attribute of layer2 (in case it adds/removes
634          * some overhead */
635         memset(th, 0, sizeof(struct rfid_protocol_handle) + mru);
636
637         /* maximum received ats length equals mru of asic/reader */
638         th->priv.tcl.state = TCL_STATE_INITIAL;
639         th->priv.tcl.ats_len = mru;
640         th->priv.tcl.toggle = 1;
641         th->l2h = l2h;
642         th->proto = &rfid_protocol_tcl;
643
644         th->priv.tcl.fsd = iso14443_fsd_approx(mru);
645
646         return th;
647 }
648
649 static int
650 tcl_fini(struct rfid_protocol_handle *ph)
651 {
652         free(ph);
653         return 0;
654 }
655
656 struct rfid_protocol rfid_protocol_tcl = {
657         .id     = RFID_PROTOCOL_TCL,
658         .name   = "ISO 14443-4 / T=CL",
659         .fn     = {
660                 .init = &tcl_init,
661                 .open = &tcl_connect,
662                 .transcieve = &tcl_transcieve,
663                 .close = &tcl_deselect,
664                 .fini = &tcl_fini,
665         },
666 };