+ if (gid == (gid_t) -1)
+ gid = file_stats.st_gid;
+
+ if (uid == (uid_t) -1)
+ uid = file_stats.st_uid;
+ }
+#endif
+
+#if CHOWN_MODIFIES_SYMLINK
+ {
+ /* Handle the case in which the system-supplied chown function
+ does *not* follow symlinks. Instead, it changes permissions
+ on the symlink itself. To work around that, we open the
+ file (but this can fail due to lack of read or write permission) and
+ use fchown on the resulting descriptor. */
+ int fd = open (file, O_RDONLY | O_NONBLOCK | O_NOCTTY);
+ if (fd < 0
+ && (fd = open (file, O_WRONLY | O_NONBLOCK | O_NOCTTY)) < 0)
+ return -1;
+ if (fchown (fd, uid, gid))
+ {
+ int saved_errno = errno;
+ close (fd);
+ errno = saved_errno;
+ return -1;
+ }
+ return close (fd);
+ }
+#else
+ return chown (file, uid, gid);
+#endif