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