chiark / gitweb /
Fix problems with primary-dir
[chiark-utils.git] / sync-accounts / sync-accounts
1 #!/usr/bin/perl
2 # $Id: sync-accounts,v 1.17 2001-03-06 18:35:09 ian Exp $
3 #
4 # Copyright (C)1999-2000 Ian Jackson <ian@davenant.greenend.org.uk>
5 # Copyright (C)2000-2001 nCipher Corporation Ltd
6 #
7 #  This is free software; you can redistribute it and/or modify it under
8 #  the terms of the GNU General Public License as published by the Free
9 #  Software Foundation; either version 2, or (at your option) any later
10 #  version.
11 #
12 #  This is distributed in the hope that it will be useful, but WITHOUT
13 #  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 #  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 #  for more details.
16 #
17 #  You should already have a copy of the GNU General Public License.
18 #  If not, write to the Free Software Foundation, Inc., 59 Temple
19 #  Place - Suite 330, Boston, MA 02111-1307, USA.
20 #
21 # usage: sync-accounts [-n] [-C<config-file>] [<host> ...]
22 # options:
23 #   -n     do not really do anything
24 #   -C     alternative config file (default is /etc/sync-accounts)
25 #   -q     display accounts synched, not synched, etc.
26 # if no host(s) specified, does all
27 # host(s) may not be specified with -q
28 #
29 # The config file consists of directives, one per line.  Leading and
30 # trailing whitespace, blank lines and lines starting # are ignored.
31 #
32 # Some config file directives apply globally and should appear first:
33 #
34 #  lockpasswd link <suffix/filename>
35 #  lockgroup link <suffix/filename>
36 #      Specifies the lockfile suffix or pathname to use when editing
37 #      the passwd and group files.  The value is a suffix if it does
38 #      not start with `/'.  If set to /dev/null no locking is done.
39 #
40 #  lockpasswd runvia <program>
41 #  lockgroup runvia <program>
42 #      Lock by reinvoking ourselves via a program as EDITOR.
43 #      (<program> would typically be vipw or vigr.)
44 #
45 #  lockpasswd none
46 #  lockgroup none
47 #      Do not lock.
48 #
49 #  logfile <filename>
50 #      Append log messages to <filename> instead of stdout.
51 #      Errors still go to stderr.
52 #
53 #  localformat bsd|std
54 #      Specifies the local password file is in the relevant format:
55 #      `std' is the standard V7 password file (with a SysV- style
56 #      /etc/shadow if one is detected at run-time); `bsd' is the weird
57 #      BSD4.4 master.passwd format, and should be used only with
58 #      `lockpasswd runvia vipw'.  The default is `std'.
59 #
60 # Some config file directives set options which may be different at
61 # different points in the file.  The most-recently-seen value is used
62 # at each point:
63 #
64 #  uidmin <min>
65 #  uidmax <max>
66 #  homebase <pathname>
67 #      When an account is to be created, a uid/gid will be chosen
68 #      which is one higher than the highest currently in use (except
69 #      that ids outside the range <min>-<max> are ignored and will
70 #      never be used).  The default home directory location is
71 #      <pathname>/<username>.
72 #
73 #  sameuid
74 #  nosameuid
75 #      Specifies whether uids are supposed to match.  The default is
76 #      nosameuid.  When sameuid is on, it is an error for the uid or
77 #      gid of a local account not to match the corresponding remote
78 #      account, and new local accounts will get the remote accounts'
79 #      ids.
80 #
81 #  usergroups
82 #  nousergroups
83 #  defaultgid <gid>
84 #      Specifies whether local accounts are supposed to have
85 #      corresponding groups, or all be part of a particular group.  If
86 #      usergroups is set, when a new account is created, the
87 #      corresponding per-user group will be created as well, and
88 #      per-user groups are created for existing accounts if necessary
89 #      (if account creation is enabled).  If the gid or group name for
90 #      a per-user group is already taken for a different group name or
91 #      gid this will be logged, and processing of that account will be
92 #      inhibited, but it is not a fatal error.  If defaultgid is used,
93 #      then newly-created accounts will be made a part of that group,
94 #      and the groups of existing accounts will be left alone.  If
95 #      nousergroups is specified then no new accounts can be created,
96 #      and existing accounts' groups will be left alone.  The default
97 #      is `usergroups'.
98 #
99 #  createuser
100 #  createuser <commandname>
101 #  nocreateuser
102 #      Specifies whether accounts found on the remote host should be
103 #      created if necessary, and what command to run to do the
104 #      creation (eg, setup of home directory).  The default is
105 #      nocreateuser.  If createuser is specified without a commandname
106 #      then sync-accounts-createuser is used.  The command is found on
107 #      the PATH if necessary.  Either sameuid, or both uidmin and
108 #      uidmax, must be specified, if accounts are to be created.
109 #
110 #      The command (which will be run with sh -c) must at least create
111 #      the new account's home directory.  The passwd and group entries
112 #      will not have been set up.  The following environment variables
113 #      will be set, giving details about the account to be created:
114 #        SYNCUSER_CREATE_USER
115 #        SYNCUSER_CREATE_UID
116 #        SYNCUSER_CREATE_GID
117 #        SYNCUSER_CREATE_COMMENT
118 #        SYNCUSER_CREATE_HOME
119 #        SYNCUSER_CREATE_SHELL
120 #      If it chooses, the script may modify the password entry which
121 #      will be added to the system, by outputting a replacement
122 #      password file entry.  (The password field of that is ignored.)
123 #      If the script outputs a line which does not contain a : then
124 #      the account will not be created after all.
125 #
126 #  group <glob-pattern>
127 #  nogroup <glob-pattern>
128 #      Specifies that the membership of the local groups specified
129 #      should be adjusted or not adjusted whenever account data for a
130 #      particular user is copied, so that the account will be a member
131 #      of the affected group locally iff it is a member of the same
132 #      group on the remote host.  The most recently-encountered
133 #      glob-pattern for a particular group takes effect.  The default
134 #      is `nogroups *'.
135 #
136 #  defaultshell <pathname>
137 #      If, when creating an account, the remote account's shell is not
138 #      available on the local system, this value will be used.  The
139 #      default is /bin/sh.
140 #
141 # Some config file directives are per-host, and should appear before
142 # any directives which actually modify accounts:
143 #
144 #  host <shorthostname>
145 #      Starts a host's section.  This resets the per-host parameters
146 #      to the defaults.  The shorthostname need not be the host's
147 #      official name in any sense.  If sync-accounts is invoked with
148 #      host names on the command line they are compared with the
149 #      shorthostnames.
150 #
151 #  getpasswd <command>
152 #  getgroup <command>
153 #      Commands to run on the local host to get the passwd, shadow and
154 #      group data for the host in question.  getpasswd must be
155 #      specified if user data is to be transferred; getgroup must be
156 #      specified if group data is to be transferred.
157 #
158 #  getshadow <command>
159 #      Specifies that shadow file data is to be used (by default,
160 #      password information is found from the output of getpasswd).
161 #      The command should emit shadow data in the format specified by
162 #      shadow(5) on Linux.  getshadow should not be specified without
163 #      getpasswd.
164 #
165 #  remoteformat std|bsd
166 #      Specifies the format of the output of `getpasswd'.  `std' is
167 #      standard V7 passwd file format (optionally augmented by the use
168 #      of a shadow file fetched with getshadow).  `bsd' is the weird
169 #      BSD4.4 master.passwd format (and getshadow should not normally
170 #      be used with `remoteformat bsd').  The default is `std'.
171 #
172 # Some configuration file directives specify that account data is to
173 # transferred from the current host.  They should appear as the last
174 # thing(s) in a host section:
175 #
176 #  user <username> [remote=<remoteusername>]
177 #      Specifies that account data should be copied for local user
178 #      <username> from the remote account <remoteusername> (assumed to
179 #      be the same as <username> if not specified).  The account
180 #      password, comment field, and shell will be copied
181 #      unconditionally.  If sameuid is specified the uid will be
182 #      checked.
183 #
184 #  users <ruidmin>-<ruidmax>
185 #      Specifies that all remote users whose uid is in the given range
186 #      are to be copied to corresponding local user accounts.
187 #
188 #  nouser <username>
189 #      Specifies that data for <username> is _not_ to be copied, even
190 #      if subsequent user or users directives suggest that it should
191 #      be.
192 #
193 #   (A note is made when a `user', `users' or `nouser' directive is
194 #   encountered for a particular account, and no subsequent directives
195 #   for that account will take effect.)
196 #
197 #  addhere
198 #      This directive has no effect on `sync-accounts'.  However, it
199 #      is used as a placeholder by `grab-account': new accounts for
200 #      creation are inserted just before `addhere'.
201 #
202 # Finally, the config file must finish with:
203
204 #  end
205
206 use POSIX;
207
208 $configfile= '/etc/sync-accounts';
209 $def_createuser= 'sync-accounts-createuser';
210 $ch_homebase= '/home';
211 $ch_defaultshell= '/bin/sh';
212 $defaultgid= -1; # -1 => usergroups; -2 => nousergroups
213 @groupglobs= [ '.*', 0 ];
214 regroupglobs();
215
216 $file{'passwd','std'}= 'passwd';
217 $file{'shadow','std'}= 'shadow';
218 $file{'group','std'}= 'group';
219
220 $file{'passwd','bsd'}= 'master.passwd';
221 $file{'shadow','bsd'}= 'shadow-non-existent';
222 $file{'group','bsd'}= 'group';
223
224 @fields_pw_std= qw(USER PW UID GID COMMENT HOME SHELL);
225 @fields_pw_bsd= qw(USER PW UID GID CLASS CHANGE EXPIRE COMMENT HOME SHELL);
226 fields_fmt('PW','std');
227 fields('GR',qw(GROUP PW GID USERS));
228 fields('SP',qw(USER PW DAYSCHGD DAYSFIX DAYSEXP DAYSWARN DAYSEXPDIS DAYSDISD RESERVED));
229 # The name field had better always be field 0 !
230
231 END {
232     foreach $x (@unlocks) {
233         ($fn, $style, $arg) = @$x;
234         &{ "unlock_$style" } ( $fn,$arg );
235     }
236 }
237
238 sub fields {
239     my ($pfx,@l) = @_;
240     my ($i, $v, $vn);
241     foreach $v (@l) { $vn= "${pfx}_$v"; $$vn = $i++; }
242     $vn= "${pfx}_fields"; $$vn= $i;
243 }
244
245 sub fields_fmt ($$) {
246     my ($pfx,$fmt) = @_;
247     my ($vn);
248     $vn= "fields_pw_$fmt";
249     die "unknown format $fmt\n" unless defined @$vn;
250     fields($pfx,@$vn);
251     $vn= "${pfx}_format";
252     $$vn= $fmt;
253 }
254
255 sub newentry {
256     my ($pfx,$name,@field_val_list) = @_;
257     my (@rv, $vn, $fn, $v, $i);
258     @rv= ();
259     $vn= "${pfx}_fields";
260     for ($i=0; $i<$$vn; $i++) { $rv[$i]= ''; }
261     die "@field_val_list ?" if @field_val_list % 2;
262     $rv[0] = $name;
263     while (@field_val_list) {
264         ($fn,$v,@field_val_list) = @field_val_list;
265         $vn= "${pfx}_$fn";
266 #print STDERR ">$fn|$v|$vn|$$vn<\n";
267         $rv[$$vn]= $v;
268     }
269     return @rv;
270 }
271
272 $|=1;
273 $cdays= int(time/86400);
274
275 @envs_createuser= qw(USER UID GID COMMENT HOME SHELL);
276
277 if (@ARGV == 1 && length $ENV{'SYNC_ACCOUNTS_RUNVIA_INFO'}) {
278     @na= map {
279         s/\%([0-9a-f][0-9a-f])/ pack("C", hex $1) /ge;
280         $_;
281     } split(/\:/, $ENV{'SYNC_ACCOUNTS_RUNVIA_INFO'});
282     delete $ENV{'SYNC_ACCOUNTS_RUNVIA_INFO'};
283     $ta= shift @na;
284     $ENV{"SYNC_ACCOUNTS_RUNVIA_LOCKEDGOT_$ta"} = $ARGV[0];
285     @ARGV= @na;
286 }
287
288 @orgargv= @ARGV;
289
290 while ($ARGV[0] =~ m/^-/) {
291     $_= shift @ARGV;
292     last if m/^--$/;
293     if (m/^-C/) {
294         $configfile= $';
295     } elsif (m/^-n$/) {
296         $no_act= 1;
297         $display= 0;
298     } elsif (m/^-q$/) {
299         $no_act= 1;
300         $display= 1;
301     } else {
302         die "unknown option $_\n";
303     }
304 }
305
306 die "hosts must not be specified with -q\n" if @ARGV && $display;
307
308 for $h (@ARGV) { $wanthost{$h}= 1; }    
309
310 open CF,"< $configfile" or die "$configfile: $!";
311
312 sub fetchfile (\%$) {
313     my ($ary_ref,$get_str) = @_;
314
315     undef %$ary_ref;
316     open G,"$get_str" or die "$get_str: $!";
317     while (<G>) {
318         chomp;
319         m/^([^:]+)\:/ or die "$ch_name: $get_str:$.: $_ ?\n";
320         $ary_ref->{$1}= [ split(/\:/,$_,-1) ];
321     }
322     close G; $? and die "$ch_name: $get_str: exit code $?\n";
323 }
324
325 sub lockstyle_ ($$) {
326     my ($fn,$lock) = @_;
327
328     die "$configfile:$.: locking mechanism for $fn not".
329         " defined (use lockpasswd/lockgroup)\n";
330 }
331
332 sub abslock (@) {
333     my ($fn,$lock) = @_;
334
335     $fn= "/etc/$fn";
336     $lock= "$fn$lock" unless $lock =~ m,^/,;
337     return ($fn,$lock);
338 }
339
340 sub lock_none ($$) { return (abslock(@_))[0]; }
341 sub unlock_none ($$) { }
342
343 sub lock_link ($$) {
344     my ($fn,$lock) = abslock(@_);
345     link $fn,$lock or die "cannot lock $fn by creating $lock: $!\n";
346     return $fn;
347 }
348 sub unlock_link ($$) {
349     my ($fn,$lock) = abslock(@_);
350     unlink $lock or warn "unable to unlock by removing $lock: $!\n";
351 }
352
353 sub lock_runvia ($$) {
354     my ($fn,$lock) = @_;
355     my ($evn);
356     $evn= "SYNC_ACCOUNTS_RUNVIA_LOCKEDGOT_$fn";
357     return $ENV{$evn} if exists $ENV{$evn};
358
359     @na= map {
360         s/\W/ sprintf("%%%02x", unpack("C", $&)) /ge;
361         $_;
362     } ($fn,@orgargv);
363     $ENV{'SYNC_ACCOUNTS_RUNVIA_INFO'}= join(":", @na);
364     $ENV{'EDITOR'}= $0;
365     delete $ENV{'VISUAL'};
366     exec $lock; die "cannot lock $fn by executing $lock: $!\n";
367 }
368 sub unlock_runvia ($$) { }
369
370 sub fetchownfile (\@$$$$) {
371     my ($ary_ref,$fn_str,$nfields,$style,$lock_arg) = @_;
372     my ($fn_use, $record, $fn_emsg);
373     $fn_emsg= $fn_str;
374     if (!$no_act) {
375         $fn_use= &{ "lock_$style" } ($fn_str, $lock_arg);
376         push @unlocks, [ $fn_str, $style, $lock_arg ];
377         $savebackto{$fn_str}= $fn_use;
378     } else {
379         $fn_use= $fn_emsg= "/etc/".$file{$fn_str,$PW_format};
380     }
381     open O,"$fn_use" or die "$fn_use ($fn_str): $!";
382     while (<O>) {
383         chomp;
384         $record= [ split(/\:/,$_,-1) ];
385         die "$fn_emsg:$.:wrong number of fields:\`$_'\n"
386             unless @$record == $nfields;
387         push @$ary_ref, $record;
388     }
389     close O or die "$fn_use ($fn_str): $!";
390 }
391
392 sub diag ($) {
393     print "$diagstr: $_[0]\n" or die $!;
394 }
395
396 sub regroupglobs () {
397     $nogroups= (@groupglobs == 1 &&
398                 $groupglobs[0]->[0] eq '.*' &&
399                 !$groupglobs[0]->[1]);
400     $ggfunc= "sub wantsyncgroup {\n  \$_= \$_[0];\n  return\n";
401     for $g (@groupglobs) { $ggfunc.= "    m/^$g->[0]\$/ ? $g->[1] :\n"; }
402     $ggfunc.= "    die;\n};\n1;\n";
403 #print STDERR "$ggfunc\n";
404     eval $ggfunc or die "$ggfunc // $@";
405 }
406
407 sub fetchown () {
408     if (!$own_fetchedpasswd) {
409 #print STDERR ">$PW_fields<\n";
410         fetchownfile(@ownpasswd,'passwd',
411                      $PW_fields, $ch_lockstyle_passwd, $ch_lock_passwd);
412         $shadowfile= $file{'shadow',$PW_format};
413         if (stat("/etc/$shadowfile")) {
414             $own_haveshadow= 1;
415             $own_fetchedshadow= 1;
416             fetchownfile(@ownshadow,'shadow',$SP_fields,'none','');
417         } elsif ($! == &ENOENT) {
418             $own_haveshadow= 0;
419         } else {
420             die "unable to check for /etc/$shadowfile: $!\n";
421         }
422         $own_fetchedpasswd= 1;
423     }
424     if (!$own_fetchedgroup) {
425         fetchownfile(@owngroup,'group',$GR_fields,
426                      $ch_lockstyle_group, $ch_lock_group);
427         $own_fetchedgroup= 1;
428     }   
429 #print STDERR "fetchown() -> $#ownpasswd $#owngroup\n";
430 }
431
432 sub checkuid ($$) {
433     my ($useuid,$foruser) = @_;
434     for $e (@ownpasswd) {
435         if ($e->[$PW_USER] ne $foruser && $e->[$PW_UID] == $useuid) {
436             diag("uid clash with $e->[$PW_USER] (uid $e->[$PW_UID])");
437             return 0;
438         }
439     }
440     return 1;
441 }
442
443 sub copyfield ($$$$) {
444     my ($file,$entry,$field,$value) = @_;
445     eval "\$ary_ref= \\\@own$file; 1;" or die $@;
446 #print STDERR "copyfield($file,$entry,$field,$value)\n";
447     for $e (@$ary_ref) {
448 #print STDERR "copyfield($file,$entry,$field,$value) $e->[0] $e->[field] ".join(':',@$e)."\n";
449         next unless $e->[0] eq $entry;
450         next if $e->[$field] eq $value;
451         $e->[$field]= $value;
452         eval "\$modified$file= 1; 1;" or die $@;
453     }
454 }
455
456 sub fetchpasswd () {
457     return if $ch_fetchedpasswd;
458     die "$configfile:$.: getpasswd not specified for host $ch_name\n"
459         unless length $ch_getpasswd;
460     undef %remshadow;
461     fetchfile(%rempasswd,"$ch_getpasswd |");
462     if (length $ch_getshadow) {
463         fetchfile(%remshadow,"$ch_getshadow |");
464         for $k (keys %rempasswd) {
465             $rempasswd{$k}->[$REM_PW]= 'xx' unless length $rempasswd{$k}->[$REM_PW];
466         }
467         for $k (keys %remshadow) {
468             next unless exists $rempasswd{$k};
469             $rempasswd{$k}->[$REM_PW]= $remshadow{$k}->[$SP_PW];
470         }
471     }
472     $ch_fetchedpasswd= 1;
473 }
474
475 sub fetchgroup () {
476     return if $ch_fetchedgroup;
477     die "$configfile:$.: getgroup not specified for host $ch_name\n"
478         unless length $ch_getgroup;
479     fetchfile(%remgroup,"$ch_getgroup |");
480     $ch_fetchedgroup= 1;
481 }
482
483 sub syncusergroup ($$) {
484     my ($lu,$luid) = @_;
485
486     return 1 if $defaultgid != -1;
487 #print STDERR "syncusergroup($lu,$luid)\n";
488     $ugfound=0;
489     
490     for $e (@owngroup) {
491         $samename= $e->[$GR_GROUP] eq $lu;
492         $sameid= $e->[$GR_GID] eq $luid;
493         next unless $samename || $sameid;
494         if (!$samename || !$sameid) {
495             diag("local group $e->[$GR_GROUP] ($e->[$GR_GID]) mismatch vs.".
496                  " local user $lu ($luid)");
497             return 0;
498         }
499         if ($ugfound) {
500             diag("per-user group $lu ($luid) duplicated");
501             return 0;
502         }
503         $ugfound=1;
504     }
505
506     return 1 if $ugfound;
507
508     if (!length $opt_createuser) {
509         diag("account creation not enabled, not creating per-user group");
510         return 0;
511     }
512     push @owngroup, [ newentry('GR', $lu,
513                                'PW', 'x',
514                                'GID', $luid) ];
515     $modifiedgroup= 1;
516     return 1;
517 }
518
519 sub hosthead ($) {
520     my ($th) = @_;
521     return if $hostheaddone eq $th;
522     print "\n\n" or die $! if length $hostheaddone;
523     print "==== $th ====\n" or die $!;
524     $hostheaddone= $th;
525 }
526
527 sub syncuser ($$) {
528     my ($lu,$ru) = @_;
529     my ($vn);
530
531 #print STDERR "syncuser($lu,$ru)\n";
532     return if $doneuser{$lu}++;
533     next unless $ch_doinghost;
534     return if !length $ru;
535
536     fetchown();
537
538     if ($display) {
539         for $e (@ownpasswd) {
540             next unless $e->[$PW_USER] eq $lu;
541             hosthead("from $ch_name");
542             print ($lu eq $ru ? " $lu" : " $lu($ru)") or die $!;
543             print "<DUPLICATE>" if $displaydone{$lu}++;
544         }
545         return;
546     }
547     
548     $diagstr= "user $lu from $ch_name!$ru";
549
550 #print STDERR "syncuser($lu,$ru) doing\n";
551     fetchpasswd();
552
553     if (!$rempasswd{$ru}) { diag("no remote entry"); return; }
554     if (length $ch_getshadow && exists $remshadow{$ru} &&
555         length $remshadow{$ru}->[$SP_DAYSDISD]) {
556         diag("remote account disabled in shadow");
557         return;
558     }
559
560     if (!grep($_->[$PW_USER] eq $lu, @ownpasswd)) {
561         if (!length $opt_createuser) { diag("account creation not enabled"); return; }
562         if ($no_act) { diag("-n specified; not creating account"); return; }
563
564         if ($opt_sameuid) {
565             $useuid= $rempasswd{$ru}->[$REM_UID];
566             $usegid= $rempasswd{$ru}->[$REM_GID];
567         } else {
568             die "nousergroups specified, cannot create users\n" if $defaultgid==-2;
569             length $ch_uidmin or die "no uidmin specified, cannot create users\n";
570             length $ch_uidmax or die "no uidmax specified, cannot create users\n";
571             $ch_uidmin<$ch_uidmax or die "uidmin>=uidmax, cannot create users\n";
572         
573             $useuid= $ch_uidmin;
574             for $e ($defaultgid==-1 ? (@ownpasswd, @owngroup) : (@ownpasswd)) {
575                 $tuid= $e->[$PW_UID]; next if $tuid<$useuid || $tuid>$ch_uidmax;
576                 if ($tuid==$ch_uidmax) {
577                     diag("uid (or gid?) $ch_uidmax used, cannot create users");
578                     return;
579                 }
580                 $useuid= $tuid+1;
581             }
582             $usegid= $defaultgid==-1 ? $useuid : $defaultgid;
583         }
584         
585         @newpwent= newentry('PW', $lu,
586                             'PW', 'x',
587                             'UID', $useuid,
588                             'GID', $usegid,
589                             'COMMENT', $rempasswd{$ru}->[$REM_COMMENT],
590                             'HOME', "$ch_homebase/$lu",
591                             'SHELL', $ch_defaultshell);
592         
593         defined($c= open CU,"-|") or die $!;
594         if (!$c) {
595             @unlocks= ();
596             defined($c2= open STDIN,"-|") or die $!;
597             if (!$c2) {
598                 print STDOUT join(':',@newpwent),"\n" or die $!;
599                 exit 0;
600             }
601             for ($i=0; $i<@envs_createuser; $i++) {
602                 $vn= "PW_$envs_createuser[$i]";
603 #print STDERR ">$i|$vn|$$vn|$newpwent[$$vn]<\n";
604                 $ENV{"SYNCUSER_CREATE_$envs_createuser[$i]"}= $newpwent[$$vn];
605             }
606             exec $opt_createuser; die "$configfile:$.: ($lu): $opt_createuser: $!\n";
607         }
608         $newpwent= <CU>;
609         close CU; $? and die "$configfile:$.: ($lu): $opt_createuser: code $?\n";
610         chomp $newpwent;
611         if (length $newpwent) {
612             if ($newpwent !~ m/\:/) { diag("creation script demurred"); return; }
613             @newpwent= split(/\:/,$newpwent,-1);
614         }
615         die "$opt_createuser: bad result: \`".join(':',@newpwent)."\'\n"
616             if @newpwent != $PW_fields or $newpwent[$PW_USER] ne $lu;
617         checkuid($newpwent[$PW_UID],$lu) or return;
618         if ($own_haveshadow) {
619             push @ownshadow, [ newentry('SP', $lu,
620                                         'PW', 'x',
621                                         'DAYSCHGD', $cdays,
622                                         'DAYSFIX', 0,
623                                         'DAYSEXP', 99999,
624                                         'DAYSEXPDIS', 7) ];
625             $modifiedshadow= 1;
626         }
627         syncusergroup($lu,$newpwent[$PW_UID]) or return;
628         push @ownpasswd,[ @newpwent ];
629         $modifiedpasswd= 1;
630     }
631
632     for $e (@ownpasswd) {
633         next unless $e->[$PW_USER] eq $lu;
634         syncusergroup($lu,$e->[$PW_UID]) or return;
635     }
636
637     $ruid= $rempasswd{$ru}->[$REM_UID];
638     $rgid= $rempasswd{$ru}->[$REM_GID];
639     if ($opt_sameuid && checkuid($ruid,$lu)) {
640         for $e (@ownpasswd) {
641             next unless $e->[$PW_USER] eq $lu;
642             $luid= $e->[$PW_UID]; $lgid= $e->[$PW_GID];
643             die "$diagstr: local uid $luid, remote uid $ruid\n" if $luid ne $ruid;
644             die "$diagstr: local gid $lgid, remote gid $rgid\n" if $lgid ne $rgid;
645         }
646     }
647
648 #print STDERR "syncuser($lu,$ru) exists $own_haveshadow\n";
649     if ($own_haveshadow && grep($_->[$PW_USER] eq $lu, @ownshadow)) {
650 #print STDERR "syncuser($lu,$ru) shadow $rempasswd{$ru}->[$REM_PW]\n";
651         copyfield('shadow',$lu,$SP_PW, $rempasswd{$ru}->[$REM_PW]);
652     } else {
653 #print STDERR "syncuser($lu,$ru) passwd $rempasswd{$ru}->[$REM_PW]\n";
654         copyfield('passwd',$lu,$PW_PW, $rempasswd{$ru}->[$REM_PW]);
655     }
656     copyfield('passwd',$lu,$PW_COMMENT, $rempasswd{$ru}->[$REM_COMMENT]);
657
658     $newsh= $rempasswd{$ru}->[$REM_SHELL];
659     $oksh= $checkedshell{$newsh};
660     if (!length $oksh) { $checkedshell{$newsh}= $oksh= (-x $newsh) ? 1 : 0; }
661     copyfield('passwd',$lu,$PW_SHELL, $newsh) if $oksh;
662
663     if (!$nogroups) {
664         for $e (@owngroup) {
665             $tgroup= $e->[$GR_GROUP];
666 #print STDERR "syncuser($lu,$ru) group $tgroup\n";
667             next unless &wantsyncgroup($tgroup);
668 #print STDERR "syncuser($lu,$ru) group $tgroup yes\n";
669             fetchgroup();
670             if (!exists $remgroup{$tgroup}) {
671                 diag("group $tgroup: not on remote host");
672                 next;
673             }
674             $inremote= grep($_ eq $ru, split(/\,/,$remgroup{$tgroup}->[$GR_USERS]));
675             $cusers= $e->[$GR_USERS]; $inlocal= grep($_ eq $lu, split(/\,/,$cusers));
676             if ($inremote && !$inlocal) {
677                 $cusers.= ',' if length $cusers;
678                 $cusers.= $lu;
679             } elsif ($inlocal && !$inremote) {
680                 $cusers= join(',', grep($_ ne $lu, split(/\,/, $cusers)));
681             } else {
682                 next;
683             }
684             $e->[$GR_USERS]= $cusers;
685             $modifiedgroup= 1;
686         }
687     }
688 }
689
690 sub banner () {
691     return if $bannerdone;
692     print "\n" or die $!; system 'date'; $? and die $?;
693     $bannerdone= 1;
694 }
695
696 sub finish () {
697     for $h (keys %wanthost) {
698         die "host $h not in config file\n" if $wanthost{$h};
699     }
700
701     if ($display) {
702 #print STDERR "\n\nfinish display=$display pw=$pw\n\n";
703         for $e (@ownpasswd) {
704             $tu= $e->[$PW_USER];
705             $tuid= $e->[$PW_UID];
706             next if $displaydone{$tu};
707             $tpw= $e->[$PW_PW];
708 #print STDERR ">$tu|$tpw<\n";
709             for $e2 (@ownshadow) {
710                 next unless $e2->[$SP_USER] eq $tu;
711                 $tpw= $e2->[$SP_PW]; last;
712             }
713             $tpw= length($tpw)>=13 ? 1 : length($tpw) ? -1 : 0;
714             $head= ($tpw == 1 ? "unsynched" :
715                     $tpw == 0 ? "unsynched, passwordless" :
716                     "unsynched, no-logins").
717                     ($tuid < 100 ? " system account" : " normal user");
718             $unsynch_type{$head} .= " $e->[$PW_USER]";
719         }
720         foreach $head (sort keys %unsynch_type) {
721             hosthead($head);
722             print $unsynch_type{$head} or die $!;
723         }
724         print "\n\n" or die $!;
725         exit 0;
726     }
727     
728     umask 077;
729     for $file (qw(passwd shadow group)) {
730         $realfile= $file{$file,$PW_format};
731         eval "\$modified= \$modified$file; \$data_ref= \\\@own$file;".
732             " \$fetched= \$own_fetched$file; 1;" or die $@;
733         next if !$modified;
734         die $file unless $fetched;
735         banner();
736         if ($no_act) {
737             $newfileinst= "/etc/$realfile";
738             $newfile= "$realfile.new";
739         } else {
740             $newfileinst= $savebackto{$file};
741             $newfile= "$newfileinst.new";
742         }
743         open NF,"> $newfile" or die "$newfile: $!";
744         for $e (@$data_ref) {
745             print NF join(':',@$e),"\n" or die $!;
746         }
747         close NF or die $!;
748         system 'diff','-U0','--label',$realfile,$newfileinst,
749                             '--label',"$realfile.new",$newfile;
750         $?==256 or die $?;
751         if (!$no_act) {
752             (@stats= stat $newfileinst) or die "$file: $!";
753             chown $stats[4],$stats[5], $newfile or die $!;
754             chmod $stats[2] & 07777, $newfile or die $!;
755             rename $newfile, $newfileinst or die $!;
756         }
757     }
758     exit 0;
759 }
760
761 while (<CF>) {
762     chomp;
763     next if m/^\#/ || !m/\S/;
764     s/^\s*//; s/\s*$//;
765     finish() if m/^end$/;
766     if (m/^host\s+(\S+)$/) {
767         $ch_name= $1;
768         $ch_getpasswd= $ch_getgroup= $ch_getshadow= '';
769         $ch_fetchedpasswd= $ch_fetchedgroup;
770         if (!@ARGV) {
771             $ch_doinghost= 1;
772         } elsif (exists $wanthost{$ch_name}) {
773             $wanthost{$ch_name}= 0;
774             $ch_doinghost= 1;
775         } else {
776             $ch_doinghost= 0;
777         }
778         fields_fmt('REM','std');
779     } elsif (m/^(getpasswd|getshadow|getgroup)\s+(.*\S)$/) {
780         eval "\$ch_$1= \$2; 1;" or die $@;
781     } elsif (m/^(local|remote)format\s+(\w+)$/) {
782         fields_fmt($1 eq 'local' ? 'PW' :
783                    $1 eq 'remote' ? 'REM' : die,
784                    $2);
785     } elsif (m/^lock(passwd|group)\s+(runvia|link)\s+(\S+)$/) {
786         eval "\$ch_lock_$1= \$3; \$ch_lockstyle_$1= \$2; 1;" or die $@;
787     } elsif (m/^lock(passwd|group)\s+(none)$/) {
788         eval "\$ch_lockstyle_$1= \$2; 1;" or die $@;
789     } elsif (m,^(homebase|defaultshell)\s+(/\S+)$,) {
790         eval "\$ch_$1= \$2; 1;" or die $@;
791     } elsif (m/^(uidmin|uidmax)\s+(\d+)$/ && $2>0) {
792         eval "\$ch_$1= \$2; 1;" or die $@;
793     } elsif (m/^createuser$/) {
794         $opt_createuser= $def_createuser;
795     } elsif (m/^nocreateuser$/) {
796         $opt_createuser= '';
797     } elsif (m/^createuser\s+(\S+)$/) {
798         $opt_createuser= $1;
799     } elsif (m/^logfile\s+(.*\S)$/) {
800         if (!$no_act) {
801             open STDOUT,">> $1" or die "$1: $!"; $|=1;
802             $!=0; system 'date'; $? and die "date: $! $?\n";
803         } elsif (!$display) {
804             print "would log to $1\n" or die $!;
805         }
806     } elsif (m/^(no|)(sameuid)$/) {
807         eval "\$opt_$2= ".($1 eq 'no' ? 0 : 1)."; 1;" or die $@;
808     } elsif (m/^usergroups$/) {
809         $defaultgid= -1;
810     } elsif (m/^nousergroups$/) {
811         $defaultgid= -2;
812     } elsif (m/^defaultgid\s+(\d+)$/) {
813         $defaultgid= $1;
814     } elsif (m/^(no|)group\s+([-+.0-9a-zA-Z*?]+)$/) {
815         $yes= $1 eq 'no' ? 0 : 1;
816         $_= $2;
817         @groupglobs=() if $_ eq '*';
818         s/[-+._]/\\$1/g;
819         s/\*/\.\*/g;
820         s/\?/\./g;
821         unshift @groupglobs, [ $_, $yes ];
822         regroupglobs();
823     } elsif (m/^user\s+(\S+)$/) {
824         syncuser($1,$1);
825     } elsif (m/^user\s+(\S+)\s+remote\=(\S+)$/) {
826         syncuser($1,$2);
827     } elsif (m/^nouser\s+(\S+)$/) {
828         syncuser($1,'');
829     } elsif (m/^users\s+(\d+)\-(\d+)$/) {
830         $tmin= $1; $tmax= $2; $except= $3;
831         fetchpasswd();
832         for $k (keys %rempasswd) {
833             $tuid= $rempasswd{$k}->[2];
834             next if $tuid<$1 or $tuid>$2;
835             syncuser($k,$k);
836         }
837     } elsif (m/^addhere$/) {
838     } else {
839         die "$configfile:$.: unknown directive\n";
840     }
841 }
842
843 die "$configfile:$.: missing \`end', or read error\n";