- move some initialization of proto handle from _tcl to core
[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 #if 0
219         int ret;
220         unsigned char ppss[3];
221         unsigned char pps_response[1];
222         unsigned int rx_len = 1;
223         unsigned char Dr, Ds, DrI, DsI;
224
225         if (h->priv.tcl.state != TCL_STATE_ATS_RCVD)
226                 return -1;
227
228         Dr = h->priv.tcl.ta & 0x07;
229         Ds = h->priv.tcl.ta & 0x70 >> 4;
230
231         if (Dr != Ds && !(h->priv.tcl.ta & 0x80)) {
232                 /* device supports different divisors for rx and tx, but not ?!? */
233                 DEBUGP("PICC has contradictory TA, aborting PPS\n");
234                 return -1;
235         };
236
237         /* ISO 14443-4:2000(E) Section 5.3. */
238
239         ppss[0] = 0xd0 & (h->priv.tcl.cid & 0x0f);
240         ppss[1] = 0x11;
241
242         /* FIXME: deal with different speed for each direction */
243         DrI = d_to_di(h, Dr);
244         DsI = d_to_di(h, Ds);
245
246         ppss[2] = (ppss[2] & 0xf0) | (DrI | DsI << 2);
247
248         ret = h->l2h->l2->fn.transcieve(h->l2h, ppss, 3, pps_response,
249                                         &rx_len, h->priv.tcl.fwt,
250                                         TCL_TRANSP_F_TX_CRC);
251         if (ret < 0)
252                 return ret;
253
254         if (pps_response[0] != ppss[0]) {
255                 DEBUGP("PPS Response != PPSS\n");
256                 return -1;
257         }
258         
259         h->priv.tcl.state = TCL_STATE_ESTABLISHED;
260 #endif
261         return 0;
262 }
263
264
265 static int
266 tcl_build_prologue2(struct tcl_handle *th, 
267                     unsigned char *prlg, unsigned int *prlg_len, 
268                     unsigned char pcb)
269 {
270         *prlg_len = 1;
271
272         *prlg = pcb;
273
274         if (th->toggle) {
275                 /* we've sent a toggle bit last time */
276                 th->toggle = 0;
277         } else {
278                 /* we've not sent a toggle last time: send one */
279                 th->toggle = 1;
280                 *prlg |= 0x01;
281         }
282
283         if (th->flags & TCL_HANDLE_F_CID_USED) {
284                 /* ISO 14443-4:2000(E) Section 7.1.1.2 */
285                 *prlg |= TCL_PCB_CID_FOLLOWING;
286                 (*prlg_len)++;
287                 prlg[*prlg_len] = th->cid & 0x0f;
288         }
289
290         /* nad only for I-block (0xc0 == 00) */
291         if ((th->flags & TCL_HANDLE_F_NAD_USED) &&
292             ((pcb & 0xc0) == 0x00)) {
293                 /* ISO 14443-4:2000(E) Section 7.1.1.3 */
294                 /* FIXME: in case of chaining only for first frame */
295                 *prlg |= TCL_PCB_NAD_FOLLOWING;
296                 prlg[*prlg_len] = th->nad;
297                 (*prlg_len)++;
298         }
299
300         return 0;
301 }
302
303 static int
304 tcl_build_prologue_i(struct tcl_handle *th,
305                      unsigned char *prlg, unsigned int *prlg_len)
306 {
307         /* ISO 14443-4:2000(E) Section 7.1.1.1 */
308         return tcl_build_prologue2(th, prlg, prlg_len, 0x02);
309 }
310
311 static int
312 tcl_build_prologue_r(struct tcl_handle *th,
313                      unsigned char *prlg, unsigned int *prlg_len,
314                      unsigned int nak)
315 {
316         unsigned char pcb = 0xa2;
317         /* ISO 14443-4:2000(E) Section 7.1.1.1 */
318
319         if (nak)
320                 pcb |= 0x10;
321
322         return tcl_build_prologue2(th, prlg, prlg_len, pcb);
323 }
324
325 static int
326 tcl_build_prologue_s(struct tcl_handle *th,
327                      unsigned char *prlg, unsigned int *prlg_len)
328 {
329         /* ISO 14443-4:2000(E) Section 7.1.1.1 */
330
331         /* the only S-block from PCD->PICC is DESELECT,
332          * well, actually there is the S(WTX) response. */
333         return tcl_build_prologue2(th, prlg, prlg_len, 0xc2);
334 }
335
336 /* FIXME: WTXM implementation */
337
338 static int tcl_prlg_len(struct tcl_handle *th)
339 {
340         int prlg_len = 1;
341
342         if (th->flags & TCL_HANDLE_F_CID_USED)
343                 prlg_len++;
344
345         if (th->flags & TCL_HANDLE_F_NAD_USED)
346                 prlg_len++;
347
348         return prlg_len;
349 }
350
351 #define max_net_tx_framesize(x) (x->fsc - tcl_prlg_len(x))
352
353 static int
354 tcl_connect(struct rfid_protocol_handle *h)
355 {
356         int ret; 
357
358         if (h->priv.tcl.state != TCL_STATE_DESELECTED &&
359             h->priv.tcl.state != TCL_STATE_INITIAL)
360                 return -1;
361
362         switch (h->l2h->l2->id) {
363         case RFID_LAYER2_ISO14443A:
364                 /* Start Type A T=CL Activation Sequence */
365                 ret = tcl_request_ats(h);
366                 if (ret < 0)
367                         return ret;
368
369                 /* Only do PPS if any non-default divisors supported */
370                 if (h->priv.tcl.ta & 0x77) {
371                         ret = tcl_do_pps(h);
372                         if (ret < 0)
373                                 return ret;
374                 }
375                 break;
376         case RFID_LAYER2_ISO14443B:
377                 /* initialized T=CL state from Type B Activation Data */
378                 h->priv.tcl.cid = h->l2h->priv.iso14443b.cid;
379                 h->priv.tcl.fsc = h->l2h->priv.iso14443b.fsc;
380                 h->priv.tcl.fsd = h->l2h->priv.iso14443b.fsd;
381                 h->priv.tcl.fwt = h->l2h->priv.iso14443b.fwt;
382
383                 /* what about ta? sfgt? */
384
385                 if (h->l2h->priv.iso14443b.flags & ISO14443B_CID_SUPPORTED)
386                         h->priv.tcl.flags |= TCL_HANDLE_F_CID_SUPPORTED;
387                 if (h->l2h->priv.iso14443b.flags & ISO14443B_NAD_SUPPORTED)
388                         h->priv.tcl.flags |= TCL_HANDLE_F_NAD_SUPPORTED;
389
390                 switch (h->l2h->priv.iso14443b.state) {
391                         case ISO14443B_STATE_SELECTED:
392                                 h->priv.tcl.state = TCL_STATE_ATS_RCVD;
393                                 break;
394                         case ISO14443B_STATE_ATTRIB_SENT:
395                                 h->priv.tcl.state = TCL_STATE_RATS_SENT;
396                                 break;
397                 }
398
399                 /* PUPI will be presented as ATS/historical bytes */
400                 memcpy(h->priv.tcl.ats, h->l2h->priv.iso14443b.pupi, 4);
401                 h->priv.tcl.ats_len = 4;
402                 h->priv.tcl.historical_bytes = h->priv.tcl.ats;
403
404                 break;
405         default:
406                 DEBUGP("unsupported l2: %u\n", h->l2h->l2->id);
407                 return -1;
408                 break;
409         }
410
411         return 0;
412 }
413
414 static int
415 tcl_deselect(struct rfid_protocol_handle *h)
416 {
417         /* ISO 14443-4:2000(E) Section 8 */
418         int ret;
419         unsigned char frame[3];         /* 3 bytes prologue, no information */
420         unsigned char rx[3];
421         unsigned int rx_len = sizeof(rx);
422         unsigned int prlg_len;
423         struct tcl_handle *th = &h->priv.tcl;
424
425         if (th->state != TCL_STATE_ESTABLISHED) {
426                 /* FIXME: not sure whether deselect is possible here,
427                  * probably better send a HLTA? */
428         }
429
430         /* build DESELECT S-block */
431         ret = tcl_build_prologue_s(th, frame, &prlg_len);
432         if (ret < 0)
433                 return ret;
434
435         ret = h->l2h->l2->fn.transcieve(h->l2h, frame, prlg_len, rx,
436                                      &rx_len, deactivation_fwt(h),
437                                      TCL_TRANSP_F_TX_CRC);
438         if (ret < 0) {
439                 /* FIXME: retransmit, HLT(A|B) */
440                 return ret;
441         }
442
443         th->state = TCL_STATE_DESELECTED;
444
445         return 0;
446 }
447
448 #define is_s_block(x) ((x & 0xc0) == 0xc0)
449 #define is_r_block(x) ((x & 0xc0) == 0x80)
450 #define is_i_block(x) ((x & 0xc0) == 0x00)
451
452 static int
453 tcl_transcieve(struct rfid_protocol_handle *h,
454                 const unsigned char *tx_data, unsigned int tx_len,
455                 unsigned char *rx_data, unsigned int *rx_len,
456                 unsigned int timeout, unsigned int flags)
457 {
458         int ret;
459         unsigned char *tx_buf, *rx_buf;
460         unsigned int prlg_len;
461         struct tcl_handle *th = &h->priv.tcl;
462
463         unsigned char *_tx;
464         unsigned int _tx_len, _timeout;
465         unsigned char wtx_resp[3];
466         unsigned char ack[10];
467         unsigned int ack_len;
468
469         if (tx_len > max_net_tx_framesize(th)) {
470                 /* slow path: we need to use chaining */
471                 return -1;
472         }
473
474         tx_buf = malloc(tcl_prlg_len(th) + tx_len);
475         if (!tx_buf) {
476                 ret = -ENOMEM;
477                 goto out;
478         }
479         rx_buf = malloc(tcl_prlg_len(th) + *rx_len);
480         if (!rx_buf) {
481                 ret = -ENOMEM;
482                 goto out_txb;
483         }
484
485         if (tcl_build_prologue_i(th, tx_buf, &prlg_len) < 0) {
486                 ret = -1;
487                 goto out_rxb;
488         }
489         memcpy(tx_buf + prlg_len, tx_data, tx_len);
490
491         /* intialize to data-to-be-transferred */
492         _tx = tx_buf;
493         _tx_len = tx_len+prlg_len;
494         _timeout = th->fwt;
495
496 do_tx:
497         ret = h->l2h->l2->fn.transcieve(h->l2h, _tx, _tx_len,
498                                         rx_buf, rx_len, _timeout, 0);
499         DEBUGP("l2 transcieve finished\n");
500         if (ret < 0)
501                 goto out_rxb;
502
503         if ((*rx_buf & 0x01) != h->priv.tcl.toggle) {
504                 DEBUGP("response with wrong toggle bit\n");
505                 goto out_rxb;
506         }
507
508         if (is_r_block(*rx_buf)) {
509                 unsigned int txed = _tx - tx_buf;
510                 DEBUGP("R-Block\n");
511                 /* Handle ACK frame in case of chaining */
512                 if (*rx_buf & TCL_PCB_CID_FOLLOWING) {
513                         if (*(rx_buf+1) != h->priv.tcl.cid) {
514                                 DEBUGP("CID %u is not valid\n", *(rx_buf)+1);
515                                 goto out_rxb;
516                         }
517                 }
518                 /* set up parameters for next frame in chain */
519                 if (txed < tx_len) {
520                         /* move tx pointer by the amount of bytes transferred
521                          * in last frame */
522                         _tx += _tx_len;
523                         _tx_len = (tx_len - txed);
524                         if (_tx_len > max_net_tx_framesize(th)) {
525                                 /* not last frame in chain */
526                                 _tx_len = max_net_tx_framesize(th);
527                         } else {
528                                 /* last frame in chain */
529                         }
530                         goto do_tx;
531                 } else {
532                         DEBUGP("Received ACK in response to last frame in "
533                                "chain?!? Expected I-frame.\n");
534                         ret = -1;
535                         goto out_rxb;
536                 }
537         } else if (is_s_block(*rx_buf)) {
538                 unsigned char inf;
539                 unsigned int prlg_len;
540
541                 DEBUGP("S-Block\n");
542                 /* Handle Wait Time Extension */
543                 if (*rx_buf & TCL_PCB_CID_FOLLOWING) {
544                         if (*rx_len < 3) {
545                                 DEBUGP("S-Block with CID but short len\n");
546                                 ret = -1;
547                                 goto out_rxb;
548                         }
549                         if (*(rx_buf+1) != h->priv.tcl.cid) {
550                                 DEBUGP("CID %u is not valid\n", *(rx_buf)+1);
551                                 goto out_rxb;
552                         }
553                         inf = *(rx_buf+2);
554                 } else
555                         inf = *(rx_buf+1);
556
557                 if ((*rx_buf & 0x30) != 0x30) {
558                         DEBUGP("S-Block but not WTX?\n");
559                         ret = -1;
560                         goto out_rxb;
561                 }
562                 inf &= 0x3f;    /* only lower 6 bits code WTXM */
563                 if (inf == 0 || (inf >= 60 && inf <= 63)) {
564                         DEBUGP("WTXM %u is RFU!\n", inf);
565                         ret = -1;
566                         goto out_rxb;
567                 }
568                 
569                 /* Acknowledge WTXM */
570                 tcl_build_prologue_s(&h->priv.tcl, wtx_resp, &prlg_len);
571                 /* set two bits that make this block a wtx */
572                 wtx_resp[0] |= 0x30;
573                 wtx_resp[prlg_len] = inf;
574                 _tx = wtx_resp;
575                 _tx_len = prlg_len+1;
576                 _timeout = th->fwt * inf;
577
578                 /* start over with next transcieve */
579                 goto do_tx; /* FIXME: do transcieve locally since we use
580                                 totally different buffer */
581
582         } else if (is_i_block(*rx_buf)) {
583                 unsigned char *inf = rx_buf+1;
584                 /* we're actually receiving payload data */
585
586                 DEBUGP("I-Block\n");
587                 if (*rx_buf & TCL_PCB_CID_FOLLOWING) {
588                         if (*(rx_buf+1) != h->priv.tcl.cid) {
589                                 DEBUGP("CID %u is not valid\n", *(rx_buf)+1);
590                                 goto out_rxb;
591                         }
592                         inf++;
593                 }
594                 if (*rx_buf & TCL_PCB_NAD_FOLLOWING) {
595                         inf++;
596                 }
597                 memcpy(rx_data, inf, *rx_len - (inf - rx_buf));
598
599                 if (*rx_buf & 0x10) {
600                         /* we're not the last frame in the chain, continue rx */
601                         DEBUGP("we're not the last frame in the chain, continue\n");
602                         ack_len = sizeof(ack);
603                         tcl_build_prologue_r(&h->priv.tcl, ack, &ack_len, 0);
604                         _tx = ack;
605                         _tx_len = ack_len;
606                         goto do_tx;
607                 }
608         }
609
610 out_rxb:
611         free(rx_buf);
612 out_txb:
613         free(tx_buf);
614 out:
615         return ret;
616 }
617
618 #if 0
619 int
620 tcl_send(struct tcl_handle *th)
621 {
622         return -1;
623 }
624
625 int
626 tcl_recv()
627 {
628         return -1;
629 }
630 #endif
631
632 static struct rfid_protocol_handle *
633 tcl_init(struct rfid_layer2_handle *l2h)
634 {
635         struct rfid_protocol_handle *th;
636         unsigned int mru = l2h->rh->ah->mru;
637
638         th = malloc(sizeof(struct rfid_protocol_handle) + mru);
639         if (!th)
640                 return NULL;
641
642         /* FIXME: mru should be attribute of layer2 (in case it adds/removes
643          * some overhead */
644         memset(th, 0, sizeof(struct rfid_protocol_handle) + mru);
645
646         /* maximum received ats length equals mru of asic/reader */
647         th->priv.tcl.state = TCL_STATE_INITIAL;
648         th->priv.tcl.ats_len = mru;
649         th->priv.tcl.toggle = 1;
650
651         th->priv.tcl.fsd = iso14443_fsd_approx(mru);
652
653         return th;
654 }
655
656 static int
657 tcl_fini(struct rfid_protocol_handle *ph)
658 {
659         free(ph);
660         return 0;
661 }
662
663 struct rfid_protocol rfid_protocol_tcl = {
664         .id     = RFID_PROTOCOL_TCL,
665         .name   = "ISO 14443-4 / T=CL",
666         .fn     = {
667                 .init = &tcl_init,
668                 .open = &tcl_connect,
669                 .transcieve = &tcl_transcieve,
670                 .close = &tcl_deselect,
671                 .fini = &tcl_fini,
672         },
673 };