xref: /plan9/sys/src/cmd/auth/lib/readln.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
1 #include <u.h>
2 #include <libc.h>
3 #include <auth.h>
4 #include "authsrv.h"
5 
6 void
7 getpass(char *key, int check)
8 {
9 	char pass[32], rpass[32];
10 	char *err;
11 
12 	readln("Password: ", pass, sizeof pass, 1);
13 	readln("Confirm password: ", rpass, sizeof rpass, 1);
14 	if(strcmp(pass, rpass) != 0)
15 		error("password mismatch");
16 	if(!passtokey(key, pass))
17 		error("bad password");
18 	if(check)
19 		if(err = okpasswd(pass))
20 			error(err);
21 }
22 
23 void
24 readln(char *prompt, char *line, int len, int raw)
25 {
26 	char *p;
27 	int fd, ctl, n, nr;
28 
29 	fd = open("/dev/cons", ORDWR);
30 	if(fd < 0)
31 		error("couldn't open cons");
32 	if(raw){
33 		ctl = open("/dev/consctl", OWRITE);
34 		if(ctl < 0)
35 			error("couldn't set raw mode");
36 		write(ctl, "rawon", 5);
37 	} else
38 		ctl = -1;
39 	fprint(fd, "%s", prompt);
40 	nr = 0;
41 	p = line;
42 	for(;;){
43 		n = read(fd, p, 1);
44 		if(n < 0){
45 			close(fd);
46 			close(ctl);
47 			error("can't read cons\n");
48 		}
49 		if(*p == 0x7f)
50 			exits(0);
51 		if(n == 0 || *p == '\n' || *p == '\r'){
52 			*p = '\0';
53 			if(raw)
54 				write(fd, "\n", 1);
55 			close(fd);
56 			close(ctl);
57 			return;
58 		}
59 		if(*p == '\b'){
60 			if(nr > 0){
61 				nr--;
62 				p--;
63 			}
64 		}else{
65 			nr++;
66 			p++;
67 		}
68 		if(nr == len){
69 			fprint(fd, "line too long; try again\n");
70 			nr = 0;
71 			p = line;
72 		}
73 	}
74 }
75