libtar: store SELinux file context in tar archives

* Using RedHat's "RHT.security.selinux=" tag in extended
  tar header (type 'x')

Signed-off-by: Vojtech Bocek <vbocek@gmail.com>

Change-Id: I102e492e4fa5b8a08fae4d34eb36386862509b4d
diff --git a/libtar/append.c b/libtar/append.c
index 05024b9..3a8bfc6 100644
--- a/libtar/append.c
+++ b/libtar/append.c
@@ -90,6 +90,31 @@
 #endif
 	th_set_path(t, (savename ? savename : realname));
 
+#ifdef HAVE_SELINUX
+	/* get selinux context */
+	if(t->options & TAR_STORE_SELINUX)
+	{
+		if(t->th_buf.selinux_context != NULL)
+		{
+			free(t->th_buf.selinux_context);
+			t->th_buf.selinux_context = NULL;
+		}
+
+		security_context_t selinux_context = NULL;
+		if(getfilecon(realname, &selinux_context) >= 0)
+		{
+			t->th_buf.selinux_context = strdup(selinux_context);
+			freecon(selinux_context);
+		}
+		else
+		{
+#ifdef DEBUG
+			perror("Failed to get selinux context");
+#endif
+		}
+	}
+#endif
+
 	/* check if it's a hardlink */
 #ifdef DEBUG
 	puts("    tar_append_file(): checking inode cache for hardlink...");