]> git.lizzy.rs Git - plan9front.git/blob - sys/src/libauthsrv/readcons.c
upas/fs: remove unused function date822tounix
[plan9front.git] / sys / src / libauthsrv / readcons.c
1 #include <u.h>
2 #include <libc.h>
3
4 /*
5  *  prompt for a string with a possible default response
6  */
7 char*
8 readcons(char *prompt, char *def, int raw)
9 {
10         int fdin, fdout, ctl, n;
11         char *s, *p;
12
13         s = p = nil;
14         fdout = ctl = -1;
15
16         if((fdin = open("/dev/cons", OREAD)) < 0)
17                 goto Out;
18         if((fdout = open("/dev/cons", OWRITE)) < 0)
19                 goto Out;
20
21         if(raw){
22                 if((ctl = open("/dev/consctl", OWRITE)) < 0)
23                         goto Out;
24                 write(ctl, "rawon", 5);
25         }
26
27         if(def != nil)
28                 fprint(fdout, "%s[%s]: ", prompt, def);
29         else
30                 fprint(fdout, "%s: ", prompt);
31
32         for(;;){
33                 n = p - s;
34                 if((n % 32) == 0){
35                         if((p = realloc(s, n+32)) == nil)
36                                 break;
37                         s = p, p += n;
38                 }
39
40                 n = read(fdin, p, 1);
41                 if(n < 0)
42                         break;
43                 if(n == 0 || *p == 0x7f){
44                         werrstr("input aborted");
45                         break;
46                 }
47
48                 if(*p == '\n' || *p == '\r'){
49                         if(p == s && def != nil){
50                                 free(s);
51                                 s = strdup(def);
52                         } else
53                                 *p = 0;
54                         if(raw)
55                                 write(fdout, "\n", 1);
56                         goto Out;
57                 } else if(*p == '\b') {
58                         while(p > s && (p[-1] & 0xc0) == 0x80)
59                                 *p-- = 0;
60                         if(p > s)
61                                 *p-- = 0;
62                 } else if(*p == 0x15) { /* ^U: line kill */
63                         if(def != nil)
64                                 fprint(fdout, "\n%s[%s]: ", prompt, def);
65                         else
66                                 fprint(fdout, "\n%s: ", prompt);
67                         while(p > s)
68                                 *p-- = 0;
69                 } else if(*p >= ' ')
70                         p++;
71         }
72         free(s);
73         s = nil;
74         if(raw)
75                 write(fdout, "\n", 1);
76 Out:
77         if(ctl >= 0){
78                 write(ctl, "rawoff", 6);
79                 close(ctl);
80         }
81         if(fdin >= 0)
82                 close(fdin);
83         if(fdout >= 0)
84                 close(fdout);
85
86         return s;
87 }