xref: /plan9-contrib/sys/src/cmd/fossil/9auth.c (revision 5e96a66c77eb9140492ca53f857cbbf108e128ed)
1 #include "stdinc.h"
2 
3 #include "9.h"
4 
5 int
6 authRead(Fid* afid, void* data, int count)
7 {
8 	AuthInfo *ai;
9 	AuthRpc *rpc;
10 
11 	if((rpc = afid->rpc) == nil)
12 		return -1;
13 
14 	switch(auth_rpc(rpc, "read", nil, 0)){
15 	default:
16 		return -1;
17 	case ARdone:
18 		if((ai = auth_getinfo(rpc)) == nil)
19 			break;
20 		if(ai->cuid == nil || *ai->cuid == '\0'){
21 			auth_freeAI(ai);
22 			break;
23 		}
24 		assert(afid->cuname == nil);
25 		afid->cuname = vtStrDup(ai->cuid);
26 		auth_freeAI(ai);
27 		if(Dflag)
28 			fprint(2, "authRead cuname %s\n", afid->cuname);
29 		assert(afid->uid == nil);
30 		if((afid->uid = uidByUname(afid->cuname)) == nil)
31 			break;
32 		return 0;
33 	case ARok:
34 		if(count < rpc->narg)
35 			break;
36 		memmove(data, rpc->arg, rpc->narg);
37 		return rpc->narg;
38 	case ARphase:
39 		break;
40 	}
41 	return -1;
42 }
43 
44 int
45 authWrite(Fid* afid, void* data, int count)
46 {
47 	assert(afid->rpc != nil);
48 	if(auth_rpc(afid->rpc, "write", data, count) != ARok)
49 		return -1;
50 	return count;
51 }
52 
53 int
54 authCheck(Fcall* t, Fid* fid, Fs* fsys)
55 {
56 	Fid *afid;
57 	uchar buf[1];
58 
59 	/*
60 	 * Can't lookup with FidWlock here as there may be
61 	 * protocol to do. Use a separate lock to protect altering
62 	 * the auth information inside afid.
63 	 */
64 	if((afid = fidGet(fid->con, t->afid, 0)) == nil){
65 		/*
66 		 * If no authentication is asked for, allow
67 		 * "none" provided the connection has already
68 		 * been authenticatated.
69 		 */
70 		if(strcmp(fid->uname, unamenone) == 0 && fid->con->aok){
71 			if((fid->uid = uidByUname(fid->uname)) == nil)
72 				return 0;
73 			return 1;
74 		}
75 
76 		/*
77 		 * The console is allowed to attach without
78 		 * authentication.
79 		 */
80 		if(!fid->con->isconsole)
81 			return 0;
82 		if((fid->uid = uidByUname(fid->uname)) == nil)
83 			return 0;
84 		return 1;
85 	}
86 
87 	/*
88 	 * Check valid afid;
89 	 * check uname and aname match.
90 	 */
91 	if(!(afid->qid.type & QTAUTH)){
92 		fidPut(afid);
93 		return 0;
94 	}
95 	if(strcmp(afid->uname, fid->uname) != 0 || afid->fsys != fsys){
96 		fidPut(afid);
97 		return 0;
98 	}
99 
100 	vtLock(afid->alock);
101 	if(afid->cuname == nil){
102 		if(authRead(afid, buf, 0) != 0 || afid->cuname == nil){
103 			vtUnlock(afid->alock);
104 			fidPut(afid);
105 			return 0;
106 		}
107 	}
108 	vtUnlock(afid->alock);
109 
110 	assert(fid->uid == nil);
111 	if((fid->uid = uidByUname(afid->cuname)) == nil){
112 		fidPut(afid);
113 		return 0;
114 	}
115 
116 	vtMemFree(fid->uname);
117 	fid->uname = vtStrDup(afid->cuname);
118 	fidPut(afid);
119 
120 	/*
121 	 * Allow "none" once the connection has been authenticated.
122 	 */
123 	fid->con->aok = 1;
124 
125 	return 1;
126 }
127