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