]> granicus.if.org Git - shadow/blob - libmisc/copydir.c
* NEWS, libmisc/chowntty.c: Fix a race condition that could lead to
[shadow] / libmisc / copydir.c
1 /*
2  * Copyright (c) 1991 - 1994, Julianne Frances Haugh
3  * Copyright (c) 1996 - 2001, Marek Michałkiewicz
4  * Copyright (c) 2003 - 2006, Tomasz Kłoczko
5  * Copyright (c) 2007 - 2008, Nicolas François
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the copyright holders or contributors may not be used to
17  *    endorse or promote products derived from this software without
18  *    specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
24  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include <config.h>
34
35 #ident "$Id$"
36
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <sys/time.h>
40 #include <fcntl.h>
41 #include <stdio.h>
42 #include "prototypes.h"
43 #include "defines.h"
44 #ifdef WITH_SELINUX
45 #include <selinux/selinux.h>
46 #endif
47 static const char *src_orig;
48 static const char *dst_orig;
49
50 struct link_name {
51         dev_t ln_dev;
52         ino_t ln_ino;
53         int ln_count;
54         char *ln_name;
55         struct link_name *ln_next;
56 };
57 static struct link_name *links;
58
59 static int copy_entry (const char *src, const char *dst,
60                        long int uid, long int gid);
61 static int copy_dir (const char *src, const char *dst,
62                      const struct stat *statp, const struct timeval mt[],
63                      long int uid, long int gid);
64 #ifdef  S_IFLNK
65 static int copy_symlink (const char *src, const char *dst,
66                          const struct stat *statp, const struct timeval mt[],
67                          long int uid, long int gid);
68 #endif
69 static int copy_hardlink (const char *src, const char *dst,
70                           struct link_name *lp);
71 static int copy_special (const char *dst,
72                          const struct stat *statp, const struct timeval mt[],
73                          long int uid, long int gid);
74 static int copy_file (const char *src, const char *dst,
75                       const struct stat *statp, const struct timeval mt[],
76                       long int uid, long int gid);
77
78 #ifdef WITH_SELINUX
79 /*
80  * selinux_file_context - Set the security context before any file or
81  *                        directory creation.
82  *
83  *      selinux_file_context () should be called before any creation of file,
84  *      symlink, directory, ...
85  *
86  */
87 static int selinux_file_context (const char *dst_name)
88 {
89         static bool selinux_checked = false;
90         static bool selinux_enabled;
91         security_context_t scontext = NULL;
92
93         if (!selinux_checked) {
94                 selinux_enabled = is_selinux_enabled () > 0;
95                 selinux_checked = true;
96         }
97
98         if (selinux_enabled) {
99                 /* Get the default security context for this file */
100                 if (matchpathcon (dst_name, 0, &scontext) < 0) {
101                         if (security_getenforce () != 0) {
102                                 return 1;
103                         }
104                 }
105                 /* Set the security context for the next created file */
106                 if (setfscreatecon (scontext) < 0) {
107                         if (security_getenforce () != 0) {
108                                 return 1;
109                         }
110                 }
111                 freecon (scontext);
112         }
113         return 0;
114 }
115 #endif
116
117 /*
118  * remove_link - delete a link from the linked list
119  */
120 static void remove_link (struct link_name *ln)
121 {
122         struct link_name *lp;
123
124         if (links == ln) {
125                 links = ln->ln_next;
126                 free (ln->ln_name);
127                 free (ln);
128                 return;
129         }
130         for (lp = links; NULL !=lp; lp = lp->ln_next) {
131                 if (lp->ln_next == ln) {
132                         break;
133                 }
134         }
135
136         if (NULL == lp) {
137                 return;
138         }
139
140         lp->ln_next = lp->ln_next->ln_next;
141         free (ln->ln_name);
142         free (ln);
143 }
144
145 /*
146  * check_link - see if a file is really a link
147  */
148
149 static struct link_name *check_link (const char *name, const struct stat *sb)
150 {
151         struct link_name *lp;
152         size_t src_len;
153         size_t dst_len;
154         size_t name_len;
155         size_t len;
156
157         for (lp = links; lp; lp = lp->ln_next) {
158                 if ((lp->ln_dev == sb->st_dev) && (lp->ln_ino == sb->st_ino)) {
159                         return lp;
160                 }
161         }
162
163         if (sb->st_nlink == 1) {
164                 return NULL;
165         }
166
167         lp = (struct link_name *) xmalloc (sizeof *lp);
168         src_len = strlen (src_orig);
169         dst_len = strlen (dst_orig);
170         name_len = strlen (name);
171         lp->ln_dev = sb->st_dev;
172         lp->ln_ino = sb->st_ino;
173         lp->ln_count = sb->st_nlink;
174         len = name_len - src_len + dst_len + 1;
175         lp->ln_name = (char *) xmalloc (len);
176         snprintf (lp->ln_name, len, "%s%s", dst_orig, name + src_len);
177         lp->ln_next = links;
178         links = lp;
179
180         return NULL;
181 }
182
183 /*
184  * copy_tree - copy files in a directory tree
185  *
186  *      copy_tree() walks a directory tree and copies ordinary files
187  *      as it goes.
188  */
189 int copy_tree (const char *src_root, const char *dst_root,
190                long int uid, long int gid)
191 {
192         char src_name[1024];
193         char dst_name[1024];
194         int err = 0;
195         bool set_orig = false;
196         struct DIRECT *ent;
197         DIR *dir;
198
199         /*
200          * Make certain both directories exist.  This routine is called
201          * after the home directory is created, or recursively after the
202          * target is created.  It assumes the target directory exists.
203          */
204
205         if (   (access (src_root, F_OK) != 0)
206             || (access (dst_root, F_OK) != 0)) {
207                 return -1;
208         }
209
210         /*
211          * Open the source directory and read each entry.  Every file
212          * entry in the directory is copied with the UID and GID set
213          * to the provided values.  As an added security feature only
214          * regular files (and directories ...) are copied, and no file
215          * is made set-ID.
216          */
217         dir = opendir (src_root);
218         if (NULL == dir) {
219                 return -1;
220         }
221
222         if (src_orig == NULL) {
223                 src_orig = src_root;
224                 dst_orig = dst_root;
225                 set_orig = true;
226         }
227         while ((0 == err) && (ent = readdir (dir)) != NULL) {
228                 /*
229                  * Skip the "." and ".." entries
230                  */
231                 if ((strcmp (ent->d_name, ".") != 0) &&
232                     (strcmp (ent->d_name, "..") != 0)) {
233                         /*
234                          * Make sure the resulting source and destination
235                          * filenames will fit in their buffers.
236                          */
237                         if (   (strlen (src_root) + strlen (ent->d_name) + 2 >
238                                 sizeof src_name)
239                             || (strlen (dst_root) + strlen (ent->d_name) + 2 >
240                                 sizeof dst_name)) {
241                                 err = -1;
242                         } else {
243                                 /*
244                                  * Build the filename for both the source and
245                                  * the destination files.
246                                  */
247                                 snprintf (src_name, sizeof src_name, "%s/%s",
248                                           src_root, ent->d_name);
249                                 snprintf (dst_name, sizeof dst_name, "%s/%s",
250                                           dst_root, ent->d_name);
251
252                                 err = copy_entry (src_name, dst_name, uid, gid);
253                         }
254                 }
255         }
256         (void) closedir (dir);
257
258         if (set_orig) {
259                 src_orig = NULL;
260                 dst_orig = NULL;
261         }
262         return err;
263 }
264
265 /*
266  * copy_entry - copy the entry of a directory
267  *
268  *      Copy the entry src to dst.
269  *      Depending on the type of entry, this function will forward the
270  *      request to copy_dir(), copy_symlink(), copy_hardlink(),
271  *      copy_special(), or copy_file().
272  *
273  *      The access and modification time will not be modified.
274  *
275  *      The permissions will be set to uid/gid.
276  *
277  *      If uid (resp. gid) is equal to -1, the user (resp. group) will
278  *      not be modified.
279  */
280 static int copy_entry (const char *src, const char *dst,
281                        long int uid, long int gid)
282 {
283         int err = 0;
284         struct stat sb;
285         struct link_name *lp;
286         struct timeval mt[2];
287
288         if (LSTAT (src, &sb) == -1) {
289                 /* If we cannot stat the file, do not care. */
290         } else {
291 #ifdef HAVE_STRUCT_STAT_ST_ATIM
292                 mt[0].tv_sec  = sb.st_atim.tv_sec;
293                 mt[0].tv_usec = sb.st_atim.tv_nsec / 1000;
294 #else
295                 mt[0].tv_sec  = sb.st_atime;
296 #ifdef HAVE_STRUCT_STAT_ST_ATIMENSEC
297                 mt[0].tv_usec = sb.st_atimensec / 1000;
298 #else
299                 mt[0].tv_usec = 0;
300 #endif
301 #endif
302
303 #ifdef HAVE_STRUCT_STAT_ST_MTIM
304                 mt[1].tv_sec  = sb.st_mtim.tv_sec;
305                 mt[1].tv_usec = sb.st_mtim.tv_nsec / 1000;
306 #else
307                 mt[1].tv_sec  = sb.st_mtime;
308 #ifdef HAVE_STRUCT_STAT_ST_MTIMENSEC
309                 mt[1].tv_usec = sb.st_mtimensec / 1000;
310 #else
311                 mt[1].tv_usec = 0;
312 #endif
313 #endif
314
315                 if (S_ISDIR (sb.st_mode)) {
316                         err = copy_dir (src, dst, &sb, mt, uid, gid);
317                 }
318
319 #ifdef  S_IFLNK
320                 /*
321                  * Copy any symbolic links
322                  */
323
324                 else if (S_ISLNK (sb.st_mode)) {
325                         err = copy_symlink (src, dst, &sb, mt, uid, gid);
326                 }
327 #endif
328
329                 /*
330                  * See if this is a previously copied link
331                  */
332
333                 else if ((lp = check_link (src, &sb)) != NULL) {
334                         err = copy_hardlink (src, dst, lp);
335                 }
336
337                 /*
338                  * Deal with FIFOs and special files.  The user really
339                  * shouldn't have any of these, but it seems like it
340                  * would be nice to copy everything ...
341                  */
342
343                 else if (!S_ISREG (sb.st_mode)) {
344                         err = copy_special (dst, &sb, mt, uid, gid);
345                 }
346
347                 /*
348                  * Create the new file and copy the contents.  The new
349                  * file will be owned by the provided UID and GID values.
350                  */
351
352                 else {
353                         err = copy_file (src, dst, &sb, mt, uid, gid);
354                 }
355         }
356
357         return err;
358 }
359
360 /*
361  * copy_dir - copy a directory
362  *
363  *      Copy a directory (recursively) from src to dst.
364  *
365  *      statp, mt, uid, gid are used to set the access and modification and the
366  *      access rights.
367  *
368  *      Return 0 on success, -1 on error.
369  */
370 static int copy_dir (const char *src, const char *dst,
371                      const struct stat *statp, const struct timeval mt[],
372                      long int uid, long int gid)
373 {
374         int err = 0;
375
376         /*
377          * Create a new target directory, make it owned by
378          * the user and then recursively copy that directory.
379          */
380
381 #ifdef WITH_SELINUX
382         selinux_file_context (dst);
383 #endif
384         if (   (mkdir (dst, statp->st_mode) != 0)
385             || (chown (dst,
386                        (uid == - 1) ? statp->st_uid : (uid_t) uid,
387                        (gid == - 1) ? statp->st_gid : (gid_t) gid) != 0)
388             || (chmod (dst, statp->st_mode) != 0)
389             || (copy_tree (src, dst, uid, gid) != 0)
390             || (utimes (dst, mt) != 0)) {
391                 err = -1;
392         }
393
394         return err;
395 }
396
397 #ifdef  S_IFLNK
398 /*
399  * copy_symlink - copy a symlink
400  *
401  *      Copy a symlink from src to dst.
402  *
403  *      statp, mt, uid, gid are used to set the access and modification and the
404  *      access rights.
405  *
406  *      Return 0 on success, -1 on error.
407  */
408 static int copy_symlink (const char *src, const char *dst,
409                          const struct stat *statp, const struct timeval mt[],
410                          long int uid, long int gid)
411 {
412         char oldlink[1024];
413         char dummy[1024];
414         int len;
415         int err = 0;
416
417         /*
418          * Get the name of the file which the link points
419          * to.  If that name begins with the original
420          * source directory name, that part of the link
421          * name will be replaced with the original
422          * destination directory name.
423          */
424
425         len = readlink (src, oldlink, sizeof (oldlink) - 1);
426         if (len < 0) {
427                 return -1;
428         }
429         oldlink[len] = '\0';    /* readlink() does not NUL-terminate */
430         if (strncmp (oldlink, src_orig, strlen (src_orig)) == 0) {
431                 snprintf (dummy, sizeof dummy, "%s%s",
432                           dst_orig,
433                           oldlink + strlen (src_orig));
434                 strcpy (oldlink, dummy);
435         }
436 #ifdef WITH_SELINUX
437         selinux_file_context (dst);
438 #endif
439         if (   (symlink (oldlink, dst) != 0)
440             || (lchown (dst,
441                         (uid == -1) ? statp->st_uid : (uid_t) uid,
442                         (gid == -1) ? statp->st_gid : (gid_t) gid) != 0)) {
443                 return -1;
444         }
445
446 #ifdef HAVE_LUTIMES
447         /* 2007-10-18: We don't care about
448          *  exit status of lutimes because
449          *  it returns ENOSYS on many system
450          *  - not implemented
451          */
452         lutimes (dst, mt);
453 #endif
454
455         return err;
456 }
457 #endif
458
459 /*
460  * copy_hardlink - copy a hardlink
461  *
462  *      Copy a hardlink from src to dst.
463  *
464  *      Return 0 on success, -1 on error.
465  */
466 static int copy_hardlink (const char *src, const char *dst,
467                           struct link_name *lp)
468 {
469         /* TODO: selinux needed? */
470
471         if (link (lp->ln_name, dst) != 0) {
472                 return -1;
473         }
474         if (unlink (src) != 0) {
475                 return -1;
476         }
477
478         /* If the file could be unlinked, decrement the links counter,
479          * and delete the file if it was the last reference */
480         lp->ln_count--;
481         if (lp->ln_count <= 0) {
482                 remove_link (lp);
483         }
484
485         return 0;
486 }
487
488 /*
489  * copy_special - copy a special file
490  *
491  *      Copy a special file from src to dst.
492  *
493  *      statp, mt, uid, gid are used to set the access and modification and the
494  *      access rights.
495  *
496  *      Return 0 on success, -1 on error.
497  */
498 static int copy_special (const char *dst,
499                          const struct stat *statp, const struct timeval mt[],
500                          long int uid, long int gid)
501 {
502         int err = 0;
503
504 #ifdef WITH_SELINUX
505         selinux_file_context (dst);
506 #endif
507
508         if (   (mknod (dst, statp->st_mode & ~07777, statp->st_rdev) != 0)
509             || (chown (dst,
510                        (uid == -1) ? statp->st_uid : (uid_t) uid,
511                        (gid == -1) ? statp->st_gid : (gid_t) gid) != 0)
512             || (chmod (dst, statp->st_mode & 07777) != 0)
513             || (utimes (dst, mt) != 0)) {
514                 err = -1;
515         }
516
517         return err;
518 }
519
520 /*
521  * copy_file - copy a file
522  *
523  *      Copy a file from src to dst.
524  *
525  *      statp, mt, uid, gid are used to set the access and modification and the
526  *      access rights.
527  *
528  *      Return 0 on success, -1 on error.
529  */
530 static int copy_file (const char *src, const char *dst,
531                       const struct stat *statp, const struct timeval mt[],
532                       long int uid, long int gid)
533 {
534         int err = 0;
535         int ifd;
536         int ofd;
537         char buf[1024];
538         ssize_t cnt;
539
540         ifd = open (src, O_RDONLY);
541         if (ifd < 0) {
542                 return -1;
543         }
544 #ifdef WITH_SELINUX
545         selinux_file_context (dst);
546 #endif
547         ofd = open (dst, O_WRONLY | O_CREAT | O_TRUNC, 0);
548         if (   (ofd < 0)
549             || (chown (dst,
550                        (uid == -1) ? statp->st_uid : (uid_t) uid,
551                        (gid == -1) ? statp->st_gid : (gid_t) gid) != 0)
552             || (chmod (dst, statp->st_mode & 07777) != 0)) {
553                 (void) close (ifd);
554                 return -1;
555         }
556
557         while ((cnt = read (ifd, buf, sizeof buf)) > 0) {
558                 if (write (ofd, buf, (size_t)cnt) != cnt) {
559                         return -1;
560                 }
561         }
562
563         (void) close (ifd);
564
565 #ifdef HAVE_FUTIMES
566         if (futimes (ofd, mt) != 0) {
567                 return -1;
568         }
569 #endif
570
571         if (close (ofd) != 0) {
572                 return -1;
573         }
574
575 #ifndef HAVE_FUTIMES
576         if (utimes(dst, mt) != 0) {
577                 return -1;
578         }
579 #endif
580
581         return err;
582 }
583
584 /*
585  * remove_tree - delete a directory tree
586  *
587  *      remove_tree() walks a directory tree and deletes all the files
588  *      and directories.
589  *      At the end, it deletes the root directory itself.
590  */
591
592 int remove_tree (const char *root)
593 {
594         char new_name[1024];
595         int err = 0;
596         struct DIRECT *ent;
597         struct stat sb;
598         DIR *dir;
599
600         /*
601          * Make certain the directory exists.
602          */
603
604         if (access (root, F_OK) != 0) {
605                 return -1;
606         }
607
608         /*
609          * Open the source directory and read each entry.  Every file
610          * entry in the directory is copied with the UID and GID set
611          * to the provided values.  As an added security feature only
612          * regular files (and directories ...) are copied, and no file
613          * is made set-ID.
614          */
615         dir = opendir (root);
616         if (NULL == dir) {
617                 return -1;
618         }
619
620         while ((ent = readdir (dir))) {
621
622                 /*
623                  * Skip the "." and ".." entries
624                  */
625
626                 if (strcmp (ent->d_name, ".") == 0 ||
627                     strcmp (ent->d_name, "..") == 0) {
628                         continue;
629                 }
630
631                 /*
632                  * Make the filename for the current entry.
633                  */
634
635                 if (strlen (root) + strlen (ent->d_name) + 2 > sizeof new_name) {
636                         err = -1;
637                         break;
638                 }
639                 snprintf (new_name, sizeof new_name, "%s/%s", root,
640                           ent->d_name);
641                 if (LSTAT (new_name, &sb) == -1) {
642                         continue;
643                 }
644
645                 if (S_ISDIR (sb.st_mode)) {
646                         /*
647                          * Recursively delete this directory.
648                          */
649                         if (remove_tree (new_name) != 0) {
650                                 err = -1;
651                                 break;
652                         }
653                 } else {
654                         /*
655                          * Delete the file.
656                          */
657                         if (unlink (new_name) != 0) {
658                                 err = -1;
659                                 break;
660                         }
661                 }
662         }
663         (void) closedir (dir);
664
665         if (0 == err) {
666                 if (rmdir (root) != 0) {
667                         err = -1;
668                 }
669         }
670
671         return err;
672 }
673