util.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <mp.h>
  4. #include <libsec.h>
  5. #include "SConn.h"
  6. #include "secstore.h"
  7. void *
  8. emalloc(ulong n)
  9. {
  10. void *p = malloc(n);
  11. if(p == nil)
  12. sysfatal("emalloc");
  13. memset(p, 0, n);
  14. return p;
  15. }
  16. void *
  17. erealloc(void *p, ulong n)
  18. {
  19. if ((p = realloc(p, n)) == nil)
  20. sysfatal("erealloc");
  21. return p;
  22. }
  23. char *
  24. estrdup(char *s)
  25. {
  26. if ((s = strdup(s)) == nil)
  27. sysfatal("estrdup");
  28. return s;
  29. }
  30. char*
  31. getpassm(char *prompt)
  32. {
  33. char *p, line[4096];
  34. int n, nr;
  35. static int cons, consctl; // closing and reopening fails in ssh environment
  36. if(cons == 0){ // first time
  37. cons = open("/dev/cons", ORDWR);
  38. if(cons < 0)
  39. sysfatal("couldn't open cons");
  40. consctl = open("/dev/consctl", OWRITE);
  41. if(consctl < 0)
  42. sysfatal("couldn't set raw mode via consctl");
  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. }
  84. char *
  85. validatefile(char *f)
  86. {
  87. char *nl;
  88. if(f==nil || *f==0)
  89. return nil;
  90. if(nl = strchr(f, '\n'))
  91. *nl = 0;
  92. if(strchr(f,'/') != nil || strcmp(f,"..")==0 || strlen(f) >= 300){
  93. syslog(0, LOG, "no slashes allowed: %s\n", f);
  94. return nil;
  95. }
  96. return f;
  97. }