]> git.cryptolib.org Git - labortage2013badge.git/blob - firmware/main.c
test commit
[labortage2013badge.git] / firmware / main.c
1 /* Name: main.c
2  * Project: labortage-2013-badge
3  * Author: bg (bg@das-labor.org)
4  * Creation Date: 2013-10-16
5  * Tabsize: 4
6  * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH, (c) Daniel Otte
7  * License: GNU GPL v3
8  * This Revision: $Id: main.c 692 2008-11-07 15:07:40Z cs $
9  */
10
11 /*
12 This example should run on most AVRs with only little changes. No special
13 hardware resources except INT0 are used. You may have to change usbconfig.h for
14 different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
15 at least be connected to INT0 as well.
16 */
17
18 #define BUTTON_PIN 5
19 #define DEBOUNCE_DELAY 50
20 #define SIMPLE_COUNTER 1
21 #define NO_CHECK 1
22 #define ALLOW_SECRET_READ 0
23
24 #include <stdint.h>
25 #include <string.h>
26 #include <stdbool.h>
27
28 #include <avr/io.h>
29 #include <avr/wdt.h>
30 #include <avr/eeprom.h>
31 #include <avr/interrupt.h>  /* for sei() */
32 #include <util/delay.h>     /* for _delay_ms() */
33
34 #include <avr/pgmspace.h>   /* required by usbdrv.h */
35 #include "usbdrv.h"
36 #include "requests.h"       /* The custom request numbers we use */
37 #include "hotp.h"
38 #include "special_functions.h"
39
40 #if !SIMPLE_COUNTER
41 #include "percnt2.h"
42 #endif
43
44 #include "usb_keyboard_codes.h"
45
46 /* ------------------------------------------------------------------------- */
47 /* ----------------------------- USB interface ----------------------------- */
48 /* ------------------------------------------------------------------------- */
49
50 #define STATE_WAIT 0
51 #define STATE_SEND_KEY 1
52 #define STATE_RELEASE_KEY 2
53 #define STATE_NEXT 3
54
55 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
56
57 PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {
58     0x05, 0x01,                    /* USAGE_PAGE (Generic Desktop) */
59     0x09, 0x06,                    /* USAGE (Keyboard) */
60     0xa1, 0x01,                    /* COLLECTION (Application) */
61     0x75, 0x01,                    /*   REPORT_SIZE (1) */
62     0x95, 0x08,                    /*   REPORT_COUNT (8) */
63     0x05, 0x07,                    /*   USAGE_PAGE (Keyboard)(Key Codes) */
64     0x19, 0xe0,                    /*   USAGE_MINIMUM (Keyboard LeftControl)(224) */
65     0x29, 0xe7,                    /*   USAGE_MAXIMUM (Keyboard Right GUI)(231) */
66     0x15, 0x00,                    /*   LOGICAL_MINIMUM (0) */
67     0x25, 0x01,                    /*   LOGICAL_MAXIMUM (1) */
68     0x81, 0x02,                    /*   INPUT (Data,Var,Abs) ; Modifier byte */
69     0x95, 0x01,                    /*   REPORT_COUNT (1) */
70     0x75, 0x08,                    /*   REPORT_SIZE (8) */
71     0x81, 0x03,                    /*   INPUT (Cnst,Var,Abs) ; Reserved byte */
72     0x95, 0x05,                    /*   REPORT_COUNT (5) */
73     0x75, 0x01,                    /*   REPORT_SIZE (1) */
74     0x05, 0x08,                    /*   USAGE_PAGE (LEDs) */
75     0x19, 0x01,                    /*   USAGE_MINIMUM (Num Lock) */
76     0x29, 0x05,                    /*   USAGE_MAXIMUM (Kana) */
77     0x91, 0x02,                    /*   OUTPUT (Data,Var,Abs) ; LED report */
78     0x95, 0x01,                    /*   REPORT_COUNT (1) */
79     0x75, 0x03,                    /*   REPORT_SIZE (3) */
80     0x91, 0x03,                    /*   OUTPUT (Cnst,Var,Abs) ; LED report padding */
81     0x95, 0x06,                    /*   REPORT_COUNT (6) */
82     0x75, 0x08,                    /*   REPORT_SIZE (8) */
83     0x15, 0x00,                    /*   LOGICAL_MINIMUM (0) */
84     0x25, 0x65,                    /*   LOGICAL_MAXIMUM (101) */
85     0x05, 0x07,                    /*   USAGE_PAGE (Keyboard)(Key Codes) */
86     0x19, 0x00,                    /*   USAGE_MINIMUM (Reserved (no event indicated))(0) */
87     0x29, 0x65,                    /*   USAGE_MAXIMUM (Keyboard Application)(101) */
88     0x81, 0x00,                    /*   INPUT (Data,Ary,Abs) */
89     0xc0                           /* END_COLLECTION */
90 };
91
92 static uint16_t secret_length_ee EEMEM = 0;
93 static uint8_t  secret_ee[32] EEMEM;
94 static uint8_t  reset_counter_ee EEMEM = 0;
95 static uint8_t  digits_ee EEMEM = 8;
96
97 #if SIMPLE_COUNTER
98 static uint32_t counter_ee EEMEM = 0;
99 #endif
100
101 static uint8_t dbg_buffer[8];
102 static uint8_t secret[32];
103 static uint16_t secret_length_b;
104 static char token[10];
105
106 #define UNI_BUFFER_SIZE 16
107
108 static union __attribute__((packed)) {
109         uint8_t  w8[UNI_BUFFER_SIZE];
110         uint16_t w16[UNI_BUFFER_SIZE/2];
111         uint32_t w32[UNI_BUFFER_SIZE/4];
112         void*    ptr[UNI_BUFFER_SIZE/sizeof(void*)];
113 } uni_buffer;
114
115 static uint8_t current_command;
116
117 typedef struct __attribute__((packed)) {
118     uint8_t modifier;
119     uint8_t reserved;
120     uint8_t keycode[6];
121 } keyboard_report_t;
122
123 static keyboard_report_t keyboard_report; /* report sent to the host */
124 static uchar idleRate;  /* in 4 ms units */
125 static uchar key_state = STATE_WAIT;
126 volatile static uchar LED_state = 0xff;
127 /* ------------------------------------------------------------------------- */
128
129 static
130 void memory_clean(void) {
131     memset(secret, 0, 32);
132     secret_length_b = 0;
133 }
134
135 static
136 uint8_t secret_set(void){
137 #if !NO_CHECK
138     uint8_t r;
139     union {
140         uint8_t w8[32];
141         uint16_t w16[16];
142     } read_back;
143 #endif
144     const uint8_t length_B = (secret_length_b + 7) / 8;
145
146     eeprom_busy_wait();
147     eeprom_write_block(secret, secret_ee, length_B);
148 #if !NO_CHECK
149     eeprom_busy_wait();
150     eeprom_read_block(read_back.w8, secret_ee, length_B);
151     r = memcmp(secret, read_back.w8, length_B);
152     memory_clean();
153     memset(read_back.w8, 0, 32);
154     if (r) {
155         return 1;
156     }
157 #endif
158     eeprom_busy_wait();
159     eeprom_write_word(&secret_length_ee, secret_length_b);
160 #if !NO_CHECK
161     eeprom_busy_wait();
162     r = eeprom_read_word(&secret_length_ee) == secret_length_b;
163     memory_clean();
164     *read_back.w16 = 0;
165     if (!r) {
166         return 1;
167     }
168 #else
169     memory_clean();
170 #endif
171
172     return 0;
173 }
174
175 static
176 void counter_inc(void){
177 #if SIMPLE_COUNTER
178     uint32_t t;
179     eeprom_busy_wait();
180     t = eeprom_read_dword(&counter_ee);
181     eeprom_busy_wait();
182     eeprom_write_dword(&counter_ee, t + 1);
183 #else
184     percnt_inc(0);
185 #endif
186 }
187
188 static
189 void counter_reset(void) {
190     uint8_t reset_counter;
191     eeprom_busy_wait();
192     reset_counter = eeprom_read_byte(&reset_counter_ee);
193 #if SIMPLE_COUNTER
194     eeprom_busy_wait();
195     eeprom_write_dword(&counter_ee, 0);
196 #else
197     percnt_reset(0);
198 #endif
199     eeprom_busy_wait();
200     eeprom_write_byte(&reset_counter_ee, reset_counter + 1);
201 }
202
203 static
204 void counter_init(void) {
205 #if !SIMPLE_COUNTER
206     eeprom_busy_wait();
207     if (eeprom_read_byte(&reset_counter_ee) == 0) {
208         counter_reset();
209     }
210     percnt_init(0);
211 #endif
212 }
213
214 static
215 void token_generate(void) {
216     uint16_t s_length_b;
217     uint8_t digits;
218     counter_inc();
219     eeprom_busy_wait();
220     eeprom_read_block(secret, secret_ee, 32);
221     eeprom_busy_wait();
222     s_length_b = eeprom_read_word(&secret_length_ee);
223     if (s_length_b > 256) {
224         s_length_b = 256;
225     }
226     eeprom_busy_wait();
227     digits = eeprom_read_byte(&digits_ee);
228 #if SIMPLE_COUNTER
229     eeprom_busy_wait();
230     hotp(token, secret, s_length_b, eeprom_read_dword(&counter_ee) - 1, digits);
231 #else
232     hotp(token, secret, s_length_b, percnt_get(0) - 1, digits);
233 #endif
234     memory_clean();
235 }
236
237
238 static
239 void buildReport(uchar send_key) {
240     keyboard_report.modifier = 0;
241     switch (send_key) {
242     case '1' ... '9':
243         keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
244         break;
245     case '0':
246         keyboard_report.keycode[0] = KEY_0;
247         break;
248     default:
249         keyboard_report.keycode[0] = 0;
250     }
251 }
252
253 static
254 int8_t button_get_debounced(volatile int8_t debounce_count) {
255     uint8_t v;
256     v = PINB & _BV(BUTTON_PIN);
257     while (debounce_count-- && (v == (PINB & _BV(BUTTON_PIN)))) {
258         ;
259     }
260     if (debounce_count != -1) {
261         return -1;
262     }
263     return v ? 0 : 1;
264 }
265
266 usbMsgLen_t usbFunctionSetup(uchar data[8])
267 {
268         usbRequest_t    *rq = (usbRequest_t *)data;
269         if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
270             switch(rq->bRequest) {
271         case USBRQ_HID_GET_REPORT: /* send "no keys pressed" if asked here */
272             /* wValue: ReportType (highbyte), ReportID (lowbyte) */
273             usbMsgPtr = (void *)&keyboard_report; /* we only have this one */
274             keyboard_report.modifier = 0;
275             keyboard_report.keycode[0] = 0;
276             return sizeof(keyboard_report);
277         case USBRQ_HID_SET_REPORT: /* if wLength == 1, should be LED state */
278             if (rq->wLength.word == 1) {
279                 current_command = LED_WRITE;
280                 return USB_NO_MSG;
281             }
282             return 0;
283         case USBRQ_HID_GET_IDLE: /* send idle rate to PC as required by spec */
284             usbMsgPtr = &idleRate;
285             return 1;
286         case USBRQ_HID_SET_IDLE: /* save idle rate as required by spec */
287             idleRate = rq->wValue.bytes[1];
288             return 0;
289         }
290     }
291     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
292                 current_command = rq->bRequest;
293         usbMsgPtr = uni_buffer.w8;
294         switch(rq->bRequest)
295                 {
296         case CUSTOM_RQ_SET_SECRET:
297             secret_length_b = rq->wValue.word;
298             if (secret_length_b > 256) {
299                 secret_length_b = 256;
300             }
301             uni_buffer.w8[0] = 0;
302             return USB_NO_MSG;
303         case CUSTOM_RQ_INC_COUNTER:
304             counter_inc();
305             return 0;
306         case CUSTOM_RQ_GET_COUNTER:
307 #if SIMPLE_COUNTER
308             eeprom_busy_wait();
309             uni_buffer.w32[0] = eeprom_read_dword(&counter_ee);
310 #else
311             uni_buffer.w32[0] = percnt_get(0);
312 #endif
313             return 4;
314         case CUSTOM_RQ_RESET_COUNTER:
315             counter_reset();
316             return 0;
317         case CUSTOM_RQ_GET_RESET_COUNTER:
318             eeprom_busy_wait();
319             uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
320             return 1;
321         case CUSTOM_RQ_SET_DIGITS:
322             if (rq->wValue.bytes[0] < 6) {
323                 rq->wValue.bytes[0] = 6;
324             }
325             if (rq->wValue.bytes[0] > 9) {
326                 rq->wValue.bytes[0] = 9;
327             }
328             eeprom_busy_wait();
329             eeprom_write_byte(&digits_ee, rq->wValue.bytes[0]);
330             return 0;
331         case CUSTOM_RQ_GET_DIGITS:
332             eeprom_busy_wait();
333             uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
334             return 1;
335         case CUSTOM_RQ_GET_TOKEN:
336             token_generate();
337             usbMsgPtr = (usbMsgPtr_t)token;
338             return strlen(token);
339         case CUSTOM_RQ_PRESS_BUTTON:
340             key_state = STATE_SEND_KEY;
341             return 0;
342         case CUSTOM_RQ_CLR_DBG:
343             memset(dbg_buffer, 0, sizeof(dbg_buffer));
344             return 0;
345                 case CUSTOM_RQ_SET_DBG:
346                         return USB_NO_MSG;
347                 case CUSTOM_RQ_GET_DBG:
348                         usbMsgPtr = dbg_buffer;
349                         return MIN(8, rq->wLength.word);
350                 case CUSTOM_RQ_RESET:
351                         soft_reset((uint8_t)(rq->wValue.word));
352                         break;
353                 case CUSTOM_RQ_READ_BUTTON:
354                         uni_buffer.w8[0] = button_get_debounced(DEBOUNCE_DELAY);
355                         return 1;
356 #if ALLOW_SECRET_READ
357                 case CUSTOM_RQ_GET_SECRET:
358             uni_buffer.w8[0] = 0;
359                     return USB_NO_MSG;
360 #else
361 #endif
362         default:
363             return 0;
364                 }
365     }
366
367     return 0;   /* default for not implemented requests: return no data back to host */
368 }
369
370
371 uchar usbFunctionWrite(uchar *data, uchar len)
372 {
373         switch(current_command){
374
375         case LED_WRITE:
376             if (data[0] != LED_state)
377                 LED_state = data[0];
378             return 1; /* Data read, not expecting more */
379         case CUSTOM_RQ_SET_SECRET:
380         {
381             if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
382                 memcpy(&secret[uni_buffer.w8[0]], data, len);
383                 uni_buffer.w8[0] += len;
384             }
385             if (uni_buffer.w8[0] >= (secret_length_b + 7) / 8) {
386                 secret_set();
387                 return 1;
388             }
389             return 0;
390         }
391         case CUSTOM_RQ_SET_DBG:
392                 if(len > sizeof(dbg_buffer)){
393                         len = sizeof(dbg_buffer);
394                 }
395                 memcpy(dbg_buffer, data, len);
396         }
397         return 1;
398 }
399
400 uchar usbFunctionRead(uchar *data, uchar len){
401 #if ALLOW_SECRET_READ || 1
402     uchar r;
403     uint8_t s_length_B;
404     switch(current_command){
405     case CUSTOM_RQ_GET_SECRET:
406         eeprom_busy_wait();
407         s_length_B = (eeprom_read_word(&secret_length_ee) + 7) / 8;
408         r = MIN(len, s_length_B - uni_buffer.w8[0]);
409         eeprom_busy_wait();
410         eeprom_read_block(data, secret_ee + uni_buffer.w8[0], r);
411         uni_buffer.w8[0] += r;
412         return r;
413     }
414 #endif
415     return 0;
416 }
417
418 static void calibrateOscillator(void)
419 {
420 uchar       step = 128;
421 uchar       trialValue = 0, optimumValue;
422 int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5);
423  
424     /* do a binary search: */
425     do {
426         OSCCAL = trialValue + step;
427         x = usbMeasureFrameLength();    /* proportional to current real frequency */
428         if(x < targetValue)             /* frequency still too low */
429             trialValue += step;
430         step >>= 1;
431     } while(step > 0);
432     /* We have a precision of +/- 1 for optimum OSCCAL here */
433     /* now do a neighborhood search for optimum value */
434     optimumValue = trialValue;
435     optimumDev = x; /* this is certainly far away from optimum */
436     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
437         x = usbMeasureFrameLength() - targetValue;
438         if (x < 0)
439             x = -x;
440         if (x < optimumDev) {
441             optimumDev = x;
442             optimumValue = OSCCAL;
443         }
444     }
445     OSCCAL = optimumValue;
446 }
447  
448
449 void usbEventResetReady(void)
450 {
451     cli();  /* usbMeasureFrameLength() counts CPU cycles, so disable interrupts. */
452     calibrateOscillator();
453     sei();
454 }
455
456 /* ------------------------------------------------------------------------- */
457
458 int main(void)
459 {
460         size_t idx = 0;
461         int8_t i = 0, last_stable_button_state = 0;
462
463     wdt_enable(WDTO_1S);
464     /* Even if you don't use the watchdog, turn it off here. On newer devices,
465      * the status of the watchdog (on/off, period) is PRESERVED OVER RESET!
466      */
467     /* RESET status: all port bits are inputs without pull-up.
468      * That's the way we need D+ and D-. Therefore we don't need any
469      * additional hardware initialization.
470      */
471
472     counter_init();
473     usbInit();
474     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
475     while(--i){             /* fake USB disconnect for ~512 ms */
476         wdt_reset();
477         _delay_ms(2);
478     }
479     usbDeviceConnect();
480         
481     sei();
482     DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
483     PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
484
485     for(;;){                /* main event loop */
486         wdt_reset();
487         usbPoll();
488
489         i = button_get_debounced(DEBOUNCE_DELAY);
490         if (i != -1) {
491             if (last_stable_button_state == 0 && i == 1) {
492                 token_generate();
493                 key_state = STATE_SEND_KEY;
494             }
495             last_stable_button_state = i;
496         }
497
498         if(usbInterruptIsReady() && key_state != STATE_WAIT){
499             switch(key_state) {
500             case STATE_SEND_KEY:
501                 buildReport(token[idx]);
502                 key_state = STATE_RELEASE_KEY; /* release next */
503                 break;
504             case STATE_RELEASE_KEY:
505                 buildReport(0);
506                 ++idx;
507                 if (token[idx] == '\0') {
508                     idx = 0;
509                     key_state = STATE_WAIT;
510                 } else {
511                     key_state = STATE_SEND_KEY;
512                 }
513                 break;
514             default:
515                 key_state = STATE_WAIT; /* should not happen */
516             }
517                         /* start sending */
518             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
519
520         }
521
522     }
523     return 0;
524 }
525
526 /* ------------------------------------------------------------------------- */