]> git.cryptolib.org Git - labortage2013badge.git/blobdiff - firmware/main.c
some minor fixes
[labortage2013badge.git] / firmware / main.c
index 056a7628228f059bbc145d2b7c10f2aeed42046a..247fcedcc018921775c429881e827774a63136ae 100644 (file)
@@ -1,10 +1,10 @@
 /* Name: main.c
- * Project: hid-custom-rq example
- * Author: Christian Starkjohann
- * Creation Date: 2008-04-07
+ * Project: labortage-2013-badge
+ * Author: bg (bg@das-labor.org)
+ * Creation Date: 2013-10-16
  * Tabsize: 4
- * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
- * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH, (c) Daniel Otte
+ * License: GNU GPL v3
  * This Revision: $Id: main.c 692 2008-11-07 15:07:40Z cs $
  */
 
@@ -13,12 +13,13 @@ This example should run on most AVRs with only little changes. No special
 hardware resources except INT0 are used. You may have to change usbconfig.h for
 different I/O pins for USB. Please note that USB D+ must be the INT0 pin, or
 at least be connected to INT0 as well.
-We assume that an LED is connected to port B bit 0. If you connect it to a
-different port or bit, change the macros below:
 */
-#define BUTTON_PIN 4
 
+#define BUTTON_PIN 5
+#define DEBOUNCE_DELAY 50
 #define SIMPLE_COUNTER 1
+#define NO_CHECK 1
+#define ALLOW_SECRET_READ 0
 
 #include <stdint.h>
 #include <string.h>
@@ -32,10 +33,9 @@ different port or bit, change the macros below:
 
 #include <avr/pgmspace.h>   /* required by usbdrv.h */
 #include "usbdrv.h"
-#include "oddebug.h"        /* This is also an example for using debug macros */
 #include "requests.h"       /* The custom request numbers we use */
-#include "special_functions.h"
 #include "hotp.h"
+#include "special_functions.h"
 #if !SIMPLE_COUNTER
 #include "percnt2.h"
 #endif
@@ -50,39 +50,41 @@ different port or bit, change the macros below:
 #define STATE_RELEASE_KEY 2
 #define STATE_NEXT 3
 
+#define MIN(a, b) (((a) < (b)) ? (a) : (b))
+
 PROGMEM const char usbHidReportDescriptor[USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH] = {
-    0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
-    0x09, 0x06,                    // USAGE (Keyboard)
-    0xa1, 0x01,                    // COLLECTION (Application)
-    0x75, 0x01,                    //   REPORT_SIZE (1)
-    0x95, 0x08,                    //   REPORT_COUNT (8)
-    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)(Key Codes)
-    0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)(224)
-    0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)(231)
-    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
-    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
-    0x81, 0x02,                    //   INPUT (Data,Var,Abs) ; Modifier byte
-    0x95, 0x01,                    //   REPORT_COUNT (1)
-    0x75, 0x08,                    //   REPORT_SIZE (8)
-    0x81, 0x03,                    //   INPUT (Cnst,Var,Abs) ; Reserved byte
-    0x95, 0x05,                    //   REPORT_COUNT (5)
-    0x75, 0x01,                    //   REPORT_SIZE (1)
-    0x05, 0x08,                    //   USAGE_PAGE (LEDs)
-    0x19, 0x01,                    //   USAGE_MINIMUM (Num Lock)
-    0x29, 0x05,                    //   USAGE_MAXIMUM (Kana)
-    0x91, 0x02,                    //   OUTPUT (Data,Var,Abs) ; LED report
-    0x95, 0x01,                    //   REPORT_COUNT (1)
-    0x75, 0x03,                    //   REPORT_SIZE (3)
-    0x91, 0x03,                    //   OUTPUT (Cnst,Var,Abs) ; LED report padding
-    0x95, 0x06,                    //   REPORT_COUNT (6)
-    0x75, 0x08,                    //   REPORT_SIZE (8)
-    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
-    0x25, 0x65,                    //   LOGICAL_MAXIMUM (101)
-    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)(Key Codes)
-    0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))(0)
-    0x29, 0x65,                    //   USAGE_MAXIMUM (Keyboard Application)(101)
-    0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
-    0xc0                           // END_COLLECTION
+    0x05, 0x01,                    /* USAGE_PAGE (Generic Desktop) */
+    0x09, 0x06,                    /* USAGE (Keyboard) */
+    0xa1, 0x01,                    /* COLLECTION (Application) */
+    0x75, 0x01,                    /*   REPORT_SIZE (1) */
+    0x95, 0x08,                    /*   REPORT_COUNT (8) */
+    0x05, 0x07,                    /*   USAGE_PAGE (Keyboard)(Key Codes) */
+    0x19, 0xe0,                    /*   USAGE_MINIMUM (Keyboard LeftControl)(224) */
+    0x29, 0xe7,                    /*   USAGE_MAXIMUM (Keyboard Right GUI)(231) */
+    0x15, 0x00,                    /*   LOGICAL_MINIMUM (0) */
+    0x25, 0x01,                    /*   LOGICAL_MAXIMUM (1) */
+    0x81, 0x02,                    /*   INPUT (Data,Var,Abs) ; Modifier byte */
+    0x95, 0x01,                    /*   REPORT_COUNT (1) */
+    0x75, 0x08,                    /*   REPORT_SIZE (8) */
+    0x81, 0x03,                    /*   INPUT (Cnst,Var,Abs) ; Reserved byte */
+    0x95, 0x05,                    /*   REPORT_COUNT (5) */
+    0x75, 0x01,                    /*   REPORT_SIZE (1) */
+    0x05, 0x08,                    /*   USAGE_PAGE (LEDs) */
+    0x19, 0x01,                    /*   USAGE_MINIMUM (Num Lock) */
+    0x29, 0x05,                    /*   USAGE_MAXIMUM (Kana) */
+    0x91, 0x02,                    /*   OUTPUT (Data,Var,Abs) ; LED report */
+    0x95, 0x01,                    /*   REPORT_COUNT (1) */
+    0x75, 0x03,                    /*   REPORT_SIZE (3) */
+    0x91, 0x03,                    /*   OUTPUT (Cnst,Var,Abs) ; LED report padding */
+    0x95, 0x06,                    /*   REPORT_COUNT (6) */
+    0x75, 0x08,                    /*   REPORT_SIZE (8) */
+    0x15, 0x00,                    /*   LOGICAL_MINIMUM (0) */
+    0x25, 0x65,                    /*   LOGICAL_MAXIMUM (101) */
+    0x05, 0x07,                    /*   USAGE_PAGE (Keyboard)(Key Codes) */
+    0x19, 0x00,                    /*   USAGE_MINIMUM (Reserved (no event indicated))(0) */
+    0x29, 0x65,                    /*   USAGE_MAXIMUM (Keyboard Application)(101) */
+    0x81, 0x00,                    /*   INPUT (Data,Ary,Abs) */
+    0xc0                           /* END_COLLECTION */
 };
 
 static uint16_t secret_length_ee EEMEM = 0;
@@ -108,10 +110,9 @@ static union __attribute__((packed)) {
        void*    ptr[UNI_BUFFER_SIZE/sizeof(void*)];
 } uni_buffer;
 
-static uint8_t uni_buffer_fill;
 static uint8_t current_command;
 
-typedef struct {
+typedef struct __attribute__((packed)) {
     uint8_t modifier;
     uint8_t reserved;
     uint8_t keycode[6];
@@ -129,8 +130,6 @@ void memory_clean(void) {
     secret_length_b = 0;
 }
 
-#define NO_CHECK 1
-
 static
 uint8_t secret_set(void){
 #if !NO_CHECK
@@ -212,14 +211,23 @@ void counter_init(void) {
 
 static
 void token_generate(void) {
+    uint16_t s_length_b;
+    uint8_t digits;
     counter_inc();
     eeprom_busy_wait();
     eeprom_read_block(secret, secret_ee, 32);
     eeprom_busy_wait();
+    s_length_b = eeprom_read_word(&secret_length_ee);
+    if (s_length_b > 256) {
+        s_length_b = 256;
+    }
+    eeprom_busy_wait();
+    digits = eeprom_read_byte(&digits_ee);
 #if SIMPLE_COUNTER
-    hotp(token, secret, eeprom_read_word(&secret_length_ee), eeprom_read_dword(&counter_ee), eeprom_read_byte(&digits_ee));
+    eeprom_busy_wait();
+    hotp(token, secret, s_length_b, eeprom_read_dword(&counter_ee) - 1, digits);
 #else
-    hotp(token, secret, eeprom_read_word(&secret_length_ee), percnt_get(0), eeprom_read_byte(&digits_ee));
+    hotp(token, secret, s_length_b, percnt_get(0) - 1, digits);
 #endif
     memory_clean();
 }
@@ -228,15 +236,7 @@ void token_generate(void) {
 static
 void buildReport(uchar send_key) {
     keyboard_report.modifier = 0;
-
     switch (send_key) {
-    case 'A' ... 'Z':
-        keyboard_report.modifier = MOD_SHIFT_LEFT;
-        keyboard_report.keycode[0] = KEY_A + (send_key-'A');
-        break;
-    case 'a' ... 'z':
-        keyboard_report.keycode[0] = KEY_A + (send_key-'a');
-        break;
     case '1' ... '9':
         keyboard_report.keycode[0] = KEY_1 + (send_key-'1');
         break;
@@ -249,13 +249,13 @@ void buildReport(uchar send_key) {
 }
 
 static
-int8_t button_get_debounced(volatile uint8_t debounce_count) {
+int8_t button_get_debounced(volatile int8_t debounce_count) {
     uint8_t v;
     v = PINB & _BV(BUTTON_PIN);
-    while (debounce_count-- && v == (PINB & _BV(BUTTON_PIN))) {
+    while (debounce_count-- && (v == (PINB & _BV(BUTTON_PIN)))) {
         ;
     }
-    if (debounce_count) {
+    if (debounce_count != -1) {
         return -1;
     }
     return v ? 0 : 1;
@@ -266,28 +266,29 @@ usbMsgLen_t usbFunctionSetup(uchar data[8])
        usbRequest_t    *rq = (usbRequest_t *)data;
        if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS) {    /* class request type */
            switch(rq->bRequest) {
-        case USBRQ_HID_GET_REPORT: // send "no keys pressed" if asked here
-            // wValue: ReportType (highbyte), ReportID (lowbyte)
-            usbMsgPtr = (void *)&keyboard_report; // we only have this one
+        case USBRQ_HID_GET_REPORT: /* send "no keys pressed" if asked here */
+            /* wValue: ReportType (highbyte), ReportID (lowbyte) */
+            usbMsgPtr = (void *)&keyboard_report; /* we only have this one */
             keyboard_report.modifier = 0;
             keyboard_report.keycode[0] = 0;
             return sizeof(keyboard_report);
-        case USBRQ_HID_SET_REPORT: // if wLength == 1, should be LED state
+        case USBRQ_HID_SET_REPORT: /* if wLength == 1, should be LED state */
             if (rq->wLength.word == 1) {
                 current_command = LED_WRITE;
                 return USB_NO_MSG;
             }
             return 0;
-        case USBRQ_HID_GET_IDLE: // send idle rate to PC as required by spec
+        case USBRQ_HID_GET_IDLE: /* send idle rate to PC as required by spec */
             usbMsgPtr = &idleRate;
             return 1;
-        case USBRQ_HID_SET_IDLE: // save idle rate as required by spec
+        case USBRQ_HID_SET_IDLE: /* save idle rate as required by spec */
             idleRate = rq->wValue.bytes[1];
             return 0;
         }
     }
     if ((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_VENDOR) {
                current_command = rq->bRequest;
+        usbMsgPtr = uni_buffer.w8;
        switch(rq->bRequest)
                {
        case CUSTOM_RQ_SET_SECRET:
@@ -307,7 +308,6 @@ usbMsgLen_t usbFunctionSetup(uchar data[8])
 #else
            uni_buffer.w32[0] = percnt_get(0);
 #endif
-           usbMsgPtr = (usbMsgPtr_t)uni_buffer.w32;
            return 4;
        case CUSTOM_RQ_RESET_COUNTER:
            counter_reset();
@@ -315,9 +315,11 @@ usbMsgLen_t usbFunctionSetup(uchar data[8])
         case CUSTOM_RQ_GET_RESET_COUNTER:
            eeprom_busy_wait();
             uni_buffer.w8[0] = eeprom_read_byte(&reset_counter_ee);
-            usbMsgPtr = uni_buffer.w8;
             return 1;
        case CUSTOM_RQ_SET_DIGITS:
+            if (rq->wValue.bytes[0] < 6) {
+                rq->wValue.bytes[0] = 6;
+            }
            if (rq->wValue.bytes[0] > 9) {
                rq->wValue.bytes[0] = 9;
            }
@@ -327,13 +329,11 @@ usbMsgLen_t usbFunctionSetup(uchar data[8])
        case CUSTOM_RQ_GET_DIGITS:
            eeprom_busy_wait();
             uni_buffer.w8[0] = eeprom_read_byte(&digits_ee);
-            usbMsgPtr = uni_buffer.w8;
             return 1;
        case CUSTOM_RQ_GET_TOKEN:
            token_generate();
            usbMsgPtr = (usbMsgPtr_t)token;
            return strlen(token);
-
        case CUSTOM_RQ_PRESS_BUTTON:
            key_state = STATE_SEND_KEY;
            return 0;
@@ -342,35 +342,23 @@ usbMsgLen_t usbFunctionSetup(uchar data[8])
             return 0;
                case CUSTOM_RQ_SET_DBG:
                        return USB_NO_MSG;
-               case CUSTOM_RQ_GET_DBG:{
-                       usbMsgLen_t len = 8;
-                       if(len > rq->wLength.word){
-                               len = rq->wLength.word;
-                       }
+               case CUSTOM_RQ_GET_DBG:
                        usbMsgPtr = dbg_buffer;
-                       return len;
-               }
-               case CUSTOM_RQ_READ_MEM:
-                       usbMsgPtr = (uchar*)rq->wValue.word;
-                       return rq->wLength.word;
-               case CUSTOM_RQ_WRITE_MEM:
-               case CUSTOM_RQ_EXEC_SPM:
-/*                     uni_buffer_fill = 4;
-                       uni_buffer.w16[0] = rq->wValue.word;
-                       uni_buffer.w16[1] = rq->wLength.word;
-                       return USB_NO_MSG;
-*/             case CUSTOM_RQ_READ_FLASH:
-                       uni_buffer.w16[0] = rq->wValue.word;
-                       uni_buffer.w16[1] = rq->wLength.word;
-            uni_buffer_fill = 4;
-                       return USB_NO_MSG;
+                       return MIN(8, rq->wLength.word);
                case CUSTOM_RQ_RESET:
                        soft_reset((uint8_t)(rq->wValue.word));
                        break;
                case CUSTOM_RQ_READ_BUTTON:
-                       uni_buffer.w8[0] = button_get_debounced(25);
-                       usbMsgPtr = uni_buffer.w8;
+                       uni_buffer.w8[0] = button_get_debounced(DEBOUNCE_DELAY);
                        return 1;
+#if ALLOW_SECRET_READ
+               case CUSTOM_RQ_GET_SECRET:
+            uni_buffer.w8[0] = 0;
+                   return USB_NO_MSG;
+#else
+#endif
+        default:
+            return 0;
                }
     }
 
@@ -385,7 +373,7 @@ uchar usbFunctionWrite(uchar *data, uchar len)
        case LED_WRITE:
            if (data[0] != LED_state)
                LED_state = data[0];
-           return 1; // Data read, not expecting more
+           return 1; /* Data read, not expecting more */
        case CUSTOM_RQ_SET_SECRET:
         {
             if (uni_buffer.w8[0] < (secret_length_b + 7) / 8) {
@@ -403,48 +391,26 @@ uchar usbFunctionWrite(uchar *data, uchar len)
                        len = sizeof(dbg_buffer);
                }
                memcpy(dbg_buffer, data, len);
-               return 1;
-       case CUSTOM_RQ_WRITE_MEM:
-               memcpy(uni_buffer.ptr[0], data, len);
-               uni_buffer.w16[0] += len;
-               return !(uni_buffer.w16[1] -= len);
-       case CUSTOM_RQ_EXEC_SPM:
-               if(uni_buffer_fill < 8){
-                       uint8_t l = 8 - uni_buffer_fill;
-                       if(len<l){
-                               len = l;
-                       }
-                       memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
-                       uni_buffer_fill += len;
-                       return 0;
-               }
-               uni_buffer.w16[1] -= len;
-               if (uni_buffer.w16[1] > 8) {
-                       memcpy(uni_buffer.ptr[0], data, len);
-                       uni_buffer.w16[0] += len;
-                       return 0;
-               } else {
-                       memcpy(&(uni_buffer.w8[uni_buffer_fill]), data, len);
-                       exec_spm(uni_buffer.w16[2], uni_buffer.w16[3], uni_buffer.ptr[0], data, len);
-                       return 1;
-               }
-       default:
-               return 1;
        }
-       return 0;
+       return 1;
 }
+
 uchar usbFunctionRead(uchar *data, uchar len){
-       uchar ret = len;
-       switch(current_command){
-       case CUSTOM_RQ_READ_FLASH:
-               while(len--){
-                       *data++ = pgm_read_byte((uni_buffer.w16[0])++);
-               }
-               return ret;
-       default:
-               break;
-       }
-       return 0;
+#if ALLOW_SECRET_READ || 1
+    uchar r;
+    uint8_t s_length_B;
+    switch(current_command){
+    case CUSTOM_RQ_GET_SECRET:
+        eeprom_busy_wait();
+        s_length_B = (eeprom_read_word(&secret_length_ee) + 7) / 8;
+        r = MIN(len, s_length_B - uni_buffer.w8[0]);
+        eeprom_busy_wait();
+        eeprom_read_block(data, secret_ee + uni_buffer.w8[0], r);
+        uni_buffer.w8[0] += r;
+        return r;
+    }
+#endif
+    return 0;
 }
 
 static void calibrateOscillator(void)
@@ -456,15 +422,15 @@ int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e
     /* do a binary search: */
     do {
         OSCCAL = trialValue + step;
-        x = usbMeasureFrameLength();    // proportional to current real frequency
-        if(x < targetValue)             // frequency still too low
+        x = usbMeasureFrameLength();    /* proportional to current real frequency */
+        if(x < targetValue)             /* frequency still too low */
             trialValue += step;
         step >>= 1;
     } while(step > 0);
     /* We have a precision of +/- 1 for optimum OSCCAL here */
     /* now do a neighborhood search for optimum value */
     optimumValue = trialValue;
-    optimumDev = x; // this is certainly far away from optimum
+    optimumDev = x; /* this is certainly far away from optimum */
     for (OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){
         x = usbMeasureFrameLength() - targetValue;
         if (x < 0)
@@ -480,11 +446,9 @@ int         x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e
 
 void usbEventResetReady(void)
 {
-    cli();  // usbMeasureFrameLength() counts CPU cycles, so disable interrupts.
+    cli();  /* usbMeasureFrameLength() counts CPU cycles, so disable interrupts. */
     calibrateOscillator();
     sei();
-// we never read the value from eeprom so this causes only degradation of eeprom
-//    eeprom_write_byte(0, OSCCAL);   // store the calibrated value in EEPROM
 }
 
 /* ------------------------------------------------------------------------- */
@@ -503,8 +467,6 @@ int main(void)
      * additional hardware initialization.
      */
 
-    DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
-    PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
     counter_init();
     usbInit();
     usbDeviceDisconnect();  /* enforce re-enumeration, do this while interrupts are disabled! */
@@ -515,14 +477,17 @@ int main(void)
     usbDeviceConnect();
        
     sei();
+    DDRB &= ~_BV(BUTTON_PIN); /* make button pin input */
+    PORTB |= _BV(BUTTON_PIN); /* turn on pull-up resistor */
 
     for(;;){                /* main event loop */
         wdt_reset();
         usbPoll();
 
-        i = button_get_debounced(25);
+        i = button_get_debounced(DEBOUNCE_DELAY);
         if (i != -1) {
             if (last_stable_button_state == 0 && i == 1) {
+                token_generate();
                 key_state = STATE_SEND_KEY;
             }
             last_stable_button_state = i;
@@ -532,7 +497,7 @@ int main(void)
             switch(key_state) {
             case STATE_SEND_KEY:
                 buildReport(token[idx]);
-                key_state = STATE_RELEASE_KEY; // release next
+                key_state = STATE_RELEASE_KEY; /* release next */
                 break;
             case STATE_RELEASE_KEY:
                 buildReport(0);
@@ -545,9 +510,9 @@ int main(void)
                 }
                 break;
             default:
-                key_state = STATE_WAIT; // should not happen
+                key_state = STATE_WAIT; /* should not happen */
             }
-                        // start sending
+                        /* start sending */
             usbSetInterrupt((void *)&keyboard_report, sizeof(keyboard_report));
 
         }