pwd.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
  2. /*
  3. * Copyright 2017 Red Hat, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #pragma once
  18. #include <string.h>
  19. #include <ctype.h>
  20. #ifdef _WIN32
  21. static const char *
  22. jwe_getpass(const char *prompt)
  23. {
  24. static char pwd[4096];
  25. fprintf(stdout, "%s", prompt);
  26. memset(pwd, 0, sizeof(pwd));
  27. for (size_t i = 0; i < sizeof(pwd) - 1; i++) {
  28. int c = fgetc(stdin);
  29. if (c == EOF || !isprint(c) || isspace(c))
  30. break;
  31. pwd[i] = c;
  32. }
  33. return pwd;
  34. }
  35. #else
  36. #include <termios.h>
  37. static const char *
  38. jwe_getpass(const char *prompt)
  39. {
  40. static char pwd[4096];
  41. struct termios of, nf;
  42. FILE *tty = NULL;
  43. tty = fopen("/dev/tty", "r+");
  44. if (!tty)
  45. return NULL;
  46. tcgetattr(fileno(tty), &of);
  47. nf = of;
  48. nf.c_lflag &= ~ECHO;
  49. nf.c_lflag |= ECHONL;
  50. if (tcsetattr(fileno(tty), TCSANOW, &nf) != 0) {
  51. fclose(tty);
  52. return NULL;
  53. }
  54. fprintf(tty, "%s", prompt);
  55. memset(pwd, 0, sizeof(pwd));
  56. for (size_t i = 0; i < sizeof(pwd) - 1; i++) {
  57. int c = fgetc(tty);
  58. if (c == EOF || !isprint(c) || isspace(c))
  59. break;
  60. pwd[i] = c;
  61. }
  62. tcsetattr(fileno(tty), TCSANOW, &of);
  63. fclose(tty);
  64. return pwd;
  65. }
  66. #endif