Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <auth.h>
4 #include <9pclient.h>
5 #include "authlocal.h"
7 static struct {
8 char *verb;
9 int val;
10 } tab[] = {
11 "ok", ARok,
12 "done", ARdone,
13 "error", ARerror,
14 "needkey", ARneedkey,
15 "badkey", ARbadkey,
16 "phase", ARphase,
17 "toosmall", ARtoosmall,
18 "error", ARerror,
19 };
21 static long
22 rpcread(AuthRpc *rpc, void *buf, int buflen)
23 {
24 if (rpc->afd >= 0)
25 return read(rpc->afd, buf, buflen);
26 else
27 return fsread(rpc->afid, buf, buflen);
28 }
30 static long
31 rpcwrite(AuthRpc *rpc, void *buf, int buflen)
32 {
33 if (rpc->afd >= 0)
34 return write(rpc->afd, buf, buflen);
35 else
36 return fswrite(rpc->afid, buf, buflen);
37 }
39 static int
40 classify(char *buf, uint n, AuthRpc *rpc)
41 {
42 int i, len;
44 for(i=0; i<nelem(tab); i++){
45 len = strlen(tab[i].verb);
46 if(n >= len && memcmp(buf, tab[i].verb, len) == 0 && (n==len || buf[len]==' ')){
47 if(n==len){
48 rpc->narg = 0;
49 rpc->arg = "";
50 }else{
51 rpc->narg = n - (len+1);
52 rpc->arg = (char*)buf+len+1;
53 }
54 return tab[i].val;
55 }
56 }
57 werrstr("malformed rpc response: %s", buf);
58 return ARrpcfailure;
59 }
61 AuthRpc*
62 auth_allocrpc(void)
63 {
64 AuthRpc *rpc;
66 rpc = mallocz(sizeof(*rpc), 1);
67 if(rpc == nil)
68 return nil;
69 rpc->afd = open("/mnt/factotum/rpc", ORDWR);
70 if(rpc->afd < 0){
71 rpc->afid = nsopen("factotum", nil, "rpc", ORDWR);
72 if(rpc->afid == nil){
73 free(rpc);
74 return nil;
75 }
76 }
77 return rpc;
78 }
80 void
81 auth_freerpc(AuthRpc *rpc)
82 {
83 if(rpc->afd >= 0)
84 close(rpc->afd);
85 if(rpc->afid != nil)
86 fsclose(rpc->afid);
87 free(rpc);
88 }
90 uint
91 auth_rpc(AuthRpc *rpc, char *verb, void *a, int na)
92 {
93 int l, n, type;
94 char *f[4];
96 l = strlen(verb);
97 if(na+l+1 > AuthRpcMax){
98 werrstr("rpc too big");
99 return ARtoobig;
102 memmove(rpc->obuf, verb, l);
103 rpc->obuf[l] = ' ';
104 memmove(rpc->obuf+l+1, a, na);
105 if((n=rpcwrite(rpc, rpc->obuf, l+1+na)) != l+1+na){
106 if(n >= 0)
107 werrstr("auth_rpc short write");
108 return ARrpcfailure;
111 if((n=rpcread(rpc, rpc->ibuf, AuthRpcMax)) < 0)
112 return ARrpcfailure;
113 rpc->ibuf[n] = '\0';
115 /*
116 * Set error string for good default behavior.
117 */
118 switch(type = classify(rpc->ibuf, n, rpc)){
119 default:
120 werrstr("unknown rpc type %d (bug in auth_rpc.c)", type);
121 break;
122 case ARok:
123 break;
124 case ARrpcfailure:
125 break;
126 case ARerror:
127 if(rpc->narg == 0)
128 werrstr("unspecified rpc error");
129 else
130 werrstr("%s", rpc->arg);
131 break;
132 case ARneedkey:
133 werrstr("needkey %s", rpc->arg);
134 break;
135 case ARbadkey:
136 if(getfields(rpc->arg, f, nelem(f), 0, "\n") < 2)
137 werrstr("badkey %s", rpc->arg);
138 else
139 werrstr("badkey %s", f[1]);
140 break;
141 case ARphase:
142 werrstr("phase error %s", rpc->arg);
143 break;
145 return type;