util.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. fprint(2, "couldn't open cons\n");
  40. exits("no cons");
  41. }
  42. consctl = open("/dev/consctl", OWRITE);
  43. if(consctl < 0){
  44. fprint(2, "couldn't set raw mode\n");
  45. exits("no consctl");
  46. }
  47. }
  48. fprint(consctl, "rawon");
  49. fprint(cons, "%s", prompt);
  50. nr = 0;
  51. p = line;
  52. for(;;){
  53. n = read(cons, p, 1);
  54. if(n < 0){
  55. fprint(consctl, "rawoff");
  56. fprint(cons, "\n");
  57. return nil;
  58. }
  59. if(n == 0 || *p == '\n' || *p == '\r' || *p == 0x7f){
  60. *p = '\0';
  61. fprint(consctl, "rawoff");
  62. fprint(cons, "\n");
  63. p = strdup(line);
  64. memset(line, 0, nr);
  65. return p;
  66. }
  67. if(*p == '\b'){
  68. if(nr > 0){
  69. nr--;
  70. p--;
  71. }
  72. }else if(*p == 21){ /* cntrl-u */
  73. fprint(cons, "\n%s", prompt);
  74. nr = 0;
  75. p = line;
  76. }else{
  77. nr++;
  78. p++;
  79. }
  80. if(nr+1 == sizeof line){
  81. fprint(cons, "line too long; try again\n%s", prompt);
  82. nr = 0;
  83. p = line;
  84. }
  85. }
  86. return nil; // NOT REACHED
  87. }
  88. char *
  89. validatefile(char *f)
  90. {
  91. char *nl;
  92. if(f==nil || *f==0)
  93. return nil;
  94. if(nl = strchr(f, '\n'))
  95. *nl = 0;
  96. if(strchr(f,'/') != nil || strcmp(f,"..")==0 || strlen(f) >= 300){
  97. syslog(0, LOG, "no slashes allowed: %s\n", f);
  98. return nil;
  99. }
  100. return f;
  101. }