re-mark 1.29b-2 as not yet uploaded (merge madness!)
[debian/tar] / src / xattrs.c
1 /* Support for extended attributes.
2
3    Copyright (C) 2006-2014, 2016 Free Software Foundation, Inc.
4
5    This file is part of GNU tar.
6
7    GNU tar is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    GNU tar is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20    Written by James Antill, on 2006-07-27.  */
21
22 #include <config.h>
23 #include <system.h>
24
25 #include <fnmatch.h>
26 #include <quotearg.h>
27
28 #include "common.h"
29
30 #include "xattr-at.h"
31 #include "selinux-at.h"
32
33 struct xattrs_mask_map
34 {
35   const char **masks;
36   size_t size;
37   size_t used;
38 };
39
40 /* list of fnmatch patterns */
41 static struct
42 {
43   /* lists of fnmatch patterns */
44   struct xattrs_mask_map incl;
45   struct xattrs_mask_map excl;
46 } xattrs_setup;
47
48 /* disable posix acls when problem found in gnulib script m4/acl.m4 */
49 #if ! USE_ACL
50 # undef HAVE_POSIX_ACLS
51 #endif
52
53 #ifdef HAVE_POSIX_ACLS
54 # include "acl.h"
55 # include <sys/acl.h>
56 #endif
57
58 #ifdef HAVE_POSIX_ACLS
59
60 /* acl-at wrappers, TODO: move to gnulib in future? */
61 static acl_t acl_get_file_at (int, const char *, acl_type_t);
62 static int acl_set_file_at (int, const char *, acl_type_t, acl_t);
63 static int file_has_acl_at (int, char const *, struct stat const *);
64 static int acl_delete_def_file_at (int, char const *);
65
66 /* acl_get_file_at */
67 #define AT_FUNC_NAME acl_get_file_at
68 #define AT_FUNC_RESULT acl_t
69 #define AT_FUNC_FAIL (acl_t)NULL
70 #define AT_FUNC_F1 acl_get_file
71 #define AT_FUNC_POST_FILE_PARAM_DECLS   , acl_type_t type
72 #define AT_FUNC_POST_FILE_ARGS          , type
73 #include "at-func.c"
74 #undef AT_FUNC_NAME
75 #undef AT_FUNC_F1
76 #undef AT_FUNC_RESULT
77 #undef AT_FUNC_FAIL
78 #undef AT_FUNC_POST_FILE_PARAM_DECLS
79 #undef AT_FUNC_POST_FILE_ARGS
80
81 /* acl_set_file_at */
82 #define AT_FUNC_NAME acl_set_file_at
83 #define AT_FUNC_F1 acl_set_file
84 #define AT_FUNC_POST_FILE_PARAM_DECLS   , acl_type_t type, acl_t acl
85 #define AT_FUNC_POST_FILE_ARGS          , type, acl
86 #include "at-func.c"
87 #undef AT_FUNC_NAME
88 #undef AT_FUNC_F1
89 #undef AT_FUNC_POST_FILE_PARAM_DECLS
90 #undef AT_FUNC_POST_FILE_ARGS
91
92 /* acl_delete_def_file_at */
93 #define AT_FUNC_NAME acl_delete_def_file_at
94 #define AT_FUNC_F1 acl_delete_def_file
95 #define AT_FUNC_POST_FILE_PARAM_DECLS
96 #define AT_FUNC_POST_FILE_ARGS
97 #include "at-func.c"
98 #undef AT_FUNC_NAME
99 #undef AT_FUNC_F1
100 #undef AT_FUNC_POST_FILE_PARAM_DECLS
101 #undef AT_FUNC_POST_FILE_ARGS
102
103 /* gnulib file_has_acl_at */
104 #define AT_FUNC_NAME file_has_acl_at
105 #define AT_FUNC_F1 file_has_acl
106 #define AT_FUNC_POST_FILE_PARAM_DECLS   , struct stat const *st
107 #define AT_FUNC_POST_FILE_ARGS          , st
108 #include "at-func.c"
109 #undef AT_FUNC_NAME
110 #undef AT_FUNC_F1
111 #undef AT_FUNC_POST_FILE_PARAM_DECLS
112 #undef AT_FUNC_POST_FILE_ARGS
113
114 /* convert unix permissions into an ACL ... needed due to "default" ACLs */
115 static acl_t
116 perms2acl (int perms)
117 {
118   char val[] = "user::---,group::---,other::---";
119   /*            0123456789 123456789 123456789 123456789 */
120
121   /* user */
122   if (perms & 0400)
123     val[6] = 'r';
124   if (perms & 0200)
125     val[7] = 'w';
126   if (perms & 0100)
127     val[8] = 'x';
128
129   /* group */
130   if (perms & 0040)
131     val[17] = 'r';
132   if (perms & 0020)
133     val[18] = 'w';
134   if (perms & 0010)
135     val[19] = 'x';
136
137   /* other */
138   if (perms & 0004)
139     val[28] = 'r';
140   if (perms & 0002)
141     val[29] = 'w';
142   if (perms & 0001)
143     val[30] = 'x';
144
145   return acl_from_text (val);
146 }
147
148 static char *
149 skip_to_ext_fields (char *ptr)
150 {
151   /* skip tag name (user/group/default/mask) */
152   ptr += strcspn (ptr, ":,\n");
153
154   if (*ptr != ':')
155     return ptr;
156   ++ptr;
157
158   ptr += strcspn (ptr, ":,\n"); /* skip user/group name */
159
160   if (*ptr != ':')
161     return ptr;
162   ++ptr;
163
164   ptr += strcspn (ptr, ":,\n"); /* skip perms */
165
166   return ptr;
167 }
168
169 /* The POSIX draft allows extra fields after the three main ones. Star
170    uses this to add a fourth field for user/group which is the numeric ID.
171    This function removes such extra fields by overwriting them with the
172    characters that follow. */
173 static char *
174 fixup_extra_acl_fields (char *ptr)
175 {
176   char *src = ptr;
177   char *dst = ptr;
178
179   while (*src)
180     {
181       const char *old = src;
182       size_t len = 0;
183
184       src = skip_to_ext_fields (src);
185       len = src - old;
186       if (old != dst)
187         memmove (dst, old, len);
188       dst += len;
189
190       if (*src == ':')          /* We have extra fields, skip them all */
191         src += strcspn (src, "\n,");
192
193       if ((*src == '\n') || (*src == ','))
194         *dst++ = *src++;        /* also done when dst == src, but that's ok */
195     }
196   if (src != dst)
197     *dst = 0;
198
199   return ptr;
200 }
201
202 /* Set the "system.posix_acl_access/system.posix_acl_default" extended
203    attribute.  Called only when acls_option > 0. */
204 static void
205 xattrs__acls_set (struct tar_stat_info const *st,
206                   char const *file_name, int type,
207                   char *ptr, size_t len, bool def)
208 {
209   acl_t acl;
210
211   if (ptr)
212     {
213       /* assert (strlen (ptr) == len); */
214       ptr = fixup_extra_acl_fields (ptr);
215       acl = acl_from_text (ptr);
216     }
217   else if (def)
218     {
219       /* No "default" IEEE 1003.1e ACL set for directory.  At this moment,
220          FILE_NAME may already have inherited default acls from parent
221          directory;  clean them up. */
222       if (acl_delete_def_file_at (chdir_fd, file_name))
223         WARNOPT (WARN_XATTR_WRITE,
224                 (0, errno,
225                  _("acl_delete_def_file_at: Cannot drop default POSIX ACLs "
226                    "for file '%s'"),
227                  file_name));
228       return;
229     }
230   else
231     acl = perms2acl (st->stat.st_mode);
232
233   if (!acl)
234     {
235       call_arg_warn ("acl_from_text", file_name);
236       return;
237     }
238
239   if (acl_set_file_at (chdir_fd, file_name, type, acl) == -1)
240     /* warn even if filesystem does not support acls */
241     WARNOPT (WARN_XATTR_WRITE,
242              (0, errno,
243               _ ("acl_set_file_at: Cannot set POSIX ACLs for file '%s'"),
244               file_name));
245
246   acl_free (acl);
247 }
248
249 static void
250 xattrs__acls_get_a (int parentfd, const char *file_name,
251                     struct tar_stat_info *st,
252                     char **ret_ptr, size_t * ret_len)
253 {
254   char *val = NULL;
255   ssize_t len;
256   acl_t acl;
257
258   if (!(acl = acl_get_file_at (parentfd, file_name, ACL_TYPE_ACCESS)))
259     {
260       if (errno != ENOTSUP)
261         call_arg_warn ("acl_get_file_at", file_name);
262       return;
263     }
264
265   val = acl_to_text (acl, &len);
266   acl_free (acl);
267
268   if (!val)
269     {
270       call_arg_warn ("acl_to_text", file_name);
271       return;
272     }
273
274   *ret_ptr = xstrdup (val);
275   *ret_len = len;
276
277   acl_free (val);
278 }
279
280 /* "system.posix_acl_default" */
281 static void
282 xattrs__acls_get_d (int parentfd, char const *file_name,
283                     struct tar_stat_info *st,
284                     char **ret_ptr, size_t * ret_len)
285 {
286   char *val = NULL;
287   ssize_t len;
288   acl_t acl;
289
290   if (!(acl = acl_get_file_at (parentfd, file_name, ACL_TYPE_DEFAULT)))
291     {
292       if (errno != ENOTSUP)
293         call_arg_warn ("acl_get_file_at", file_name);
294       return;
295     }
296
297   val = acl_to_text (acl, &len);
298   acl_free (acl);
299
300   if (!val)
301     {
302       call_arg_warn ("acl_to_text", file_name);
303       return;
304     }
305
306   *ret_ptr = xstrdup (val);
307   *ret_len = len;
308
309   acl_free (val);
310 }
311 #endif /* HAVE_POSIX_ACLS */
312
313 static void
314 acls_one_line (const char *prefix, char delim,
315                const char *aclstring, size_t len)
316 {
317   /* support both long and short text representation of posix acls */
318   struct obstack stk;
319   int pref_len = strlen (prefix);
320   const char *oldstring = aclstring;
321   int pos = 0;
322
323   if (!aclstring || !len)
324     return;
325
326   obstack_init (&stk);
327   while (pos <= len)
328     {
329       int move = strcspn (aclstring, ",\n");
330       if (!move)
331         break;
332
333       if (oldstring != aclstring)
334         obstack_1grow (&stk, delim);
335
336       obstack_grow (&stk, prefix, pref_len);
337       obstack_grow (&stk, aclstring, move);
338
339       aclstring += move + 1;
340     }
341
342   obstack_1grow (&stk, '\0');
343
344   fprintf (stdlis, "%s", (char *) obstack_finish (&stk));
345
346   obstack_free (&stk, NULL);
347 }
348
349 void
350 xattrs_acls_get (int parentfd, char const *file_name,
351                  struct tar_stat_info *st, int fd, int xisfile)
352 {
353   if (acls_option > 0)
354     {
355 #ifndef HAVE_POSIX_ACLS
356       static int done = 0;
357       if (!done)
358         WARN ((0, 0, _("POSIX ACL support is not available")));
359       done = 1;
360 #else
361       int err = file_has_acl_at (parentfd, file_name, &st->stat);
362       if (err == 0)
363         return;
364       if (err == -1)
365         {
366           call_arg_warn ("file_has_acl_at", file_name);
367           return;
368         }
369
370       xattrs__acls_get_a (parentfd, file_name, st,
371                           &st->acls_a_ptr, &st->acls_a_len);
372       if (!xisfile)
373         xattrs__acls_get_d (parentfd, file_name, st,
374                             &st->acls_d_ptr, &st->acls_d_len);
375 #endif
376     }
377 }
378
379 void
380 xattrs_acls_set (struct tar_stat_info const *st,
381                  char const *file_name, char typeflag)
382 {
383   if (acls_option > 0 && typeflag != SYMTYPE)
384     {
385 #ifndef HAVE_POSIX_ACLS
386       static int done = 0;
387       if (!done)
388         WARN ((0, 0, _("POSIX ACL support is not available")));
389       done = 1;
390 #else
391       xattrs__acls_set (st, file_name, ACL_TYPE_ACCESS,
392                         st->acls_a_ptr, st->acls_a_len, false);
393       if (typeflag == DIRTYPE || typeflag == GNUTYPE_DUMPDIR)
394         xattrs__acls_set (st, file_name, ACL_TYPE_DEFAULT,
395                           st->acls_d_ptr, st->acls_d_len, true);
396 #endif
397     }
398 }
399
400 static void
401 mask_map_realloc (struct xattrs_mask_map *map)
402 {
403   if (map->used == map->size)
404     {
405       if (map->size == 0)
406         map->size = 4;
407       map->masks = x2nrealloc (map->masks, &map->size, sizeof (map->masks[0]));
408     }
409 }
410
411 void
412 xattrs_mask_add (const char *mask, bool incl)
413 {
414   struct xattrs_mask_map *mask_map =
415     incl ? &xattrs_setup.incl : &xattrs_setup.excl;
416   /* ensure there is enough space */
417   mask_map_realloc (mask_map);
418   /* just assign pointers -- we silently expect that pointer "mask" is valid
419      through the whole program (pointer to argv array) */
420   mask_map->masks[mask_map->used++] = mask;
421 }
422
423 static void
424 clear_mask_map (struct xattrs_mask_map *mask_map)
425 {
426   if (mask_map->size)
427     free (mask_map->masks);
428 }
429
430 void
431 xattrs_clear_setup (void)
432 {
433   clear_mask_map (&xattrs_setup.incl);
434   clear_mask_map (&xattrs_setup.excl);
435 }
436
437 /* get all xattrs from file given by FILE_NAME or FD (when non-zero).  This
438    includes all the user.*, security.*, system.*, etc. available domains */
439 void
440 xattrs_xattrs_get (int parentfd, char const *file_name,
441                    struct tar_stat_info *st, int fd)
442 {
443   if (xattrs_option > 0)
444     {
445 #ifndef HAVE_XATTRS
446       static int done = 0;
447       if (!done)
448         WARN ((0, 0, _("XATTR support is not available")));
449       done = 1;
450 #else
451       static size_t xsz = 1024;
452       static char *xatrs = NULL;
453       ssize_t xret = -1;
454
455       if (!xatrs)
456         xatrs = x2nrealloc (xatrs, &xsz, 1);
457
458       while (((fd == 0) ?
459               ((xret =
460                 llistxattrat (parentfd, file_name, xatrs, xsz)) == -1) :
461               ((xret = flistxattr (fd, xatrs, xsz)) == -1))
462              && (errno == ERANGE))
463         {
464           xatrs = x2nrealloc (xatrs, &xsz, 1);
465         }
466
467       if (xret == -1)
468         call_arg_warn ((fd == 0) ? "llistxattrat" : "flistxattr", file_name);
469       else
470         {
471           const char *attr = xatrs;
472           static size_t asz = 1024;
473           static char *val = NULL;
474
475           if (!val)
476             val = x2nrealloc (val, &asz, 1);
477
478           while (xret > 0)
479             {
480               size_t len = strlen (attr);
481               ssize_t aret = 0;
482
483               /* Archive all xattrs during creation, decide at extraction time
484                * which ones are of interest/use for the target filesystem. */
485               while (((fd == 0)
486                       ? ((aret = lgetxattrat (parentfd, file_name, attr,
487                                               val, asz)) == -1)
488                       : ((aret = fgetxattr (fd, attr, val, asz)) == -1))
489                      && (errno == ERANGE))
490                 {
491                   val = x2nrealloc (val, &asz, 1);
492                 }
493
494               if (aret != -1)
495                 xheader_xattr_add (st, attr, val, aret);
496               else if (errno != ENOATTR)
497                 call_arg_warn ((fd == 0) ? "lgetxattrat"
498                                : "fgetxattr", file_name);
499
500               attr += len + 1;
501               xret -= len + 1;
502             }
503         }
504 #endif
505     }
506 }
507
508 #ifdef HAVE_XATTRS
509 static void
510 xattrs__fd_set (struct tar_stat_info const *st,
511                 char const *file_name, char typeflag,
512                 const char *attr, const char *ptr, size_t len)
513 {
514   if (ptr)
515     {
516       const char *sysname = "setxattrat";
517       int ret = -1;
518
519       if (typeflag != SYMTYPE)
520         ret = setxattrat (chdir_fd, file_name, attr, ptr, len, 0);
521       else
522         {
523           sysname = "lsetxattr";
524           ret = lsetxattrat (chdir_fd, file_name, attr, ptr, len, 0);
525         }
526
527       if (ret == -1)
528         WARNOPT (WARN_XATTR_WRITE,
529                  (0, errno,
530                   _("%s: Cannot set '%s' extended attribute for file '%s'"),
531                   sysname, attr, file_name));
532     }
533 }
534 #endif
535
536 /* lgetfileconat is called against FILE_NAME iff the FD parameter is set to
537    zero, otherwise the fgetfileconat is used against correct file descriptor */
538 void
539 xattrs_selinux_get (int parentfd, char const *file_name,
540                     struct tar_stat_info *st, int fd)
541 {
542   if (selinux_context_option > 0)
543     {
544 #if HAVE_SELINUX_SELINUX_H != 1
545       static int done = 0;
546       if (!done)
547         WARN ((0, 0, _("SELinux support is not available")));
548       done = 1;
549 #else
550       int result = fd ?
551                     fgetfilecon (fd, &st->cntx_name)
552                     : lgetfileconat (parentfd, file_name, &st->cntx_name);
553
554       if (result == -1 && errno != ENODATA && errno != ENOTSUP)
555         call_arg_warn (fd ? "fgetfilecon" : "lgetfileconat", file_name);
556 #endif
557     }
558 }
559
560 void
561 xattrs_selinux_set (struct tar_stat_info const *st,
562                     char const *file_name, char typeflag)
563 {
564   if (selinux_context_option > 0)
565     {
566 #if HAVE_SELINUX_SELINUX_H != 1
567       static int done = 0;
568       if (!done)
569         WARN ((0, 0, _("SELinux support is not available")));
570       done = 1;
571 #else
572       const char *sysname = "setfilecon";
573       int ret;
574
575       if (!st->cntx_name)
576         return;
577
578       if (typeflag != SYMTYPE)
579         {
580           ret = setfileconat (chdir_fd, file_name, st->cntx_name);
581           sysname = "setfileconat";
582         }
583       else
584         {
585           ret = lsetfileconat (chdir_fd, file_name, st->cntx_name);
586           sysname = "lsetfileconat";
587         }
588
589       if (ret == -1)
590         WARNOPT (WARN_XATTR_WRITE,
591                  (0, errno,
592                   _("%s: Cannot set SELinux context for file '%s'"),
593                   sysname, file_name));
594 #endif
595     }
596 }
597
598 static bool
599 xattrs_matches_mask (const char *kw, struct xattrs_mask_map *mm)
600 {
601   int i;
602
603   if (!mm->size)
604     return false;
605
606   for (i = 0; i < mm->used; i++)
607     if (fnmatch (mm->masks[i], kw, 0) == 0)
608       return true;
609
610   return false;
611 }
612
613 #define USER_DOT_PFX "user."
614
615 static bool
616 xattrs_kw_included (const char *kw, bool archiving)
617 {
618   if (xattrs_setup.incl.size)
619     return xattrs_matches_mask (kw, &xattrs_setup.incl);
620   else if (archiving)
621     return true;
622   else
623     return strncmp (kw, USER_DOT_PFX, sizeof (USER_DOT_PFX) - 1) == 0;
624 }
625
626 static bool
627 xattrs_kw_excluded (const char *kw, bool archiving)
628 {
629   return xattrs_setup.excl.size ?
630     xattrs_matches_mask (kw, &xattrs_setup.excl) : false;
631 }
632
633 /* Check whether the xattr with keyword KW should be discarded from list of
634    attributes that are going to be archived/excluded (set ARCHIVING=true for
635    archiving, false for excluding) */
636 static bool
637 xattrs_masked_out (const char *kw, bool archiving)
638 {
639   return xattrs_kw_included (kw, archiving) ?
640     xattrs_kw_excluded (kw, archiving) : true;
641 }
642
643 void
644 xattrs_xattrs_set (struct tar_stat_info const *st,
645                    char const *file_name, char typeflag, int later_run)
646 {
647   if (xattrs_option > 0)
648     {
649 #ifndef HAVE_XATTRS
650       static int done = 0;
651       if (!done)
652         WARN ((0, 0, _("XATTR support is not available")));
653       done = 1;
654 #else
655       size_t scan = 0;
656
657       if (!st->xattr_map_size)
658         return;
659
660       for (; scan < st->xattr_map_size; ++scan)
661         {
662           char *keyword = st->xattr_map[scan].xkey;
663           keyword += strlen ("SCHILY.xattr.");
664
665           /* TODO: this 'later_run' workaround is temporary solution -> once
666              capabilities should become fully supported by it's API and there
667              should exist something like xattrs_capabilities_set() call.
668              For a regular files: all extended attributes are restored during
669              the first run except 'security.capability' which is restored in
670              'later_run == 1'.  */
671           if (typeflag == REGTYPE
672               && later_run == !!strcmp (keyword, "security.capability"))
673             continue;
674
675           if (xattrs_masked_out (keyword, false /* extracting */ ))
676             /* we don't want to restore this keyword */
677             continue;
678
679           xattrs__fd_set (st, file_name, typeflag, keyword,
680                           st->xattr_map[scan].xval_ptr,
681                           st->xattr_map[scan].xval_len);
682         }
683 #endif
684     }
685 }
686
687 void
688 xattrs_print_char (struct tar_stat_info const *st, char *output)
689 {
690   int i;
691
692   if (verbose_option < 2)
693     {
694       *output = 0;
695       return;
696     }
697
698   if (xattrs_option > 0 || selinux_context_option > 0 || acls_option > 0)
699     {
700       /* placeholders */
701       *output = ' ';
702       output[1] = 0;
703     }
704
705   if (xattrs_option > 0 && st->xattr_map_size)
706     for (i = 0; i < st->xattr_map_size; ++i)
707       {
708         char *keyword = st->xattr_map[i].xkey + strlen ("SCHILY.xattr.");
709         if (!xattrs_masked_out (keyword, false /* like extracting */ ))
710           {
711             *output = '*';
712             break;
713           }
714       }
715
716   if (selinux_context_option > 0 && st->cntx_name)
717     *output = '.';
718
719   if (acls_option > 0 && (st->acls_a_len || st->acls_d_len))
720     *output = '+';
721 }
722
723 void
724 xattrs_print (struct tar_stat_info const *st)
725 {
726   if (verbose_option < 3)
727     return;
728
729   /* selinux */
730   if (selinux_context_option > 0 && st->cntx_name)
731     fprintf (stdlis, "  s: %s\n", st->cntx_name);
732
733   /* acls */
734   if (acls_option > 0 && (st->acls_a_len || st->acls_d_len))
735     {
736       fprintf (stdlis, "  a: ");
737       acls_one_line ("", ',', st->acls_a_ptr, st->acls_a_len);
738       acls_one_line ("default:", ',', st->acls_d_ptr, st->acls_d_len);
739       fprintf (stdlis, "\n");
740     }
741
742   /* xattrs */
743   if (xattrs_option > 0 && st->xattr_map_size)
744     {
745       int i;
746
747       for (i = 0; i < st->xattr_map_size; ++i)
748         {
749           char *keyword = st->xattr_map[i].xkey + strlen ("SCHILY.xattr.");
750           if (!xattrs_masked_out (keyword, false /* like extracting */ ))
751             fprintf (stdlis, "  x: %lu %s\n",
752                      (unsigned long) st->xattr_map[i].xval_len, keyword);
753         }
754     }
755 }