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 grouping byte-arrays combinators
6 accessors math.parser fry assocs namespaces continuations
10 TUPLE: passwd user-name password uid gid gecos dir shell ;
12 HOOK: new-passwd os ( -- passwd )
13 HOOK: passwd>new-passwd os ( passwd -- new-passwd )
17 M: unix new-passwd ( -- passwd )
20 M: unix passwd>new-passwd ( passwd -- seq )
23 [ passwd-pw_name >>user-name ]
24 [ passwd-pw_passwd >>password ]
25 [ passwd-pw_uid >>uid ]
26 [ passwd-pw_gid >>gid ]
27 [ passwd-pw_gecos >>gecos ]
28 [ passwd-pw_dir >>dir ]
29 [ passwd-pw_shell >>shell ]
32 : with-pwent ( quot -- )
33 [ endpwent ] [ ] cleanup ; inline
37 : all-users ( -- seq )
39 [ getpwent dup ] [ passwd>new-passwd ] [ drop ] produce
44 : <user-cache> ( -- assoc )
45 all-users [ [ uid>> ] keep ] H{ } map>assoc ;
47 : with-user-cache ( quot -- )
48 [ <user-cache> user-cache ] dip with-variable ; inline
50 GENERIC: user-passwd ( obj -- passwd/f )
52 M: integer user-passwd ( id -- passwd/f )
54 [ at ] [ getpwuid [ passwd>new-passwd ] [ f ] if* ] if* ;
56 M: string user-passwd ( string -- passwd/f )
57 getpwnam dup [ passwd>new-passwd ] when ;
59 : user-name ( id -- string )
61 [ nip user-name>> ] [ number>string ] if* ;
63 : user-id ( string -- id )
66 : real-user-id ( -- id )
69 : real-user-name ( -- string )
70 real-user-id user-name ; inline
72 : effective-user-id ( -- id )
75 : effective-user-name ( -- string )
76 effective-user-id user-name ; inline
78 GENERIC: set-real-user ( string/id -- )
80 GENERIC: set-effective-user ( string/id -- )
82 : with-real-user ( string/id quot -- )
83 '[ _ set-real-user @ ]
84 real-user-id '[ _ set-real-user ]
87 : with-effective-user ( string/id quot -- )
88 '[ _ set-effective-user @ ]
89 effective-user-id '[ _ set-effective-user ]
94 : (set-real-user) ( id -- )
95 setuid io-error ; inline
97 : (set-effective-user) ( id -- )
98 seteuid io-error ; inline
102 M: string set-real-user ( string -- )
103 user-id (set-real-user) ;
105 M: integer set-real-user ( id -- )
108 M: integer set-effective-user ( id -- )
109 (set-effective-user) ;
111 M: string set-effective-user ( string -- )
112 user-id (set-effective-user) ;
115 { [ dup bsd? ] [ drop "unix.users.bsd" require ] }
116 { [ dup linux? ] [ drop ] }