OpenPGP: refactor do_dump_do()

- limit length of data to write even in raw mode to the real length
- cluster variuable definitions
- restrict scope of variables
- introduce a variable length to make the purpose more obious
- start preprocessor directives at column one
- add comments where needed
- harmonize coding style: space after "if" and casts
This commit is contained in:
Peter Marschall 2018-06-05 09:08:17 +02:00 committed by Frank Morgner
parent 4a1bf9fb21
commit ba9eebceaf
1 changed files with 19 additions and 16 deletions

View File

@ -391,11 +391,10 @@ static int do_userinfo(sc_card_t *card)
static int do_dump_do(sc_card_t *card, unsigned int tag) static int do_dump_do(sc_card_t *card, unsigned int tag)
{ {
int r, tmp; int r;
FILE *fp; size_t length;
unsigned char buffer[254]; // Private DO are specified up to 254 bytes
// Private DO are specified up to 254 bytes
unsigned char buffer[254];
memset(buffer, '\0', sizeof(buffer)); memset(buffer, '\0', sizeof(buffer));
if (tag < 0x101 || tag > 0x104) { if (tag < 0x101 || tag > 0x104) {
@ -411,9 +410,12 @@ static int do_dump_do(sc_card_t *card, unsigned int tag)
} }
return r; return r;
} }
length = (size_t) r; /* r is guaranteed to be non-negative */
if (opt_raw) { if (opt_raw) {
r = 0; int tmp;
FILE *fp;
#ifndef _WIN32 #ifndef _WIN32
tmp = dup(fileno(stdout)); tmp = dup(fileno(stdout));
#else #else
@ -423,7 +425,7 @@ static int do_dump_do(sc_card_t *card, unsigned int tag)
return EXIT_FAILURE; return EXIT_FAILURE;
fp = freopen(NULL, "wb", stdout); fp = freopen(NULL, "wb", stdout);
if (fp) { if (fp) {
r = (int)fwrite(buffer, sizeof(char), sizeof(buffer), fp); r = (int) fwrite(buffer, sizeof(char), length, fp);
} }
#ifndef _WIN32 #ifndef _WIN32
dup2(tmp, fileno(stdout)); dup2(tmp, fileno(stdout));
@ -432,10 +434,11 @@ static int do_dump_do(sc_card_t *card, unsigned int tag)
#endif #endif
clearerr(stdout); clearerr(stdout);
close(tmp); close(tmp);
if (sizeof(buffer) != r)
if (length != r) /* fail on write errors */
return EXIT_FAILURE; return EXIT_FAILURE;
} else { } else {
util_hex_dump_asc(stdout, buffer, r, -1); util_hex_dump_asc(stdout, buffer, length, -1);
} }
return EXIT_SUCCESS; return EXIT_SUCCESS;