switched to autotools

git-svn-id: https://vsmartcard.svn.sourceforge.net/svnroot/vsmartcard@102 96b47cad-a561-4643-ad3b-153ac7d7599c
This commit is contained in:
frankmorgner
2010-05-08 19:09:45 +00:00
parent 5ec26dd0be
commit 53cf8b684c
8 changed files with 75 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
bin_PROGRAMS = picc_to_pcsc
bin_SCRIPTS = picc.py
picc_to_pcsc_SOURCES = picc_to_pcsc.c
picc_to_pcsc_LDADD = $(PCSC_LIBS)
picc_to_pcsc_CFLAGS = $(PCSC_CFLAGS)

153
picc_to_pcsc/src/picc.py Normal file
View File

@@ -0,0 +1,153 @@
#!/usr/bin/python
"""
* Copyright (C) 2009 Dominik Oepen
*
* This file is part of picc.
*
* picc is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* picc is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* picc. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import smartcard.util
from optparse import OptionParser
from smartcard.System import readers
from struct import pack
def setup(readernumber):
"""Open up a connection to the specified reader via PCSC
"""
r = readers()
connection = r[readernumber].createConnection()
connection.connect()
return connection
def read_from_picc(fd):
"""Read a line from the terminal, parse it and return a string
representation
"""
line = fd.readline()
#Parse line
if (line[0] != '0'):
print(line)
return None
else:
idx = line.find(':')
if (idx == -1):
print "Failed to parse string"
return None
length = int(line[:idx])
apdu = line[idx+2:]
apdu = apdu.replace(' ','')
#if (len(apdu) != length*2+1):
# print "Encountered corrupted APDU"
# return None
return apdu
def transmit_to_pcsc(line, connection):
"""Write a line (including the string representation of an APDU)
to PCSC. Return the response from PCSC or NULL in case of error
"""
#Convert string to tuple of Bytes
try:
apdu_bytes = smartcard.util.toBytes(line)
except TypeError, e:
print "Failed to transmit APDU to PCSC: " + e
return #FIXME
rapdu = connection.transmit( SELECT + DF_TELECOM )
#print "%x %x" % (sw1, sw2)
rv = smartcard.util.toHexString(rapdu, PACK)
return rv
def write_to_picc(line,fd):
"""Read a line and format it for the OpenPICC. Then write it
to the terminal
"""
#fd.write("0002: 90 00\r\n")
length = len(line)
length /= 2
output_string = hex(length)[2:]
output_string += ":"
for (i in range[0, len(line), 2])
output_string += " " + line[i:i+2]
output_string += "\r\n"
fd.write(output_string)
#fd.flush()
if __name__ == "__main__":
#Parse command line arguments
parser = OptionParser()
parser.add_option("-t", "--tty", action="store", dest="ttyno",
type="string", default='0',
help="Number of ttyACM the OpenPICC is connected to [default: %default]")
parser.add_option("-r", "--reader", action="store", dest="readerno",
type="string", default='0',
help="Number of ttyACM the OpenPICC is connected to [default: %default]")
(options, args) = parser.parse_args()
if (options.ttyno.isdigit()):
nr = options.ttyno
else:
print "Invalid tty number %s. Using default tty (/dev/ttyACM0)" % options.ttyno
nr = '0'
if (options.readerno.isdigit()):
readerno = int(options.readerno)
else:
print "Invalid reader number %s. Using default reader (0)"
readerno = 0
ttyPath = "/dev/ttyACM" + nr
#Connect to Virtual PCD via PC/SC
try:
connection = setup(readerno)
except:
print "PC/SC Error"
sys.exit()
#Open terminal
try:
fd = open(ttyPath,'a+')
except IOError:
print "Failed to open %s" % ttyPath
sys.exit()
#Actual processing
while (True):
try:
apdu = read_from_picc(fd)
except IOError:
print "Failed to read from %s" % ttyPath
sys.exit()
if (apdu == None):
continue
else:
print("Got APDU: %s" %apdu)
response = transmit_to_pcsc(apdu)
try:
write_to_picc(response,fd)
except IOError:
print "Failed to write to %s" % ttyPath
sys.exit()

View File

@@ -0,0 +1,241 @@
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <winscard.h>
#include <string.h>
#include "picc_to_pcsc.h"
static sighandler_t register_sig(int signo, sighandler_t sighandler) {
struct sigaction new_sig, old_sig;
new_sig.sa_handler = sighandler;
sigemptyset (&new_sig.sa_mask);
new_sig.sa_flags = SA_RESTART;
if (sigaction (signo, &new_sig, &old_sig) < 0)
return SIG_ERR;
return old_sig.sa_handler;
}
char* perform_initialization(int num)
{
char *readers, *str;
DWORD size;
LONG r;
r = SCardEstablishContext(SCARD_SCOPE_SYSTEM, NULL, NULL, &hcontext);
if (r != SCARD_S_SUCCESS) {
fprintf(stderr, "pc/sc error: %s\n", pcsc_stringify_error(r));
SCardReleaseContext(hcontext);
return NULL;
}
r = SCardListReaders(hcontext, NULL, NULL, &size);
if (size == 0)
r = SCARD_E_UNKNOWN_READER;
if (r != SCARD_S_SUCCESS) {
fprintf(stderr, "pc/sc error: %s\n", pcsc_stringify_error(r));
SCardReleaseContext(hcontext);
return NULL;
}
/* get all readers */
readers = (char*)malloc(size);
if (readers == NULL) {
fprintf(stderr, "pc/sc error: %s\n",
pcsc_stringify_error(SCARD_E_NO_MEMORY));
SCardReleaseContext(hcontext);
return NULL;
}
r = SCardListReaders(hcontext, NULL, readers, &size);
if (r != SCARD_S_SUCCESS) {
free(readers);
fprintf(stderr, "pc/sc error: %s\n", pcsc_stringify_error(r));
SCardReleaseContext(hcontext);
return NULL;
}
/* name of reader number num*/
str = readers;
for (size = 0; size < num; size++) {
/* go to the next name */
str += strlen(str) + 1;
/* no more readers available? */
if (strlen(str) == 0) {
free(readers);
fprintf(stderr, "pc/sc error: %s\n",
pcsc_stringify_error(SCARD_E_UNKNOWN_READER));
SCardReleaseContext(hcontext);
return NULL;
}
}
strcpy(reader_name, str);
free(readers);
rstate.dwCurrentState = SCARD_STATE_UNAWARE;
rstate.szReader = reader_name;
return reader_name;
}
void setup() {
/*setup environment, open device, set global filehandle*/
DWORD dwActiveProtocol;
LONG pcsc_result;
perform_initialization(0); /*Right num for PICC?*/
printf("Initialised reader: %s\n",reader_name);
pcsc_result = SCardConnect(hcontext, reader_name,
SCARD_SHARE_EXCLUSIVE, (SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1),
&hcard, &dwActiveProtocol);
if (pcsc_result == SCARD_S_SUCCESS) {
pcsc_result = SCardGetStatusChange(hcontext, 1, &rstate, 1);
if (pcsc_result != SCARD_S_SUCCESS) fprintf(stderr,"%s\n",pcsc_stringify_error(pcsc_result));
} else {
fprintf(stderr,"%s\n",pcsc_stringify_error(pcsc_result));
}
/*Register our signal handlers*/
register_sig(SIGINT,checkSig);
/*Open the device*/
fd = fopen(PICCDEV, "a+"); /*O_NOCTTY ?*/
if (fd == NULL) {
fprintf(stderr,"Failed to open %s. Exiting.\n", PICCDEV);
exit(-1);
} else printf("Initialisation completed\n");
}
void checkSig(int signo){
if (signo == SIGINT)
printf("Received SIGINT, exiting.\n");
cleanup();
}
void printHex(char *title, unsigned char *msg, unsigned int length) {
int n = 0;
printf("%s: \t",title);
while (n<length) {
printf("%x ",msg[n]);
n++;
}
printf("\n");
}
void cleanup() {
int releaseContext;
/*Power down card*/
SCardDisconnect(hcard, SCARD_UNPOWER_CARD);
releaseContext = SCardReleaseContext(hcontext);
if (releaseContext != SCARD_S_SUCCESS) {
printf("%s\n",pcsc_stringify_error(releaseContext));
}
printf("Smartcard disconnected\n");
/*Close the device*/
fclose(fd);
/*Die*/
exit(0);
}
unsigned int read_from_device(unsigned char *inputBuffer) {
char *line;
size_t linelen=0;
if(getline(&line, &linelen, fd) != -1) {
printf("%s\n",line);
fflush(stdout);
} else {line = NULL;}// cleanup();} //Should we quit when we encounter an EOL?
unsigned int length=0;
unsigned char *buf=NULL;
if (line != NULL && line[0] == '0') { //Ignore empty lines and 'RESET' lines
sscanf(line, "%x : ", &length );
buf = malloc(length);
if(buf == NULL) { fprintf(stderr, "WAHH!\n"); return 0; }
int pos=0;
while(sscanf(line+(pos*3+5), " %x ", (unsigned int *) &(buf[pos])) == 1) {
printf("[%02X]", buf[pos]);
if(++pos >= length) break;
}
printf("Have %i bytes, should have %i bytes\n", pos, length);
memcpy(inputBuffer,buf,length);
}
if(line != NULL) {
free(line);
}
if(buf != NULL) {
free(buf);
}
return length;
}
int transmit_to_pcsc(unsigned char *inputBuffer, unsigned int inputLength, unsigned char *outputBuffer, unsigned int *outputLength) {
printHex("APDU", inputBuffer, inputLength);
unsigned int dwRecvLength = MAX_BUFFER_SIZE;
int result;
result = SCardTransmit(hcard, SCARD_PCI_T0, inputBuffer,
inputLength, NULL, outputBuffer, (DWORD*) &dwRecvLength);
/*Check response code */
if (result != SCARD_S_SUCCESS) {
fprintf(stderr,"SCardTransmit failed.\n");
fprintf(stderr,"dwRecvLength = %d maximum is:%d\n",dwRecvLength,MAX_BUFFER_SIZE);
fprintf(stderr,"%s\n",pcsc_stringify_error(result));
return -1;
} else {
printf("Received %d Byte\n",dwRecvLength);
printHex("RAPDU", outputBuffer, dwRecvLength);
*outputLength = dwRecvLength;
}
return 0;
}
void write_to_device(unsigned char *buffer, unsigned int msgLength) {
char* foo;
foo = (char*) malloc(msgLength*3+5);
//fprintf(fd, "%04X:", msgLength);
sprintf(foo,"%04X:",msgLength);
int i;
for(i=0; i<msgLength; i++) {
sprintf(&foo[3*i+5]," %02X",buffer[i]);
//fprintf(fd, " %02X", buffer[i]);
}
printf("%s",foo);
fprintf(fd,"%s", foo);
fprintf(fd, "\r\n");
fflush(fd);
free(foo);
}
int main (int argv, char **args) {
unsigned char inputBuffer[MAX_BUFFER_SIZE];
unsigned char outputBuffer[MAX_BUFFER_SIZE];
unsigned int inputLength, outputLength = MAX_BUFFER_SIZE;
int status;
setup();
while(1) {
inputLength = read_from_device(inputBuffer);
if (inputLength == 0) continue;
fflush(fd);
status = transmit_to_pcsc(inputBuffer,inputLength,outputBuffer,&outputLength);
if (!status) {
write_to_device(outputBuffer, outputLength);
//fprintf(fd,"0002: 90 00\0");
} else {
printf("Failed\n");
}
}
cleanup();
return 0;
}

View File

@@ -0,0 +1,24 @@
#ifndef PICC_TO_PCSC
#define PICC_TO_PCSC
#define PICCDEV "/dev/ttyACM0"
typedef void (*sighandler_t)(int);
/*Global variables*/
FILE *fd; /*filehandle used for PICCDEV*/
SCARDCONTEXT hcontext;
SCARDHANDLE hcard;
SCARD_READERSTATE rstate;
char reader_name[MAX_READERNAME];
static sighandler_t register_sig(int signo, sighandler_t sighandler);
void checkSig(int signo);
unsigned int read_from_device(unsigned char *inputBuffer);
int transmit_to_pcsc(unsigned char *inputBuffer, unsigned int inputLength, unsigned char *outputBuffer, unsigned int *outputLength);
void write_to_device(unsigned char *buffer, unsigned int msglength);
void setup();
void cleanup();
void printHex(char *title, unsigned char *msg, unsigned int length);
#endif