util.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. char*
  27. getpassm(char *prompt)
  28. {
  29. char *p, line[4096];
  30. int n, nr;
  31. static int cons, consctl; // closing and reopening fails in ssh environment
  32. if(cons == 0){ // first time
  33. cons = open("/dev/cons", ORDWR);
  34. if(cons < 0){
  35. fprint(2, "couldn't open cons\n");
  36. exits("no cons");
  37. }
  38. consctl = open("/dev/consctl", OWRITE);
  39. if(consctl < 0){
  40. fprint(2, "couldn't set raw mode\n");
  41. exits("no consctl");
  42. }
  43. }
  44. fprint(consctl, "rawon");
  45. fprint(cons, "%s", prompt);
  46. nr = 0;
  47. p = line;
  48. for(;;){
  49. n = read(cons, p, 1);
  50. if(n < 0){
  51. fprint(consctl, "rawoff");
  52. fprint(cons, "\n");
  53. return nil;
  54. }
  55. if(n == 0 || *p == '\n' || *p == '\r' || *p == 0x7f){
  56. *p = '\0';
  57. fprint(consctl, "rawoff");
  58. fprint(cons, "\n");
  59. p = strdup(line);
  60. memset(line, 0, nr);
  61. return p;
  62. }
  63. if(*p == '\b'){
  64. if(nr > 0){
  65. nr--;
  66. p--;
  67. }
  68. }else if(*p == 21){ /* cntrl-u */
  69. fprint(cons, "\n%s", prompt);
  70. nr = 0;
  71. p = line;
  72. }else{
  73. nr++;
  74. p++;
  75. }
  76. if(nr+1 == sizeof line){
  77. fprint(cons, "line too long; try again\n%s", prompt);
  78. nr = 0;
  79. p = line;
  80. }
  81. }
  82. return nil; // NOT REACHED
  83. }