gcns.c: refactoring

This commit is contained in:
giomba 2022-01-06 18:04:42 +01:00
parent 606edadb13
commit 5167b30043
2 changed files with 68 additions and 23 deletions

View File

@ -38,6 +38,7 @@
#include <getopt.h>
#include "common/compat_strlcpy.h"
#include "gcns.h"
#include "libopensc/asn1.h"
#include "libopensc/cardctl.h"
#include "libopensc/cards.h"
@ -51,57 +52,92 @@ static int opt_wait = 0;
static const char *opt_reader = NULL;
static sc_context_t *ctx = NULL;
static sc_card_t *card = NULL;
sc_context_param_t ctx_param;
static void die(int ret) {
if (card) {
sc_disconnect_card(card);
}
if (ctx) sc_release_context(ctx);
exit(ret);
}
int main(int argc, char *argv[]) {
int gcns_init() {
int r, err = 0;
sc_context_param_t ctx_param;
int lcycle = SC_CARDCTRL_LIFECYCLE_ADMIN;
printf("OpenSC version: %s\n", sc_get_version());
memset(&ctx_param, 0, sizeof(ctx_param));
ctx_param.ver = 0;
r = sc_context_create(&ctx, &ctx_param);
if (r) {
fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
return 1;
return GCNS_INIT;
}
ctx->flags |= SC_CTX_FLAG_ENABLE_DEFAULT_DRIVER;
err = util_connect_card_ex(ctx, &card, opt_reader, opt_wait, 0, 0);
if (err) goto end;
if (err) {
return GCNS_INIT;
}
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_card_ctl(card, SC_CARDCTL_LIFECYCLE_SET, &lcycle);
sc_unlock(card);
if (r && r != SC_ERROR_NOT_SUPPORTED)
printf("unable to change lifecycle: %s\n", sc_strerror(r));
if (r && r != SC_ERROR_NOT_SUPPORTED) {
fprintf(stderr, "unable to change lifecycle: %s\n", sc_strerror(r));
return GCNS_INIT;
}
u8 buffer[2048];
return GCNS_SUCCESS;
}
int gcns_close() {
if (card) {
sc_disconnect_card(card);
}
if (ctx) sc_release_context(ctx);
return GCNS_SUCCESS;
}
int gcns_read_personal_data(u8 *buffer, size_t len) {
sc_path_t path;
int r;
sc_format_path("3F0011001102", &path);
r = sc_select_file(card, &path, NULL);
if (r) {
fprintf(stderr, "no select file 3F0011001102\n");
fprintf(stderr, "no select file: 3F0011001102\n");
return GCNS_READ_PERSONAL_DATA;
}
r = sc_read_binary(card, 0, buffer, 0x180, 0);
if (r) {
if (r < 0) {
fprintf(stderr, "no read binary: %d\n", r);
return GCNS_READ_PERSONAL_DATA;
}
util_hex_dump_asc(stdout, buffer, r, 0);
end:
die(err);
return 0; /* not reached */
return r;
}
int main(int argc, char *argv[]) {
int r;
printf("OpenSC version: %s\n", sc_get_version());
r = gcns_init();
if (r != GCNS_SUCCESS) {
fprintf(stderr, "Init Error\n");
return GCNS_INIT;
}
u8 buffer[2048];
r = gcns_read_personal_data(buffer, 2048);
if (r < 0) {
fprintf(stderr, "Read personal data error\n");
return GCNS_READ_PERSONAL_DATA;
}
util_hex_dump_asc(stdout, buffer, r, 0);
r = gcns_close();
if (r != GCNS_SUCCESS) {
return GCNS_CLOSE;
}
return GCNS_SUCCESS;
}

9
src/tools/gcns.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef GCNS_H
#define GCNS_h
#define GCNS_SUCCESS 0
#define GCNS_INIT -1001
#define GCNS_READ_PERSONAL_DATA -1002
#define GCNS_CLOSE -1003
#endif