xref: /plan9/sys/src/cmd/auth/lib/readln.c (revision 5979f96214a33481f1724725761f2ef3585d2237)
1 #include <u.h>
2 #include <libc.h>
3 #include <authsrv.h>
4 #include <bio.h>
5 #include "authcmdlib.h"
6 
7 void
getpass(char * key,char * pass,int check,int confirm)8 getpass(char *key, char *pass, int check, int confirm)
9 {
10 	char rpass[32], npass[32];
11 	char *err;
12 
13 	if(pass == nil)
14 		pass = npass;
15 
16 	for(;;){
17 		readln("Password: ", pass, sizeof npass, 1);
18 		if(confirm){
19 			readln("Confirm password: ", rpass, sizeof rpass, 1);
20 			if(strcmp(pass, rpass) != 0){
21 				print("mismatch, try again\n");
22 				continue;
23 			}
24 		}
25 		if(!passtokey(key, pass)){
26 			print("bad password, try again\n");
27 			continue;
28 		}
29 		if(check)
30 			if(err = okpasswd(pass)){
31 				print("%s, try again\n", err);
32 				continue;
33 			}
34 		break;
35 	}
36 }
37 
38 int
getsecret(int passvalid,char * p9pass)39 getsecret(int passvalid, char *p9pass)
40 {
41 	char answer[32];
42 
43 	readln("assign Inferno/POP secret? (y/n) ", answer, sizeof answer, 0);
44 	if(*answer != 'y' && *answer != 'Y')
45 		return 0;
46 
47 	if(passvalid){
48 		readln("make it the same as the plan 9 password? (y/n) ",
49 			answer, sizeof answer, 0);
50 		if(*answer == 'y' || *answer == 'Y')
51 			return 1;
52 	}
53 
54 	for(;;){
55 		readln("Secret(0 to 256 characters): ", p9pass,
56 			sizeof answer, 1);
57 		readln("Confirm: ", answer, sizeof answer, 1);
58 		if(strcmp(p9pass, answer) == 0)
59 			break;
60 		print("mismatch, try again\n");
61 	}
62 	return 1;
63 }
64 
65 void
readln(char * prompt,char * line,int len,int raw)66 readln(char *prompt, char *line, int len, int raw)
67 {
68 	char *p;
69 	int fdin, fdout, ctl, n, nr;
70 
71 	fdin = open("/dev/cons", OREAD);
72 	fdout = open("/dev/cons", OWRITE);
73 	fprint(fdout, "%s", prompt);
74 	if(raw){
75 		ctl = open("/dev/consctl", OWRITE);
76 		if(ctl < 0)
77 			error("couldn't set raw mode");
78 		write(ctl, "rawon", 5);
79 	} else
80 		ctl = -1;
81 	nr = 0;
82 	p = line;
83 	for(;;){
84 		n = read(fdin, p, 1);
85 		if(n < 0){
86 			close(ctl);
87 			error("can't read cons\n");
88 		}
89 		if(*p == 0x7f)
90 			exits(0);
91 		if(n == 0 || *p == '\n' || *p == '\r'){
92 			*p = '\0';
93 			if(raw){
94 				write(ctl, "rawoff", 6);
95 				write(fdout, "\n", 1);
96 			}
97 			close(ctl);
98 			return;
99 		}
100 		if(*p == '\b'){
101 			if(nr > 0){
102 				nr--;
103 				p--;
104 			}
105 		}else{
106 			nr++;
107 			p++;
108 		}
109 		if(nr == len){
110 			fprint(fdout, "line too long; try again\n");
111 			nr = 0;
112 			p = line;
113 		}
114 	}
115 }
116