util.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #include <u.h>
  2. #include <libc.h>
  3. void *
  4. emalloc(ulong n)
  5. {
  6. void *p = malloc(n);
  7. if(p == nil)
  8. sysfatal("emalloc");
  9. memset(p, 0, n);
  10. return p;
  11. }
  12. void *
  13. erealloc(void *p, ulong n)
  14. {
  15. if ((p = realloc(p, n)) == nil)
  16. sysfatal("erealloc");
  17. return p;
  18. }
  19. char *
  20. estrdup(char *s)
  21. {
  22. if ((s = strdup(s)) == nil)
  23. sysfatal("estrdup");
  24. return s;
  25. }
  26. // name changed from getpass() to avoid conflict with Irix stdlib.h
  27. int
  28. getpasswd(char *prompt, char *line, int len)
  29. {
  30. char *p;
  31. int n, nr;
  32. static int cons, consctl; // closing and reopening fails in ssh environment
  33. if(cons == 0){ // first time
  34. cons = open("/dev/cons", ORDWR);
  35. if(cons < 0){
  36. fprint(2, "couldn't open cons\n");
  37. exits("no cons");
  38. }
  39. consctl = open("/dev/consctl", OWRITE);
  40. if(consctl < 0){
  41. fprint(2, "couldn't set raw mode\n");
  42. exits("no consctl");
  43. }
  44. }
  45. fprint(consctl, "rawon");
  46. fprint(cons, "%s", prompt);
  47. nr = 0;
  48. p = line;
  49. for(;;){
  50. n = read(cons, p, 1);
  51. if(n < 0){
  52. fprint(consctl, "rawoff");
  53. fprint(cons, "\n");
  54. return -1;
  55. }
  56. if(n == 0 || *p == '\n' || *p == '\r' || *p == 0x7f){
  57. *p = '\0';
  58. fprint(consctl, "rawoff");
  59. fprint(cons, "\n");
  60. return nr;
  61. }
  62. if(*p == '\b'){
  63. if(nr > 0){
  64. nr--;
  65. p--;
  66. }
  67. }else if(*p == 21){ /* cntrl-u */
  68. fprint(cons, "\n%s", prompt);
  69. nr = 0;
  70. p = line;
  71. }else{
  72. nr++;
  73. p++;
  74. }
  75. if(nr == len){
  76. fprint(cons, "line too long; try again\n%s", prompt);
  77. nr = 0;
  78. p = line;
  79. }
  80. }
  81. return -1; // NOT REACHED
  82. }