/*+++++++++++++++++
  passwd.c - functions for reading a password securely
  markus@mhoenicka.de 2006-09-19

   This program 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 2 of the License, or
   (at your option) any later version.
   
   This program 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 this program; if not, see <http://www.gnu.org/licenses/>

  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

#include <stdio.h>
#include <string.h>
#include <termios.h>

#include "refdb.h"
#include "passwd.h"

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  ask_for_passwd(): asks user for a password. To protect the password,
                    the characters are not displayed on the screen
		    while the user types them. We don't even give a
		    hint about the length of the password by not
		    displaying '*' for each character

  int ask_for_password returns 0 if ok, 1 if some error occurred

  char* passwd ptr to a buffer that can hold a password that is
                    PREFS_BUF_LEN byte long.

  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
int ask_for_passwd(char* passwd) {
  int done = 0;
  int pw_len;
  struct termios initialrsettings;
  struct termios newrsettings;

  /* get current settings of stdin */
  tcgetattr(fileno(stdin), &initialrsettings);
  
  newrsettings = initialrsettings;
  newrsettings.c_lflag &= ~ECHO;

  /* set new attributes. TCSAFLUSH discards any previously typed stuff */
  if (tcsetattr(fileno(stdin), TCSAFLUSH, &newrsettings) != 0) {
    fprintf(stderr, "Could not set terminal attributes\n");
    return 1;
  }

  while (!done) {
    fprintf(stderr, "Please enter your password: ");
    if (fgets(passwd, PASSWD_LENGTH+1, stdin) != NULL) {
      done = 1;
    }
  }

  /* reset terminal to the previous state */
  tcsetattr(fileno(stdin), TCSANOW, &initialrsettings);
  fprintf(stderr, "\n");

  /* be paranoid */
  passwd[PASSWD_LENGTH] = '\0';

  /* remove newline if necessary */
  pw_len = strlen(passwd)-1;
  if (passwd[pw_len] == '\n') {
    passwd[pw_len] = '\0';
  }

  return 0;
}

