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