1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: alien alien.c-types alien.strings io.encodings.utf8
4 io.backend.unix kernel math sequences splitting unix strings
5 combinators.short-circuit byte-arrays combinators qualified
6 accessors math.parser fry assocs namespaces continuations
7 unix.users unix.utilities ;
12 TUPLE: group id name passwd members ;
16 GENERIC: group-struct ( obj -- group )
20 : group-members ( group-struct -- seq )
21 group-gr_mem utf8 alien>strings ;
23 : (group-struct) ( id -- group-struct id group-struct byte-array length void* )
24 "group" <c-object> tuck 4096
25 [ <byte-array> ] keep f <void*> ;
27 M: integer group-struct ( id -- group )
28 (group-struct) getgrgid_r io-error ;
30 M: string group-struct ( string -- group )
31 (group-struct) getgrnam_r 0 = [ (io-error) ] unless ;
33 : group-struct>group ( group-struct -- group )
36 [ group-gr_name >>name ]
37 [ group-gr_passwd >>passwd ]
39 [ group-members >>members ]
44 : group-name ( id -- string )
48 group-struct group-gr_name
50 [ nip ] [ number>string ] if* ;
52 : group-id ( string -- id )
53 group-struct group-gr_gid ;
57 : >groups ( byte-array n -- groups )
58 [ 4 grouping:group ] dip head-slice [ *uint group-name ] map ;
60 : (user-groups) ( string -- seq )
61 #! first group is -1337, legacy unix code
62 -1337 NGROUPS_MAX [ 4 * <byte-array> ] keep
63 <int> [ getgrouplist io-error ] 2keep
64 [ 4 tail-slice ] [ *int 1- ] bi* >groups ;
68 GENERIC: user-groups ( string/id -- seq )
70 M: string user-groups ( string -- seq )
73 M: integer user-groups ( id -- seq )
74 username (user-groups) ;
76 : all-groups ( -- seq )
77 [ getgrent dup ] [ group-struct>group ] [ drop ] produce ;
79 : <group-cache> ( -- assoc )
80 all-groups [ [ id>> ] keep ] H{ } map>assoc ;
82 : with-group-cache ( quot -- )
83 [ <group-cache> group-cache ] dip with-variable ; inline
85 : real-group-id ( -- id )
88 : real-group-name ( -- string )
89 real-group-id group-name ; inline
91 : effective-group-id ( -- string )
94 : effective-group-name ( -- string )
95 effective-group-id group-name ; inline
97 GENERIC: set-real-group ( obj -- )
99 GENERIC: set-effective-group ( obj -- )
101 : with-real-group ( string/id quot -- )
102 '[ _ set-real-group @ ]
103 real-group-id '[ _ set-real-group ] [ ] cleanup ; inline
105 : with-effective-group ( string/id quot -- )
106 '[ _ set-effective-group @ ]
107 effective-group-id '[ _ set-effective-group ] [ ] cleanup ; inline
111 : (set-real-group) ( id -- )
112 setgid io-error ; inline
114 : (set-effective-group) ( id -- )
115 setegid io-error ; inline
119 M: string set-real-group ( string -- )
120 group-id (set-real-group) ;
122 M: integer set-real-group ( id -- )
125 M: integer set-effective-group ( id -- )
126 (set-effective-group) ;
128 M: string set-effective-group ( string -- )
129 group-id (set-effective-group) ;