xref: /plan9-contrib/sys/src/cmd/auth/secstore/util.c (revision ec59a3ddbfceee0efe34584c2c9981a5e5ff1ec4)
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 
8 void *
9 emalloc(ulong n)
10 {
11 	void *p = malloc(n);
12 	if(p == nil)
13 		sysfatal("emalloc");
14 	memset(p, 0, n);
15 	return p;
16 }
17 
18 void *
19 erealloc(void *p, ulong n)
20 {
21 	if ((p = realloc(p, n)) == nil)
22 		sysfatal("erealloc");
23 	return p;
24 }
25 
26 char *
27 estrdup(char *s)
28 {
29 	if ((s = strdup(s)) == nil)
30 		sysfatal("estrdup");
31 	return s;
32 }
33 
34 char*
35 getpassm(char *prompt)
36 {
37 	char *p, line[4096];
38 	int n, nr;
39 	static int cons, consctl;  // closing and reopening fails in ssh environment
40 
41 	if(cons == 0){ // first time
42 		cons = open("/dev/cons", ORDWR);
43 		if(cons < 0)
44 			sysfatal("couldn't open cons");
45 		consctl = open("/dev/consctl", OWRITE);
46 		if(consctl < 0)
47 			sysfatal("couldn't set raw mode via consctl");
48 	}
49 	fprint(consctl, "rawon");
50 	fprint(cons, "%s", prompt);
51 	nr = 0;
52 	p = line;
53 	for(;;){
54 		n = read(cons, p, 1);
55 		if(n < 0){
56 			fprint(consctl, "rawoff");
57 			fprint(cons, "\n");
58 			return nil;
59 		}
60 		if(n == 0 || *p == '\n' || *p == '\r' || *p == 0x7f){
61 			*p = '\0';
62 			fprint(consctl, "rawoff");
63 			fprint(cons, "\n");
64 			p = strdup(line);
65 			memset(line, 0, nr);
66 			return p;
67 		}
68 		if(*p == '\b'){
69 			if(nr > 0){
70 				nr--;
71 				p--;
72 			}
73 		}else if(*p == 21){		/* cntrl-u */
74 			fprint(cons, "\n%s", prompt);
75 			nr = 0;
76 			p = line;
77 		}else{
78 			nr++;
79 			p++;
80 		}
81 		if(nr+1 == sizeof line){
82 			fprint(cons, "line too long; try again\n%s", prompt);
83 			nr = 0;
84 			p = line;
85 		}
86 	}
87 }
88 
89 char *
90 validatefile(char *f)
91 {
92 	char *nl;
93 
94 	if(f==nil || *f==0)
95 		return nil;
96 	if(nl = strchr(f, '\n'))
97 		*nl = 0;
98 	if(strchr(f,'/') != nil || strcmp(f,"..")==0 || strlen(f) >= 300){
99 		syslog(0, LOG, "no slashes allowed: %s\n", f);
100 		return nil;
101 	}
102 	return f;
103 }
104 
105