global: convert indentation-TABs to spaces
[coreutils.git] / src / chown-core.c
blob7e5774ee1ed96b50449c23db16e17626bacc11e3
1 /* chown-core.c -- core functions for changing ownership.
2 Copyright (C) 2000, 2002-2009 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 <http://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 "quote.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 ATTRIBUTE_UNUSED)
72 /* Deliberately do not free chopt->user_name or ->group_name.
73 They're not always allocated. */
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 /* Tell the user how/if the user and group of FILE have been changed.
105 If USER is NULL, give the group-oriented messages.
106 CHANGED describes what (if anything) has happened. */
108 static void
109 describe_change (const char *file, enum Change_status changed,
110 char const *user, char const *group)
112 const char *fmt;
113 char const *spec;
114 char *spec_allocated = NULL;
116 if (changed == CH_NOT_APPLIED)
118 printf (_("neither symbolic link %s nor referent has been changed\n"),
119 quote (file));
120 return;
123 if (user)
125 if (group)
127 spec_allocated = xmalloc (strlen (user) + 1 + strlen (group) + 1);
128 stpcpy (stpcpy (stpcpy (spec_allocated, user), ":"), group);
129 spec = spec_allocated;
131 else
133 spec = user;
136 else
138 spec = group;
141 switch (changed)
143 case CH_SUCCEEDED:
144 fmt = (user ? _("changed ownership of %s to %s\n")
145 : group ? _("changed group of %s to %s\n")
146 : _("no change to ownership of %s\n"));
147 break;
148 case CH_FAILED:
149 fmt = (user ? _("failed to change ownership of %s to %s\n")
150 : group ? _("failed to change group of %s to %s\n")
151 : _("failed to change ownership of %s\n"));
152 break;
153 case CH_NO_CHANGE_REQUESTED:
154 fmt = (user ? _("ownership of %s retained as %s\n")
155 : group ? _("group of %s retained as %s\n")
156 : _("ownership of %s retained\n"));
157 break;
158 default:
159 abort ();
162 printf (fmt, quote (file), spec);
164 free (spec_allocated);
167 /* Change the owner and/or group of the FILE to UID and/or GID (safely)
168 only if REQUIRED_UID and REQUIRED_GID match the owner and group IDs
169 of FILE. ORIG_ST must be the result of `stat'ing FILE.
171 The `safely' part above means that we can't simply use chown(2),
172 since FILE might be replaced with some other file between the time
173 of the preceding stat/lstat and this chown call. So here we open
174 FILE and do everything else via the resulting file descriptor.
175 We first call fstat and verify that the dev/inode match those from
176 the preceding stat call, and only then, if appropriate (given the
177 required_uid and required_gid constraints) do we call fchown.
179 Return RC_do_ordinary_chown if we can't open FILE, or if FILE is a
180 special file that might have undesirable side effects when opening.
181 In this case the caller can use the less-safe ordinary chown.
183 Return one of the RCH_status values. */
185 static enum RCH_status
186 restricted_chown (int cwd_fd, char const *file,
187 struct stat const *orig_st,
188 uid_t uid, gid_t gid,
189 uid_t required_uid, gid_t required_gid)
191 enum RCH_status status = RC_ok;
192 struct stat st;
193 int open_flags = O_NONBLOCK | O_NOCTTY;
194 int fd;
196 if (required_uid == (uid_t) -1 && required_gid == (gid_t) -1)
197 return RC_do_ordinary_chown;
199 if (! S_ISREG (orig_st->st_mode))
201 if (S_ISDIR (orig_st->st_mode))
202 open_flags |= O_DIRECTORY;
203 else
204 return RC_do_ordinary_chown;
207 fd = openat (cwd_fd, file, O_RDONLY | open_flags);
208 if (! (0 <= fd
209 || (errno == EACCES && S_ISREG (orig_st->st_mode)
210 && 0 <= (fd = openat (cwd_fd, file, O_WRONLY | open_flags)))))
211 return (errno == EACCES ? RC_do_ordinary_chown : RC_error);
213 if (fstat (fd, &st) != 0)
214 status = RC_error;
215 else if (! SAME_INODE (*orig_st, st))
216 status = RC_inode_changed;
217 else if ((required_uid == (uid_t) -1 || required_uid == st.st_uid)
218 && (required_gid == (gid_t) -1 || required_gid == st.st_gid))
220 if (fchown (fd, uid, gid) == 0)
222 status = (close (fd) == 0
223 ? RC_ok : RC_error);
224 return status;
226 else
228 status = RC_error;
232 { /* FIXME: remove these curly braces when we assume C99. */
233 int saved_errno = errno;
234 close (fd);
235 errno = saved_errno;
236 return status;
240 /* Change the owner and/or group of the file specified by FTS and ENT
241 to UID and/or GID as appropriate.
242 If REQUIRED_UID is not -1, then skip files with any other user ID.
243 If REQUIRED_GID is not -1, then skip files with any other group ID.
244 CHOPT specifies additional options.
245 Return true if successful. */
246 static bool
247 change_file_owner (FTS *fts, FTSENT *ent,
248 uid_t uid, gid_t gid,
249 uid_t required_uid, gid_t required_gid,
250 struct Chown_option const *chopt)
252 char const *file_full_name = ent->fts_path;
253 char const *file = ent->fts_accpath;
254 struct stat const *file_stats;
255 struct stat stat_buf;
256 bool ok = true;
257 bool do_chown;
258 bool symlink_changed = true;
260 switch (ent->fts_info)
262 case FTS_D:
263 if (chopt->recurse)
265 if (ROOT_DEV_INO_CHECK (chopt->root_dev_ino, ent->fts_statp))
267 /* This happens e.g., with "chown -R --preserve-root 0 /"
268 and with "chown -RH --preserve-root 0 symlink-to-root". */
269 ROOT_DEV_INO_WARN (file_full_name);
270 /* Tell fts not to traverse into this hierarchy. */
271 fts_set (fts, ent, FTS_SKIP);
272 /* Ensure that we do not process "/" on the second visit. */
273 ent = fts_read (fts);
274 return false;
276 return true;
278 break;
280 case FTS_DP:
281 if (! chopt->recurse)
282 return true;
283 break;
285 case FTS_NS:
286 /* For a top-level file or directory, this FTS_NS (stat failed)
287 indicator is determined at the time of the initial fts_open call.
288 With programs like chmod, chown, and chgrp, that modify
289 permissions, it is possible that the file in question is
290 accessible when control reaches this point. So, if this is
291 the first time we've seen the FTS_NS for this file, tell
292 fts_read to stat it "again". */
293 if (ent->fts_level == 0 && ent->fts_number == 0)
295 ent->fts_number = 1;
296 fts_set (fts, ent, FTS_AGAIN);
297 return true;
299 if (! chopt->force_silent)
300 error (0, ent->fts_errno, _("cannot access %s"),
301 quote (file_full_name));
302 ok = false;
303 break;
305 case FTS_ERR:
306 if (! chopt->force_silent)
307 error (0, ent->fts_errno, _("%s"), quote (file_full_name));
308 ok = false;
309 break;
311 case FTS_DNR:
312 if (! chopt->force_silent)
313 error (0, ent->fts_errno, _("cannot read directory %s"),
314 quote (file_full_name));
315 ok = false;
316 break;
318 default:
319 break;
322 if (!ok)
324 do_chown = false;
325 file_stats = NULL;
327 else if (required_uid == (uid_t) -1 && required_gid == (gid_t) -1
328 && chopt->verbosity == V_off
329 && ! chopt->root_dev_ino
330 && ! chopt->affect_symlink_referent)
332 do_chown = true;
333 file_stats = ent->fts_statp;
335 else
337 file_stats = ent->fts_statp;
339 /* If this is a symlink and we're dereferencing them,
340 stat it to get info on the referent. */
341 if (chopt->affect_symlink_referent && S_ISLNK (file_stats->st_mode))
343 if (fstatat (fts->fts_cwd_fd, file, &stat_buf, 0) != 0)
345 if (! chopt->force_silent)
346 error (0, errno, _("cannot dereference %s"),
347 quote (file_full_name));
348 ok = false;
351 file_stats = &stat_buf;
354 do_chown = (ok
355 && (required_uid == (uid_t) -1
356 || required_uid == file_stats->st_uid)
357 && (required_gid == (gid_t) -1
358 || required_gid == file_stats->st_gid));
361 /* This happens when chown -LR --preserve-root encounters a symlink-to-/. */
362 if (ok
363 && FTSENT_IS_DIRECTORY (ent)
364 && ROOT_DEV_INO_CHECK (chopt->root_dev_ino, file_stats))
366 ROOT_DEV_INO_WARN (file_full_name);
367 return false;
370 if (do_chown)
372 if ( ! chopt->affect_symlink_referent)
374 ok = (lchownat (fts->fts_cwd_fd, file, uid, gid) == 0);
376 /* Ignore any error due to lack of support; POSIX requires
377 this behavior for top-level symbolic links with -h, and
378 implies that it's required for all symbolic links. */
379 if (!ok && errno == EOPNOTSUPP)
381 ok = true;
382 symlink_changed = false;
385 else
387 /* If possible, avoid a race condition with --from=O:G and without the
388 (-h) --no-dereference option. If fts's stat call determined
389 that the uid/gid of FILE matched the --from=O:G-selected
390 owner and group IDs, blindly using chown(2) here could lead
391 chown(1) or chgrp(1) mistakenly to dereference a *symlink*
392 to an arbitrary file that an attacker had moved into the
393 place of FILE during the window between the stat and
394 chown(2) calls. If FILE is a regular file or a directory
395 that can be opened, this race condition can be avoided safely. */
397 enum RCH_status err
398 = restricted_chown (fts->fts_cwd_fd, file, file_stats, uid, gid,
399 required_uid, required_gid);
400 switch (err)
402 case RC_ok:
403 break;
405 case RC_do_ordinary_chown:
406 ok = (chownat (fts->fts_cwd_fd, file, uid, gid) == 0);
407 break;
409 case RC_error:
410 ok = false;
411 break;
413 case RC_inode_changed:
414 /* FIXME: give a diagnostic in this case? */
415 case RC_excluded:
416 do_chown = false;
417 ok = false;
418 break;
420 default:
421 abort ();
425 /* On some systems (e.g., GNU/Linux 2.4.x),
426 the chown function resets the `special' permission bits.
427 Do *not* restore those bits; doing so would open a window in
428 which a malicious user, M, could subvert a chown command run
429 by some other user and operating on files in a directory
430 where M has write access. */
432 if (do_chown && !ok && ! chopt->force_silent)
433 error (0, errno, (uid != (uid_t) -1
434 ? _("changing ownership of %s")
435 : _("changing group of %s")),
436 quote (file_full_name));
439 if (chopt->verbosity != V_off)
441 bool changed =
442 ((do_chown & ok & symlink_changed)
443 && ! ((uid == (uid_t) -1 || uid == file_stats->st_uid)
444 && (gid == (gid_t) -1 || gid == file_stats->st_gid)));
446 if (changed || chopt->verbosity == V_high)
448 enum Change_status ch_status =
449 (!ok ? CH_FAILED
450 : !symlink_changed ? CH_NOT_APPLIED
451 : !changed ? CH_NO_CHANGE_REQUESTED
452 : CH_SUCCEEDED);
453 describe_change (file_full_name, ch_status,
454 chopt->user_name, chopt->group_name);
458 if ( ! chopt->recurse)
459 fts_set (fts, ent, FTS_SKIP);
461 return ok;
464 /* Change the owner and/or group of the specified FILES.
465 BIT_FLAGS specifies how to treat each symlink-to-directory
466 that is encountered during a recursive traversal.
467 CHOPT specifies additional options.
468 If UID is not -1, then change the owner id of each file to UID.
469 If GID is not -1, then change the group id of each file to GID.
470 If REQUIRED_UID and/or REQUIRED_GID is not -1, then change only
471 files with user ID and group ID that match the non-(-1) value(s).
472 Return true if successful. */
473 extern bool
474 chown_files (char **files, int bit_flags,
475 uid_t uid, gid_t gid,
476 uid_t required_uid, gid_t required_gid,
477 struct Chown_option const *chopt)
479 bool ok = true;
481 /* Use lstat and stat only if they're needed. */
482 int stat_flags = ((required_uid != (uid_t) -1 || required_gid != (gid_t) -1
483 || chopt->affect_symlink_referent
484 || chopt->verbosity != V_off)
486 : FTS_NOSTAT);
488 FTS *fts = xfts_open (files, bit_flags | stat_flags, NULL);
490 while (1)
492 FTSENT *ent;
494 ent = fts_read (fts);
495 if (ent == NULL)
497 if (errno != 0)
499 /* FIXME: try to give a better message */
500 if (! chopt->force_silent)
501 error (0, errno, _("fts_read failed"));
502 ok = false;
504 break;
507 ok &= change_file_owner (fts, ent, uid, gid,
508 required_uid, required_gid, chopt);
511 /* Ignore failure, since the only way it can do so is in failing to
512 return to the original directory, and since we're about to exit,
513 that doesn't matter. */
514 fts_close (fts);
516 return ok;