From d0618ba24c0b442d2965e05a39057f7712ad019d Mon Sep 17 00:00:00 2001 From: "viktor.tarasov" Date: Sun, 18 Apr 2010 07:47:16 +0000 Subject: [PATCH] tools: #120: 'getpass' sensible to Ctrl-C, thanks to Andreas git-svn-id: https://www.opensc-project.org/svnp/opensc/trunk@4249 c6295689-39f2-0310-b995-f0e70906c6a9 --- src/tools/util.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++- src/tools/util.h | 2 ++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/tools/util.c b/src/tools/util.c index 7005c80b..65ea7062 100644 --- a/src/tools/util.c +++ b/src/tools/util.c @@ -3,8 +3,10 @@ #include #include #include +#ifndef _WIN32 +#include +#endif #include - #include "util.h" int util_connect_card(sc_context_t *ctx, sc_card_t **cardp, @@ -281,3 +283,66 @@ util_warn(const char *fmt, ...) va_end(ap); } +int util_getpass (char **lineptr, size_t *len, FILE *stream) +{ +#ifdef _WIN32 +#define MAX_PASS_SIZE 128 + char *buf; + int i; + + buf = calloc(1, MAX_PASS_SIZE); + if (!buf) + return -1; + + for (i = 0; i < MAX_PASS_SIZE - 1; i++) { + buf[i] = _getch(); + if (buf[i] == 0 || buf[i] == 3) + return -1; + if (buf[i] == '\n' || buf[i] == '\r') + break; + } + buf[i] = 0; + + if (*lineptr) { + if (*len < i+1) { + free(*lineptr); + *lineptr=buf; + *len = MAX_PASS_SIZE; + } else { + memcpy(*lineptr,buf,i+1); + memset(buf, 0, MAX_PASS_SIZE); + free(buf); + } + } else { + *lineptr = buf; + if (len) + *len = MAX_PASS_SIZE; + } + return i; +#else + struct termios old, new; + int nread; + + /* Turn echoing off and fail if we can't. */ + if (tcgetattr (fileno (stream), &old) != 0) + return -1; + new = old; + new.c_lflag &= ~ECHO; + if (tcsetattr (fileno (stream), TCSAFLUSH, &new) != 0) + return -1; + + /* Read the password. */ + nread = getline (lineptr, len, stream); + if (nread < 0) + return -1; + + /* Remove trailing CR */ + if (*(*lineptr + nread - 1) == '\n' || *(*lineptr + nread - 1) == '\r') + *(*lineptr + --nread) = '\0'; + + /* Restore terminal. */ + (void) tcsetattr (fileno (stream), TCSAFLUSH, &old); + return nread; +#endif +} + diff --git a/src/tools/util.h b/src/tools/util.h index dda771e3..f0ea80b7 100644 --- a/src/tools/util.h +++ b/src/tools/util.h @@ -35,6 +35,8 @@ void util_fatal(const char *fmt, ...); /* All singing all dancing card connect routine */ int util_connect_card(struct sc_context *, struct sc_card **, const char *reader_id, int wait, int verbose); +int util_getpass (char **lineptr, size_t *n, FILE *stream); + #ifdef __cplusplus } #endif