[ create a new paste ] login | about

Link: http://codepad.org/JkVp50nQ    [ raw code | fork ]

C, pasted on Sep 12:
#include "getpassword.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * \brief Read a password without character echoing.
 * \note Input ends only when an EOF or LF character is encountered.
 * \param prompt Password prompt, if NULL "Password: " is used. If empty ("")
 * no prompt is used.
 * \param buffer Somewhere to store the password. This will be made larger if
 * necessary, although the enlargening operation will be slow. If NULL, the
 * function fails.
 * \param sz Pointer to the size of buffer. This will be increased if necessary.
 * If sz is a NULL pointer the function fails.
 * \param replacement Character to print instead of printing input characters.
 * If this is '\0'; none is used.
 * \return 0 on success or -1 on error.
 */
int getpassword(const char* prompt, char** buffer, unsigned* sz, char replacement)
{
	if (!buffer || !sz)
		return -1;

	/*
	 * Decide what prompt to print, if any, and then print it
	 */
	const char* default_prompt = "Password: ";
	if (prompt != NULL) {
		fprintf(stderr, "%s", prompt);
	} else if (strcmp(prompt, "")) {
		fprintf(stderr, "%s", default_prompt);
	}

	/*
	 * Disable character echoing and line buffering
	 */
#if defined(WINDOWS)
	HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
	DWORD mode;

	if (!GetConsoleMode(hstdin, &mode))
		return -1;

	if (hstdin == INVALID_HANDLE_VALUE || !(SetConsoleMode(hstdin, 0)))
		return -1; /* Failed to disable buffering */
#elif defined(POSIX)
	struct termios tty_attr;

	if (tcgetattr(STDIN_FILENO, &tty_attr) < 0)
		return -1;

	const tcflag_t c_lflag = tty_attr.c_lflag; /* Allows us to restore this later */
	tty_attr.c_lflag &= ~ICANON;
	tty_attr.c_lflag &= ~ECHO;

	if (tcsetattr(STDIN_FILENO, 0, &tty_attr) < 0)
		return -1;
#endif

	int i = 0,
	    c = 0;
	for (; (c = getchar()) != '\n' && c != EOF; ++i) {
		/*
		 * If the buffer gets too full, expand it
		 */
		if (i > *sz) {
			if (!realloc(*buffer, *sz))
				return -1;
			(*sz) += 1;
		}

		if (replacement)
			putchar(replacement);

		(*buffer)[i] = c;
	}

	if (replacement)
		putchar('\n');

	/*
	 * Re-enable character echoing and line buffering
	 */
#if defined(WINDOWS)
	if (!SetConsoleMode(hstdin, mode))
		return -1;
#elif defined(POSIX)
	tty_attr.c_lflag = c_lflag;

	if (tcsetattr(STDIN_FILENO, 0, &tty_attr) < 0)
		return -1;
#endif
	return 0;
}

#ifdef __cplusplus
}
#endif


Create a new paste based on this one


Comments: