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