build: ensure sys/select.h is included
[coreutils.git] / src / chown-core.c
blobd03d8b3963add4da363fa4f96b8f6186ad7d905c
1 /* chown-core.c -- core functions for changing ownership.
2 Copyright (C) 2000-2019 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Extracted from chown.c/chgrp.c and librarified by Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <pwd.h>
23 #include <grp.h>
25 #include "system.h"
26 #include "chown-core.h"
27 #include "error.h"
28 #include "ignore-value.h"
29 #include "root-dev-ino.h"
30 #include "xfts.h"
32 #define FTSENT_IS_DIRECTORY(E) \
33 ((E)->fts_info == FTS_D \
34 || (E)->fts_info == FTS_DC \
35 || (E)->fts_info == FTS_DP \
36 || (E)->fts_info == FTS_DNR)
38 enum RCH_status
40 /* we called fchown and close, and both succeeded */
41 RC_ok = 2,
43 /* required_uid and/or required_gid are specified, but don't match */
44 RC_excluded,
46 /* SAME_INODE check failed */
47 RC_inode_changed,
49 /* open/fchown isn't needed, isn't safe, or doesn't work due to
50 permissions problems; fall back on chown */
51 RC_do_ordinary_chown,
53 /* open, fstat, fchown, or close failed */
54 RC_error
57 extern void
58 chopt_init (struct Chown_option *chopt)
60 chopt->verbosity = V_off;
61 chopt->root_dev_ino = NULL;
62 chopt->affect_symlink_referent = true;
63 chopt->recurse = false;
64 chopt->force_silent = false;
65 chopt->user_name = NULL;
66 chopt->group_name = NULL;
69 extern void
70 chopt_free (struct Chown_option *chopt)
72 free (chopt->user_name);
73 free (chopt->group_name);
76 /* Convert the numeric group-id, GID, to a string stored in xmalloc'd memory,
77 and return it. If there's no corresponding group name, use the decimal
78 representation of the ID. */
80 extern char *
81 gid_to_name (gid_t gid)
83 char buf[INT_BUFSIZE_BOUND (intmax_t)];
84 struct group *grp = getgrgid (gid);
85 return xstrdup (grp ? grp->gr_name
86 : TYPE_SIGNED (gid_t) ? imaxtostr (gid, buf)
87 : umaxtostr (gid, buf));
90 /* Convert the numeric user-id, UID, to a string stored in xmalloc'd memory,
91 and return it. If there's no corresponding user name, use the decimal
92 representation of the ID. */
94 extern char *
95 uid_to_name (uid_t uid)
97 char buf[INT_BUFSIZE_BOUND (intmax_t)];
98 struct passwd *pwd = getpwuid (uid);
99 return xstrdup (pwd ? pwd->pw_name
100 : TYPE_SIGNED (uid_t) ? imaxtostr (uid, buf)
101 : umaxtostr (uid, buf));
104 /* Allocate a string representing USER and GROUP. */
106 static char *
107 user_group_str (char const *user, char const *group)
109 char *spec = NULL;
111 if (user)
113 if (group)
115 spec = xmalloc (strlen (user) + 1 + strlen (group) + 1);
116 stpcpy (stpcpy (stpcpy (spec, user), ":"), group);
118 else
120 spec = xstrdup (user);
123 else if (group)
125 spec = xstrdup (group);
128 return spec;
131 /* Tell the user how/if the user and group of FILE have been changed.
132 If USER is NULL, give the group-oriented messages.
133 CHANGED describes what (if anything) has happened. */
135 static void
136 describe_change (const char *file, enum Change_status changed,
137 char const *old_user, char const *old_group,
138 char const *user, char const *group)
140 const char *fmt;
141 char *old_spec;
142 char *spec;
144 if (changed == CH_NOT_APPLIED)
146 printf (_("neither symbolic link %s nor referent has been changed\n"),
147 quoteaf (file));
148 return;
151 spec = user_group_str (user, group);
152 old_spec = user_group_str (user ? old_user : NULL, group ? old_group : NULL);
154 switch (changed)
156 case CH_SUCCEEDED:
157 fmt = (user ? _("changed ownership of %s from %s to %s\n")
158 : group ? _("changed group of %s from %s to %s\n")
159 : _("no change to ownership of %s\n"));
160 break;
161 case CH_FAILED:
162 if (old_spec)
164 fmt = (user ? _("failed to change ownership of %s from %s to %s\n")
165 : group ? _("failed to change group of %s from %s to %s\n")
166 : _("failed to change ownership of %s\n"));
168 else
170 fmt = (user ? _("failed to change ownership of %s to %s\n")
171 : group ? _("failed to change group of %s to %s\n")
172 : _("failed to change ownership of %s\n"));
173 free (old_spec);
174 old_spec = spec;
175 spec = NULL;
177 break;
178 case CH_NO_CHANGE_REQUESTED:
179 fmt = (user ? _("ownership of %s retained as %s\n")
180 : group ? _("group of %s retained as %s\n")
181 : _("ownership of %s retained\n"));
182 break;
183 default:
184 abort ();
187 printf (fmt, quoteaf (file), old_spec, spec);
189 free (old_spec);
190 free (spec);
193 /* Change the owner and/or group of the FILE to UID and/or GID (safely)
194 only if REQUIRED_UID and REQUIRED_GID match the owner and group IDs
195 of FILE. ORIG_ST must be the result of 'stat'ing FILE.
197 The 'safely' part above means that we can't simply use chown(2),
198 since FILE might be replaced with some other file between the time
199 of the preceding stat/lstat and this chown call. So here we open
200 FILE and do everything else via the resulting file descriptor.
201 We first call fstat and verify that the dev/inode match those from
202 the preceding stat call, and only then, if appropriate (given the
203 required_uid and required_gid constraints) do we call fchown.
205 Return RC_do_ordinary_chown if we can't open FILE, or if FILE is a
206 special file that might have undesirable side effects when opening.
207 In this case the caller can use the less-safe ordinary chown.
209 Return one of the RCH_status values. */
211 static enum RCH_status
212 restricted_chown (int cwd_fd, char const *file,
213 struct stat const *orig_st,
214 uid_t uid, gid_t gid,
215 uid_t required_uid, gid_t required_gid)
217 enum RCH_status status = RC_ok;
218 struct stat st;
219 int open_flags = O_NONBLOCK | O_NOCTTY;
220 int fd;
222 if (required_uid == (uid_t) -1 && required_gid == (gid_t) -1)
223 return RC_do_ordinary_chown;
225 if (! S_ISREG (orig_st->st_mode))
227 if (S_ISDIR (orig_st->st_mode))
228 open_flags |= O_DIRECTORY;
229 else
230 return RC_do_ordinary_chown;
233 fd = openat (cwd_fd, file, O_RDONLY | open_flags);
234 if (! (0 <= fd
235 || (errno == EACCES && S_ISREG (orig_st->st_mode)
236 && 0 <= (fd = openat (cwd_fd, file, O_WRONLY | open_flags)))))
237 return (errno == EACCES ? RC_do_ordinary_chown : RC_error);
239 if (fstat (fd, &st) != 0)
240 status = RC_error;
241 else if (! SAME_INODE (*orig_st, st))
242 status = RC_inode_changed;
243 else if ((required_uid == (uid_t) -1 || required_uid == st.st_uid)
244 && (required_gid == (gid_t) -1 || required_gid == st.st_gid))
246 if (fchown (fd, uid, gid) == 0)
248 status = (close (fd) == 0
249 ? RC_ok : RC_error);
250 return status;
252 else
254 status = RC_error;
258 int saved_errno = errno;
259 close (fd);
260 errno = saved_errno;
261 return status;
264 /* Change the owner and/or group of the file specified by FTS and ENT
265 to UID and/or GID as appropriate.
266 If REQUIRED_UID is not -1, then skip files with any other user ID.
267 If REQUIRED_GID is not -1, then skip files with any other group ID.
268 CHOPT specifies additional options.
269 Return true if successful. */
270 static bool
271 change_file_owner (FTS *fts, FTSENT *ent,
272 uid_t uid, gid_t gid,
273 uid_t required_uid, gid_t required_gid,
274 struct Chown_option const *chopt)
276 char const *file_full_name = ent->fts_path;
277 char const *file = ent->fts_accpath;
278 struct stat const *file_stats;
279 struct stat stat_buf;
280 bool ok = true;
281 bool do_chown;
282 bool symlink_changed = true;
284 switch (ent->fts_info)
286 case FTS_D:
287 if (chopt->recurse)
289 if (ROOT_DEV_INO_CHECK (chopt->root_dev_ino, ent->fts_statp))
291 /* This happens e.g., with "chown -R --preserve-root 0 /"
292 and with "chown -RH --preserve-root 0 symlink-to-root". */
293 ROOT_DEV_INO_WARN (file_full_name);
294 /* Tell fts not to traverse into this hierarchy. */
295 fts_set (fts, ent, FTS_SKIP);
296 /* Ensure that we do not process "/" on the second visit. */
297 ignore_value (fts_read (fts));
298 return false;
300 return true;
302 break;
304 case FTS_DP:
305 if (! chopt->recurse)
306 return true;
307 break;
309 case FTS_NS:
310 /* For a top-level file or directory, this FTS_NS (stat failed)
311 indicator is determined at the time of the initial fts_open call.
312 With programs like chmod, chown, and chgrp, that modify
313 permissions, it is possible that the file in question is
314 accessible when control reaches this point. So, if this is
315 the first time we've seen the FTS_NS for this file, tell
316 fts_read to stat it "again". */
317 if (ent->fts_level == 0 && ent->fts_number == 0)
319 ent->fts_number = 1;
320 fts_set (fts, ent, FTS_AGAIN);
321 return true;
323 if (! chopt->force_silent)
324 error (0, ent->fts_errno, _("cannot access %s"),
325 quoteaf (file_full_name));
326 ok = false;
327 break;
329 case FTS_ERR:
330 if (! chopt->force_silent)
331 error (0, ent->fts_errno, "%s", quotef (file_full_name));
332 ok = false;
333 break;
335 case FTS_DNR:
336 if (! chopt->force_silent)
337 error (0, ent->fts_errno, _("cannot read directory %s"),
338 quoteaf (file_full_name));
339 ok = false;
340 break;
342 case FTS_DC: /* directory that causes cycles */
343 if (cycle_warning_required (fts, ent))
345 emit_cycle_warning (file_full_name);
346 return false;
348 break;
350 default:
351 break;
354 if (!ok)
356 do_chown = false;
357 file_stats = NULL;
359 else if (required_uid == (uid_t) -1 && required_gid == (gid_t) -1
360 && chopt->verbosity == V_off
361 && ! chopt->root_dev_ino
362 && ! chopt->affect_symlink_referent)
364 do_chown = true;
365 file_stats = ent->fts_statp;
367 else
369 file_stats = ent->fts_statp;
371 /* If this is a symlink and we're dereferencing them,
372 stat it to get info on the referent. */
373 if (chopt->affect_symlink_referent && S_ISLNK (file_stats->st_mode))
375 if (fstatat (fts->fts_cwd_fd, file, &stat_buf, 0) != 0)
377 if (! chopt->force_silent)
378 error (0, errno, _("cannot dereference %s"),
379 quoteaf (file_full_name));
380 ok = false;
383 file_stats = &stat_buf;
386 do_chown = (ok
387 && (required_uid == (uid_t) -1
388 || required_uid == file_stats->st_uid)
389 && (required_gid == (gid_t) -1
390 || required_gid == file_stats->st_gid));
393 /* This happens when chown -LR --preserve-root encounters a symlink-to-/. */
394 if (ok
395 && FTSENT_IS_DIRECTORY (ent)
396 && ROOT_DEV_INO_CHECK (chopt->root_dev_ino, file_stats))
398 ROOT_DEV_INO_WARN (file_full_name);
399 return false;
402 if (do_chown)
404 if ( ! chopt->affect_symlink_referent)
406 ok = (lchownat (fts->fts_cwd_fd, file, uid, gid) == 0);
408 /* Ignore any error due to lack of support; POSIX requires
409 this behavior for top-level symbolic links with -h, and
410 implies that it's required for all symbolic links. */
411 if (!ok && errno == EOPNOTSUPP)
413 ok = true;
414 symlink_changed = false;
417 else
419 /* If possible, avoid a race condition with --from=O:G and without the
420 (-h) --no-dereference option. If fts's stat call determined
421 that the uid/gid of FILE matched the --from=O:G-selected
422 owner and group IDs, blindly using chown(2) here could lead
423 chown(1) or chgrp(1) mistakenly to dereference a *symlink*
424 to an arbitrary file that an attacker had moved into the
425 place of FILE during the window between the stat and
426 chown(2) calls. If FILE is a regular file or a directory
427 that can be opened, this race condition can be avoided safely. */
429 enum RCH_status err
430 = restricted_chown (fts->fts_cwd_fd, file, file_stats, uid, gid,
431 required_uid, required_gid);
432 switch (err)
434 case RC_ok:
435 break;
437 case RC_do_ordinary_chown:
438 ok = (chownat (fts->fts_cwd_fd, file, uid, gid) == 0);
439 break;
441 case RC_error:
442 ok = false;
443 break;
445 case RC_inode_changed:
446 /* FIXME: give a diagnostic in this case? */
447 case RC_excluded:
448 do_chown = false;
449 ok = false;
450 break;
452 default:
453 abort ();
457 /* On some systems (e.g., GNU/Linux 2.4.x),
458 the chown function resets the 'special' permission bits.
459 Do *not* restore those bits; doing so would open a window in
460 which a malicious user, M, could subvert a chown command run
461 by some other user and operating on files in a directory
462 where M has write access. */
464 if (do_chown && !ok && ! chopt->force_silent)
465 error (0, errno, (uid != (uid_t) -1
466 ? _("changing ownership of %s")
467 : _("changing group of %s")),
468 quoteaf (file_full_name));
471 if (chopt->verbosity != V_off)
473 bool changed =
474 ((do_chown && ok && symlink_changed)
475 && ! ((uid == (uid_t) -1 || uid == file_stats->st_uid)
476 && (gid == (gid_t) -1 || gid == file_stats->st_gid)));
478 if (changed || chopt->verbosity == V_high)
480 enum Change_status ch_status =
481 (!ok ? CH_FAILED
482 : !symlink_changed ? CH_NOT_APPLIED
483 : !changed ? CH_NO_CHANGE_REQUESTED
484 : CH_SUCCEEDED);
485 char *old_usr = file_stats ? uid_to_name (file_stats->st_uid) : NULL;
486 char *old_grp = file_stats ? gid_to_name (file_stats->st_gid) : NULL;
487 describe_change (file_full_name, ch_status,
488 old_usr, old_grp,
489 chopt->user_name, chopt->group_name);
490 free (old_usr);
491 free (old_grp);
495 if ( ! chopt->recurse)
496 fts_set (fts, ent, FTS_SKIP);
498 return ok;
501 /* Change the owner and/or group of the specified FILES.
502 BIT_FLAGS specifies how to treat each symlink-to-directory
503 that is encountered during a recursive traversal.
504 CHOPT specifies additional options.
505 If UID is not -1, then change the owner id of each file to UID.
506 If GID is not -1, then change the group id of each file to GID.
507 If REQUIRED_UID and/or REQUIRED_GID is not -1, then change only
508 files with user ID and group ID that match the non-(-1) value(s).
509 Return true if successful. */
510 extern bool
511 chown_files (char **files, int bit_flags,
512 uid_t uid, gid_t gid,
513 uid_t required_uid, gid_t required_gid,
514 struct Chown_option const *chopt)
516 bool ok = true;
518 /* Use lstat and stat only if they're needed. */
519 int stat_flags = ((required_uid != (uid_t) -1 || required_gid != (gid_t) -1
520 || chopt->affect_symlink_referent
521 || chopt->verbosity != V_off)
523 : FTS_NOSTAT);
525 FTS *fts = xfts_open (files, bit_flags | stat_flags, NULL);
527 while (1)
529 FTSENT *ent;
531 ent = fts_read (fts);
532 if (ent == NULL)
534 if (errno != 0)
536 /* FIXME: try to give a better message */
537 if (! chopt->force_silent)
538 error (0, errno, _("fts_read failed"));
539 ok = false;
541 break;
544 ok &= change_file_owner (fts, ent, uid, gid,
545 required_uid, required_gid, chopt);
548 if (fts_close (fts) != 0)
550 error (0, errno, _("fts_close failed"));
551 ok = false;
554 return ok;