Add missign single include guards
[platform/upstream/glib.git] / gio / glocalfileinfo.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  * 
5  * Copyright (C) 2006-2007 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library 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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  *
22  * Author: Alexander Larsson <alexl@redhat.com>
23  */
24
25 #include "config.h"
26
27 #ifdef HAVE_SYS_TIME_H
28 #include <sys/time.h>
29 #endif
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <string.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #define _GNU_SOURCE
37 #include <fcntl.h>
38 #include <errno.h>
39 #ifdef HAVE_GRP_H
40 #include <grp.h>
41 #endif
42 #ifdef HAVE_PWD_H
43 #include <pwd.h>
44 #endif
45 #ifdef HAVE_SELINUX
46 #include <selinux/selinux.h>
47 #endif
48
49 #ifdef HAVE_XATTR
50
51 #if defined HAVE_SYS_XATTR_H
52   #include <sys/xattr.h>
53 #elif defined HAVE_ATTR_XATTR_H
54   #include <attr/xattr.h>
55 #else
56   #error "Neither <sys/xattr.h> nor <attr/xattr.h> is present but extended attribute support is enabled."
57 #endif /* defined HAVE_SYS_XATTR_H || HAVE_ATTR_XATTR_H */
58
59 #endif /* HAVE_XATTR */
60
61 #include <glib/gstdio.h>
62 #include <gfileattribute-priv.h>
63 #include <gfileinfo-priv.h>
64 #include <gvfs.h>
65
66 #include "glibintl.h"
67
68 #ifdef G_OS_WIN32
69 #include <windows.h>
70 #include <io.h>
71 #ifndef W_OK
72 #define W_OK 2
73 #endif
74 #ifndef R_OK
75 #define R_OK 4
76 #endif
77 #ifndef X_OK
78 #define X_OK 0 /* not really */
79 #endif
80 #ifndef S_ISREG
81 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
82 #endif
83 #ifndef S_ISDIR
84 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
85 #endif
86 #ifndef S_IXUSR
87 #define S_IXUSR _S_IEXEC
88 #endif
89 #endif
90
91 #include "glocalfileinfo.h"
92 #include "gioerror.h"
93 #include "gthemedicon.h"
94 #include "gcontenttype.h"
95 #include "gcontenttypeprivate.h"
96
97 #include "gioalias.h"
98
99 /* See gstdio.h */
100 #ifndef G_OS_WIN32
101 #define _g_stat_struct stat
102 #endif
103
104 struct ThumbMD5Context {
105         guint32 buf[4];
106         guint32 bits[2];
107         unsigned char in[64];
108 };
109
110 #ifndef G_OS_WIN32
111
112 typedef struct {
113   char *user_name;
114   char *real_name;
115 } UidData;
116
117 G_LOCK_DEFINE_STATIC (uid_cache);
118 static GHashTable *uid_cache = NULL;
119
120 G_LOCK_DEFINE_STATIC (gid_cache);
121 static GHashTable *gid_cache = NULL;
122
123 #endif  /* !G_OS_WIN32 */
124
125 char *
126 _g_local_file_info_create_etag (GLocalFileStat *statbuf)
127 {
128   GTimeVal tv;
129   
130   tv.tv_sec = statbuf->st_mtime;
131 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
132   tv.tv_usec = statbuf->st_mtimensec / 1000;
133 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
134   tv.tv_usec = statbuf->st_mtim.tv_nsec / 1000;
135 #else
136   tv.tv_usec = 0;
137 #endif
138
139   return g_strdup_printf ("%lu:%lu", tv.tv_sec, tv.tv_usec);
140 }
141
142 static char *
143 _g_local_file_info_create_file_id (GLocalFileStat *statbuf)
144 {
145   return g_strdup_printf ("l%" G_GUINT64_FORMAT ":%" G_GUINT64_FORMAT,
146                           (guint64) statbuf->st_dev, 
147                           (guint64) statbuf->st_ino);
148 }
149
150 static char *
151 _g_local_file_info_create_fs_id (GLocalFileStat *statbuf)
152 {
153   return g_strdup_printf ("l%" G_GUINT64_FORMAT,
154                           (guint64) statbuf->st_dev);
155 }
156
157
158 #ifdef S_ISLNK
159
160 static gchar *
161 read_link (const gchar *full_name)
162 {
163 #ifdef HAVE_READLINK
164   gchar *buffer;
165   guint size;
166   
167   size = 256;
168   buffer = g_malloc (size);
169   
170   while (1)
171     {
172       int read_size;
173       
174       read_size = readlink (full_name, buffer, size);
175       if (read_size < 0)
176         {
177           g_free (buffer);
178           return NULL;
179         }
180       if (read_size < size)
181         {
182           buffer[read_size] = 0;
183           return buffer;
184         }
185       size *= 2;
186       buffer = g_realloc (buffer, size);
187     }
188 #else
189   return NULL;
190 #endif
191 }
192
193 #endif  /* S_ISLNK */
194
195 #ifdef HAVE_SELINUX
196 /* Get the SELinux security context */
197 static void
198 get_selinux_context (const char            *path,
199                      GFileInfo             *info,
200                      GFileAttributeMatcher *attribute_matcher,
201                      gboolean               follow_symlinks)
202 {
203   char *context;
204
205   if (!_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT))
206     return;
207   
208   if (is_selinux_enabled ())
209     {
210       if (follow_symlinks)
211         {
212           if (lgetfilecon_raw (path, &context) < 0)
213             return;
214         }
215       else
216         {
217           if (getfilecon_raw (path, &context) < 0)
218             return;
219         }
220
221       if (context)
222         {
223           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
224           freecon (context);
225         }
226     }
227 }
228 #endif
229
230 #ifdef HAVE_XATTR
231
232 /* Wrappers to hide away differences between (Linux) getxattr/lgetxattr and
233  * (Mac) getxattr(..., XATTR_NOFOLLOW)
234  */
235 #ifdef HAVE_XATTR_NOFOLLOW
236 #define g_fgetxattr(fd,name,value,size)  fgetxattr(fd,name,value,size,0,0)
237 #define g_flistxattr(fd,name,size)       flistxattr(fd,name,size,0)
238 #define g_setxattr(path,name,value,size) setxattr(path,name,value,size,0,0)
239 #else
240 #define g_fgetxattr     fgetxattr
241 #define g_flistxattr    flistxattr
242 #define g_setxattr(path,name,value,size) setxattr(path,name,value,size,0)
243 #endif
244
245 static ssize_t
246 g_getxattr (const char *path, const char *name, void *value, size_t size,
247             gboolean follow_symlinks)
248 {
249 #ifdef HAVE_XATTR_NOFOLLOW
250   return getxattr (path, name, value, size, 0, follow_symlinks ? 0 : XATTR_NOFOLLOW);
251 #else
252   if (follow_symlinks)
253     return getxattr (path, name, value, size);
254   else
255     return lgetxattr (path, name, value, size);
256 #endif
257 }
258
259 static ssize_t
260 g_listxattr(const char *path, char *namebuf, size_t size,
261             gboolean follow_symlinks)
262 {
263 #ifdef HAVE_XATTR_NOFOLLOW
264   return listxattr (path, namebuf, size, follow_symlinks ? 0 : XATTR_NOFOLLOW);
265 #else
266   if (follow_symlinks)
267     return listxattr (path, namebuf, size);
268   else
269     return llistxattr (path, namebuf, size);
270 #endif
271 }
272
273 static gboolean
274 valid_char (char c)
275 {
276   return c >= 32 && c <= 126 && c != '\\';
277 }
278
279 static gboolean
280 name_is_valid (const char *str)
281 {
282   while (*str)
283     {
284       if (!valid_char (*str++))
285         return FALSE;
286     }
287   return TRUE;
288 }
289
290 static char *
291 hex_escape_string (const char *str, 
292                    gboolean   *free_return)
293 {
294   int num_invalid, i;
295   char *escaped_str, *p;
296   unsigned char c;
297   static char *hex_digits = "0123456789abcdef";
298   int len;
299
300   len = strlen (str);
301   
302   num_invalid = 0;
303   for (i = 0; i < len; i++)
304     {
305       if (!valid_char (str[i]))
306         num_invalid++;
307     }
308
309   if (num_invalid == 0)
310     {
311       *free_return = FALSE;
312       return (char *)str;
313     }
314
315   escaped_str = g_malloc (len + num_invalid*3 + 1);
316
317   p = escaped_str;
318   for (i = 0; i < len; i++)
319     {
320       if (valid_char (str[i]))
321         *p++ = str[i];
322       else
323         {
324           c = str[i];
325           *p++ = '\\';
326           *p++ = 'x';
327           *p++ = hex_digits[(c >> 4) & 0xf];
328           *p++ = hex_digits[c & 0xf];
329         }
330     }
331   *p = 0;
332
333   *free_return = TRUE;
334   return escaped_str;
335 }
336
337 static char *
338 hex_unescape_string (const char *str, 
339                      int        *out_len, 
340                      gboolean   *free_return)
341 {
342   int i;
343   char *unescaped_str, *p;
344   unsigned char c;
345   int len;
346
347   len = strlen (str);
348   
349   if (strchr (str, '\\') == NULL)
350     {
351       if (out_len)
352         *out_len = len;
353       *free_return = FALSE;
354       return (char *)str;
355     }
356   
357   unescaped_str = g_malloc (len + 1);
358
359   p = unescaped_str;
360   for (i = 0; i < len; i++)
361     {
362       if (str[i] == '\\' &&
363           str[i+1] == 'x' &&
364           len - i >= 4)
365         {
366           c =
367             (g_ascii_xdigit_value (str[i+2]) << 4) |
368             g_ascii_xdigit_value (str[i+3]);
369           *p++ = c;
370           i += 3;
371         }
372       else
373         *p++ = str[i];
374     }
375   *p++ = 0;
376
377   if (out_len)
378     *out_len = p - unescaped_str;
379   *free_return = TRUE;
380   return unescaped_str;
381 }
382
383 static void
384 escape_xattr (GFileInfo  *info,
385               const char *gio_attr, /* gio attribute name */
386               const char *value, /* Is zero terminated */
387               size_t      len /* not including zero termination */)
388 {
389   char *escaped_val;
390   gboolean free_escaped_val;
391   
392   escaped_val = hex_escape_string (value, &free_escaped_val);
393   
394   g_file_info_set_attribute_string (info, gio_attr, escaped_val);
395   
396   if (free_escaped_val)
397     g_free (escaped_val);
398 }
399
400 static void
401 get_one_xattr (const char *path,
402                GFileInfo  *info,
403                const char *gio_attr,
404                const char *xattr,
405                gboolean    follow_symlinks)
406 {
407   char value[64];
408   char *value_p;
409   ssize_t len;
410
411   len = g_getxattr (path, xattr, value, sizeof (value)-1, follow_symlinks);
412
413   value_p = NULL;
414   if (len >= 0)
415     value_p = value;
416   else if (len == -1 && errno == ERANGE)
417     {
418       len = g_getxattr (path, xattr, NULL, 0, follow_symlinks);
419
420       if (len < 0)
421         return;
422
423       value_p = g_malloc (len+1);
424
425       len = g_getxattr (path, xattr, value_p, len, follow_symlinks);
426
427       if (len < 0)
428         {
429           g_free (value_p);
430           return;
431         }
432     }
433   else
434     return;
435   
436   /* Null terminate */
437   value_p[len] = 0;
438
439   escape_xattr (info, gio_attr, value_p, len);
440   
441   if (value_p != value)
442     g_free (value_p);
443 }
444
445 #endif /* defined HAVE_XATTR */
446
447 static void
448 get_xattrs (const char            *path,
449             gboolean               user,
450             GFileInfo             *info,
451             GFileAttributeMatcher *matcher,
452             gboolean               follow_symlinks)
453 {
454 #ifdef HAVE_XATTR
455   gboolean all;
456   gsize list_size;
457   ssize_t list_res_size;
458   size_t len;
459   char *list;
460   const char *attr, *attr2;
461
462   if (user)
463     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
464   else
465     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
466
467   if (all)
468     {
469       list_res_size = g_listxattr (path, NULL, 0, follow_symlinks);
470
471       if (list_res_size == -1 ||
472           list_res_size == 0)
473         return;
474
475       list_size = list_res_size;
476       list = g_malloc (list_size);
477
478     retry:
479       
480       list_res_size = g_listxattr (path, list, list_size, follow_symlinks);
481       
482       if (list_res_size == -1 && errno == ERANGE)
483         {
484           list_size = list_size * 2;
485           list = g_realloc (list, list_size);
486           goto retry;
487         }
488
489       if (list_res_size == -1)
490         return;
491
492       attr = list;
493       while (list_res_size > 0)
494         {
495           if ((user && g_str_has_prefix (attr, "user.")) ||
496               (!user && !g_str_has_prefix (attr, "user.")))
497             {
498               char *escaped_attr, *gio_attr;
499               gboolean free_escaped_attr;
500               
501               if (user)
502                 {
503                   escaped_attr = hex_escape_string (attr + 5, &free_escaped_attr);
504                   gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
505                 }
506               else
507                 {
508                   escaped_attr = hex_escape_string (attr, &free_escaped_attr);
509                   gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
510                 }
511               
512               if (free_escaped_attr)
513                 g_free (escaped_attr);
514               
515               get_one_xattr (path, info, gio_attr, attr, follow_symlinks);
516
517               g_free (gio_attr);
518             }
519               
520           len = strlen (attr) + 1;
521           attr += len;
522           list_res_size -= len;
523         }
524
525       g_free (list);
526     }
527   else
528     {
529       while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
530         {
531           char *unescaped_attribute, *a;
532           gboolean free_unescaped_attribute;
533
534           attr2 = strchr (attr, ':');
535           if (attr2)
536             {
537               attr2 += 2; /* Skip '::' */
538               unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
539               if (user)
540                 a = g_strconcat ("user.", unescaped_attribute, NULL);
541               else
542                 a = unescaped_attribute;
543               
544               get_one_xattr (path, info, attr, a, follow_symlinks);
545
546               if (user)
547                 g_free (a);
548               
549               if (free_unescaped_attribute)
550                 g_free (unescaped_attribute);
551             }
552         }
553     }
554 #endif /* defined HAVE_XATTR */
555 }
556
557 #ifdef HAVE_XATTR
558 static void
559 get_one_xattr_from_fd (int         fd,
560                        GFileInfo  *info,
561                        const char *gio_attr,
562                        const char *xattr)
563 {
564   char value[64];
565   char *value_p;
566   ssize_t len;
567
568   len = g_fgetxattr (fd, xattr, value, sizeof (value) - 1);
569
570   value_p = NULL;
571   if (len >= 0)
572     value_p = value;
573   else if (len == -1 && errno == ERANGE)
574     {
575       len = g_fgetxattr (fd, xattr, NULL, 0);
576
577       if (len < 0)
578         return;
579
580       value_p = g_malloc (len + 1);
581
582       len = g_fgetxattr (fd, xattr, value_p, len);
583
584       if (len < 0)
585         {
586           g_free (value_p);
587           return;
588         }
589     }
590   else
591     return;
592   
593   /* Null terminate */
594   value_p[len] = 0;
595
596   escape_xattr (info, gio_attr, value_p, len);
597   
598   if (value_p != value)
599     g_free (value_p);
600 }
601 #endif /* defined HAVE_XATTR */
602
603 static void
604 get_xattrs_from_fd (int                    fd,
605                     gboolean               user,
606                     GFileInfo             *info,
607                     GFileAttributeMatcher *matcher)
608 {
609 #ifdef HAVE_XATTR
610   gboolean all;
611   gsize list_size;
612   ssize_t list_res_size;
613   size_t len;
614   char *list;
615   const char *attr, *attr2;
616
617   if (user)
618     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
619   else
620     all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
621
622   if (all)
623     {
624       list_res_size = g_flistxattr (fd, NULL, 0);
625
626       if (list_res_size == -1 ||
627           list_res_size == 0)
628         return;
629
630       list_size = list_res_size;
631       list = g_malloc (list_size);
632
633     retry:
634       
635       list_res_size = g_flistxattr (fd, list, list_size);
636       
637       if (list_res_size == -1 && errno == ERANGE)
638         {
639           list_size = list_size * 2;
640           list = g_realloc (list, list_size);
641           goto retry;
642         }
643
644       if (list_res_size == -1)
645         return;
646
647       attr = list;
648       while (list_res_size > 0)
649         {
650           if ((user && g_str_has_prefix (attr, "user.")) ||
651               (!user && !g_str_has_prefix (attr, "user.")))
652             {
653               char *escaped_attr, *gio_attr;
654               gboolean free_escaped_attr;
655               
656               if (user)
657                 {
658                   escaped_attr = hex_escape_string (attr + 5, &free_escaped_attr);
659                   gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
660                 }
661               else
662                 {
663                   escaped_attr = hex_escape_string (attr, &free_escaped_attr);
664                   gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
665                 }
666               
667               if (free_escaped_attr)
668                 g_free (escaped_attr);
669               
670               get_one_xattr_from_fd (fd, info, gio_attr, attr);
671             }
672           
673           len = strlen (attr) + 1;
674           attr += len;
675           list_res_size -= len;
676         }
677
678       g_free (list);
679     }
680   else
681     {
682       while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
683         {
684           char *unescaped_attribute, *a;
685           gboolean free_unescaped_attribute;
686
687           attr2 = strchr (attr, ':');
688           if (attr2)
689             {
690               attr2++; /* Skip ':' */
691               unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
692               if (user)
693                 a = g_strconcat ("user.", unescaped_attribute, NULL);
694               else
695                 a = unescaped_attribute;
696               
697               get_one_xattr_from_fd (fd, info, attr, a);
698
699               if (user)
700                 g_free (a);
701               
702               if (free_unescaped_attribute)
703                 g_free (unescaped_attribute);
704             }
705         }
706     }
707 #endif /* defined HAVE_XATTR */
708 }
709
710 #ifdef HAVE_XATTR
711 static gboolean
712 set_xattr (char                       *filename,
713            const char                 *escaped_attribute,
714            const GFileAttributeValue  *attr_value,
715            GError                    **error)
716 {
717   char *attribute, *value;
718   gboolean free_attribute, free_value;
719   int val_len, res, errsv;
720   gboolean is_user;
721   char *a;
722
723   if (attr_value == NULL)
724     {
725       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
726                            _("Attribute value must be non-NULL"));
727       return FALSE;
728     }
729
730   if (attr_value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
731     {
732       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
733                            _("Invalid attribute type (string expected)"));
734       return FALSE;
735     }
736
737   if (!name_is_valid (escaped_attribute))
738     {
739       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
740                            _("Invalid extended attribute name"));
741       return FALSE;
742     }
743
744   if (g_str_has_prefix (escaped_attribute, "xattr::"))
745     {
746       escaped_attribute += strlen ("xattr::");
747       is_user = TRUE;
748     }
749   else
750     {
751       g_warn_if_fail (g_str_has_prefix (escaped_attribute, "xattr-sys::"));
752       escaped_attribute += strlen ("xattr-sys::");
753       is_user = FALSE;
754     }
755   
756   attribute = hex_unescape_string (escaped_attribute, NULL, &free_attribute);
757   value = hex_unescape_string (attr_value->u.string, &val_len, &free_value);
758
759   if (is_user)
760     a = g_strconcat ("user.", attribute, NULL);
761   else
762     a = attribute;
763   
764   res = g_setxattr (filename, a, value, val_len);
765   errsv = errno;
766   
767   if (is_user)
768     g_free (a);
769   
770   if (free_attribute)
771     g_free (attribute);
772   
773   if (free_value)
774     g_free (value);
775
776   if (res == -1)
777     {
778       g_set_error (error, G_IO_ERROR,
779                    g_io_error_from_errno (errsv),
780                    _("Error setting extended attribute '%s': %s"),
781                    escaped_attribute, g_strerror (errsv));
782       return FALSE;
783     }
784   
785   return TRUE;
786 }
787
788 #endif
789
790
791 void
792 _g_local_file_info_get_parent_info (const char            *dir,
793                                     GFileAttributeMatcher *attribute_matcher,
794                                     GLocalParentFileInfo  *parent_info)
795 {
796   struct _g_stat_struct statbuf;
797   int res;
798
799   parent_info->extra_data = NULL;
800   parent_info->free_extra_data = NULL;
801   parent_info->writable = FALSE;
802   parent_info->is_sticky = FALSE;
803   parent_info->has_trash_dir = FALSE;
804   parent_info->device = 0;
805
806   if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME) ||
807       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE) ||
808       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH) ||
809       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT))
810     {
811       /* FIXME: Windows: The underlying _waccess() call in the C
812        * library is mostly pointless as it only looks at the READONLY
813        * FAT-style attribute of the file, it doesn't check the ACL at
814        * all.
815        */
816       parent_info->writable = (g_access (dir, W_OK) == 0);
817       
818       res = g_stat (dir, &statbuf);
819
820       /*
821        * The sticky bit (S_ISVTX) on a directory means that a file in that directory can be
822        * renamed or deleted only by the owner of the file, by the owner of the directory, and
823        * by a privileged process.
824        */
825       if (res == 0)
826         {
827 #ifdef S_ISVTX
828           parent_info->is_sticky = (statbuf.st_mode & S_ISVTX) != 0;
829 #else
830           parent_info->is_sticky = FALSE;
831 #endif
832           parent_info->owner = statbuf.st_uid;
833           parent_info->device = statbuf.st_dev;
834           /* No need to find trash dir if it's not writable anyway */
835           if (parent_info->writable &&
836               _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
837             parent_info->has_trash_dir = _g_local_file_has_trash_dir (dir, statbuf.st_dev);
838         }
839     }
840 }
841
842 void
843 _g_local_file_info_free_parent_info (GLocalParentFileInfo *parent_info)
844 {
845   if (parent_info->extra_data &&
846       parent_info->free_extra_data)
847     parent_info->free_extra_data (parent_info->extra_data);
848 }
849
850 static void
851 get_access_rights (GFileAttributeMatcher *attribute_matcher,
852                    GFileInfo             *info,
853                    const gchar           *path,
854                    GLocalFileStat        *statbuf,
855                    GLocalParentFileInfo  *parent_info)
856 {
857   /* FIXME: Windows: The underlyin _waccess() is mostly pointless */
858   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
859                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ))
860     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ,
861                                              g_access (path, R_OK) == 0);
862   
863   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
864                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE))
865     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE,
866                                              g_access (path, W_OK) == 0);
867   
868   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
869                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE))
870     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE,
871                                              g_access (path, X_OK) == 0);
872
873
874   if (parent_info)
875     {
876       gboolean writable;
877
878       writable = FALSE;
879       if (parent_info->writable)
880         {
881           if (parent_info->is_sticky)
882             {
883 #ifndef G_OS_WIN32
884               uid_t uid = geteuid ();
885
886               if (uid == statbuf->st_uid ||
887                   uid == parent_info->owner ||
888                   uid == 0)
889 #endif
890                 writable = TRUE;
891             }
892           else
893             writable = TRUE;
894         }
895
896       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME))
897         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME,
898                                                  writable);
899       
900       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE))
901         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE,
902                                                  writable);
903
904       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
905         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH,
906                                                  writable && parent_info->has_trash_dir);
907     }
908 }
909
910 static void
911 set_info_from_stat (GFileInfo             *info, 
912                     GLocalFileStat        *statbuf,
913                     GFileAttributeMatcher *attribute_matcher)
914 {
915   GFileType file_type;
916
917   file_type = G_FILE_TYPE_UNKNOWN;
918
919   if (S_ISREG (statbuf->st_mode))
920     file_type = G_FILE_TYPE_REGULAR;
921   else if (S_ISDIR (statbuf->st_mode))
922     file_type = G_FILE_TYPE_DIRECTORY;
923 #ifndef G_OS_WIN32
924   else if (S_ISCHR (statbuf->st_mode) ||
925            S_ISBLK (statbuf->st_mode) ||
926            S_ISFIFO (statbuf->st_mode)
927 #ifdef S_ISSOCK
928            || S_ISSOCK (statbuf->st_mode)
929 #endif
930            )
931     file_type = G_FILE_TYPE_SPECIAL;
932 #endif
933 #ifdef S_ISLNK
934   else if (S_ISLNK (statbuf->st_mode))
935     file_type = G_FILE_TYPE_SYMBOLIC_LINK;
936 #endif
937
938   g_file_info_set_file_type (info, file_type);
939   g_file_info_set_size (info, statbuf->st_size);
940
941   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_DEVICE, statbuf->st_dev);
942 #ifndef G_OS_WIN32
943   /* Pointless setting these on Windows even if they exist in the struct */
944   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_INODE, statbuf->st_ino);
945   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_NLINK, statbuf->st_nlink);
946   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_UID, statbuf->st_uid);
947   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_GID, statbuf->st_gid);
948   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_RDEV, statbuf->st_rdev);
949 #endif
950   /* FIXME: st_mode is mostly pointless on Windows, too. Set the attribute or not? */
951   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_MODE, statbuf->st_mode);
952 #if defined (HAVE_STRUCT_STAT_ST_BLKSIZE)
953   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCK_SIZE, statbuf->st_blksize);
954 #endif
955 #if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
956   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCKS, statbuf->st_blocks);
957   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_ALLOCATED_SIZE,
958                                           statbuf->st_blocks * G_GUINT64_CONSTANT (512));
959 #endif
960   
961   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED, statbuf->st_mtime);
962 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
963   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtimensec / 1000);
964 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
965   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtim.tv_nsec / 1000);
966 #endif
967   
968   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS, statbuf->st_atime);
969 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
970   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atimensec / 1000);
971 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
972   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atim.tv_nsec / 1000);
973 #endif
974   
975   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED, statbuf->st_ctime);
976 #if defined (HAVE_STRUCT_STAT_ST_CTIMENSEC)
977   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctimensec / 1000);
978 #elif defined (HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC)
979   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctim.tv_nsec / 1000);
980 #endif
981
982   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
983                                             G_FILE_ATTRIBUTE_ID_ETAG_VALUE))
984     {
985       char *etag = _g_local_file_info_create_etag (statbuf);
986       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ETAG_VALUE, etag);
987       g_free (etag);
988     }
989
990   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
991                                             G_FILE_ATTRIBUTE_ID_ID_FILE))
992     {
993       char *id = _g_local_file_info_create_file_id (statbuf);
994       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILE, id);
995       g_free (id);
996     }
997
998   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
999                                             G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM))
1000     {
1001       char *id = _g_local_file_info_create_fs_id (statbuf);
1002       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM, id);
1003       g_free (id);
1004     }
1005 }
1006
1007 #ifndef G_OS_WIN32
1008
1009 static char *
1010 make_valid_utf8 (const char *name)
1011 {
1012   GString *string;
1013   const gchar *remainder, *invalid;
1014   gint remaining_bytes, valid_bytes;
1015   
1016   string = NULL;
1017   remainder = name;
1018   remaining_bytes = strlen (name);
1019   
1020   while (remaining_bytes != 0) 
1021     {
1022       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1023         break;
1024       valid_bytes = invalid - remainder;
1025     
1026       if (string == NULL) 
1027         string = g_string_sized_new (remaining_bytes);
1028
1029       g_string_append_len (string, remainder, valid_bytes);
1030       /* append U+FFFD REPLACEMENT CHARACTER */
1031       g_string_append (string, "\357\277\275");
1032       
1033       remaining_bytes -= valid_bytes + 1;
1034       remainder = invalid + 1;
1035     }
1036   
1037   if (string == NULL)
1038     return g_strdup (name);
1039   
1040   g_string_append (string, remainder);
1041
1042   g_warn_if_fail (g_utf8_validate (string->str, -1, NULL));
1043   
1044   return g_string_free (string, FALSE);
1045 }
1046
1047 static char *
1048 convert_pwd_string_to_utf8 (char *pwd_str)
1049 {
1050   char *utf8_string;
1051   
1052   if (!g_utf8_validate (pwd_str, -1, NULL))
1053     {
1054       utf8_string = g_locale_to_utf8 (pwd_str, -1, NULL, NULL, NULL);
1055       if (utf8_string == NULL)
1056         utf8_string = make_valid_utf8 (pwd_str);
1057     }
1058   else 
1059     utf8_string = g_strdup (pwd_str);
1060   
1061   return utf8_string;
1062 }
1063
1064 static void
1065 uid_data_free (UidData *data)
1066 {
1067   g_free (data->user_name);
1068   g_free (data->real_name);
1069   g_free (data);
1070 }
1071
1072 /* called with lock held */
1073 static UidData *
1074 lookup_uid_data (uid_t uid)
1075 {
1076   UidData *data;
1077   char buffer[4096];
1078   struct passwd pwbuf;
1079   struct passwd *pwbufp;
1080   char *gecos, *comma;
1081   
1082   if (uid_cache == NULL)
1083     uid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)uid_data_free);
1084
1085   data = g_hash_table_lookup (uid_cache, GINT_TO_POINTER (uid));
1086
1087   if (data)
1088     return data;
1089
1090   data = g_new0 (UidData, 1);
1091
1092 #if defined(HAVE_POSIX_GETPWUID_R)
1093   getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer), &pwbufp);
1094 #elif defined(HAVE_NONPOSIX_GETPWUID_R)
1095   pwbufp = getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer));
1096 #else
1097   pwbufp = getpwuid (uid);
1098 #endif
1099
1100   if (pwbufp != NULL)
1101     {
1102       if (pwbufp->pw_name != NULL && pwbufp->pw_name[0] != 0)
1103         data->user_name = convert_pwd_string_to_utf8 (pwbufp->pw_name);
1104
1105       gecos = pwbufp->pw_gecos;
1106
1107       if (gecos)
1108         {
1109           comma = strchr (gecos, ',');
1110           if (comma)
1111             *comma = 0;
1112           data->real_name = convert_pwd_string_to_utf8 (gecos);
1113         }
1114     }
1115
1116   /* Default fallbacks */
1117   if (data->real_name == NULL)
1118     {
1119       if (data->user_name != NULL)
1120         data->real_name = g_strdup (data->user_name);
1121       else
1122         data->real_name = g_strdup_printf ("user #%d", (int)uid);
1123     }
1124   
1125   if (data->user_name == NULL)
1126     data->user_name = g_strdup_printf ("%d", (int)uid);
1127   
1128   g_hash_table_replace (uid_cache, GINT_TO_POINTER (uid), data);
1129   
1130   return data;
1131 }
1132
1133 static char *
1134 get_username_from_uid (uid_t uid)
1135 {
1136   char *res;
1137   UidData *data;
1138   
1139   G_LOCK (uid_cache);
1140   data = lookup_uid_data (uid);
1141   res = g_strdup (data->user_name);  
1142   G_UNLOCK (uid_cache);
1143
1144   return res;
1145 }
1146
1147 static char *
1148 get_realname_from_uid (uid_t uid)
1149 {
1150   char *res;
1151   UidData *data;
1152   
1153   G_LOCK (uid_cache);
1154   data = lookup_uid_data (uid);
1155   res = g_strdup (data->real_name);  
1156   G_UNLOCK (uid_cache);
1157   
1158   return res;
1159 }
1160
1161 /* called with lock held */
1162 static char *
1163 lookup_gid_name (gid_t gid)
1164 {
1165   char *name;
1166   char buffer[4096];
1167   struct group gbuf;
1168   struct group *gbufp;
1169   
1170   if (gid_cache == NULL)
1171     gid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_free);
1172
1173   name = g_hash_table_lookup (gid_cache, GINT_TO_POINTER (gid));
1174
1175   if (name)
1176     return name;
1177
1178 #if defined (HAVE_POSIX_GETGRGID_R)
1179   getgrgid_r (gid, &gbuf, buffer, sizeof(buffer), &gbufp);
1180 #elif defined (HAVE_NONPOSIX_GETGRGID_R)
1181   gbufp = getgrgid_r (gid, &gbuf, buffer, sizeof(buffer));
1182 #else
1183   gbufp = getgrgid (gid);
1184 #endif
1185
1186   if (gbufp != NULL &&
1187       gbufp->gr_name != NULL &&
1188       gbufp->gr_name[0] != 0)
1189     name = convert_pwd_string_to_utf8 (gbufp->gr_name);
1190   else
1191     name = g_strdup_printf("%d", (int)gid);
1192   
1193   g_hash_table_replace (gid_cache, GINT_TO_POINTER (gid), name);
1194   
1195   return name;
1196 }
1197
1198 static char *
1199 get_groupname_from_gid (gid_t gid)
1200 {
1201   char *res;
1202   char *name;
1203   
1204   G_LOCK (gid_cache);
1205   name = lookup_gid_name (gid);
1206   res = g_strdup (name);  
1207   G_UNLOCK (gid_cache);
1208   return res;
1209 }
1210
1211 #endif /* !G_OS_WIN32 */
1212
1213 static char *
1214 get_content_type (const char          *basename,
1215                   const char          *path,
1216                   GLocalFileStat      *statbuf,
1217                   gboolean             is_symlink,
1218                   gboolean             symlink_broken,
1219                   GFileQueryInfoFlags  flags,
1220                   gboolean             fast)
1221 {
1222   if (is_symlink &&
1223       (symlink_broken || (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)))
1224     return g_strdup  ("inode/symlink");
1225   else if (S_ISDIR(statbuf->st_mode))
1226     return g_strdup ("inode/directory");
1227 #ifndef G_OS_WIN32
1228   else if (S_ISCHR(statbuf->st_mode))
1229     return g_strdup ("inode/chardevice");
1230   else if (S_ISBLK(statbuf->st_mode))
1231     return g_strdup ("inode/blockdevice");
1232   else if (S_ISFIFO(statbuf->st_mode))
1233     return g_strdup ("inode/fifo");
1234 #endif
1235 #ifdef S_ISSOCK
1236   else if (S_ISSOCK(statbuf->st_mode))
1237     return g_strdup ("inode/socket");
1238 #endif
1239   else
1240     {
1241       char *content_type;
1242       gboolean result_uncertain;
1243       
1244       content_type = g_content_type_guess (basename, NULL, 0, &result_uncertain);
1245       
1246 #ifndef G_OS_WIN32
1247       if (!fast && result_uncertain && path != NULL)
1248         {
1249           guchar sniff_buffer[4096];
1250           gsize sniff_length;
1251           int fd;
1252
1253           sniff_length = _g_unix_content_type_get_sniff_len ();
1254           if (sniff_length > 4096)
1255             sniff_length = 4096;
1256
1257 #ifdef O_NOATIME          
1258           fd = open (path, O_RDONLY | O_NOATIME);
1259           if (fd < 0 && errno == EPERM)
1260 #endif
1261             fd = open (path, O_RDONLY);
1262
1263           if (fd != -1)
1264             {
1265               ssize_t res;
1266               
1267               res = read (fd, sniff_buffer, sniff_length);
1268               close (fd);
1269               if (res >= 0)
1270                 {
1271                   g_free (content_type);
1272                   content_type = g_content_type_guess (basename, sniff_buffer, res, NULL);
1273                 }
1274             }
1275         }
1276 #endif
1277       
1278       return content_type;
1279     }
1280   
1281 }
1282
1283 static void
1284 get_thumbnail_attributes (const char *path,
1285                           GFileInfo  *info)
1286 {
1287   GChecksum *checksum;
1288   char *uri;
1289   char *filename;
1290   char *basename;
1291
1292   uri = g_filename_to_uri (path, NULL, NULL);
1293
1294   checksum = g_checksum_new (G_CHECKSUM_MD5);
1295   g_checksum_update (checksum, (const guchar *) uri, strlen (uri));
1296   
1297   g_free (uri);
1298
1299   basename = g_strconcat (g_checksum_get_string (checksum), ".png", NULL);
1300   g_checksum_free (checksum);
1301
1302   filename = g_build_filename (g_get_home_dir (),
1303                                ".thumbnails", "normal", basename,
1304                                NULL);
1305
1306   if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1307     _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1308   else
1309     {
1310       g_free (filename);
1311       filename = g_build_filename (g_get_home_dir (),
1312                                    ".thumbnails", "fail",
1313                                    "gnome-thumbnail-factory",
1314                                    basename,
1315                                    NULL);
1316
1317       if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1318         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAILING_FAILED, TRUE);
1319     }
1320   g_free (basename);
1321   g_free (filename);
1322 }
1323
1324 #ifdef G_OS_WIN32
1325 static void
1326 win32_get_file_user_info (const gchar  *filename,
1327                           gchar       **group_name, 
1328                           gchar       **user_name, 
1329                           gchar       **real_name)
1330 {
1331   PSECURITY_DESCRIPTOR psd = NULL;
1332   DWORD sd_size = 0; /* first call calculates the size required */
1333   
1334   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1335   if ((GetFileSecurityW (wfilename, 
1336                         GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1337                         NULL,
1338                         sd_size,
1339                         &sd_size) || (ERROR_INSUFFICIENT_BUFFER == GetLastError())) &&
1340      (psd = g_try_malloc (sd_size)) != NULL &&
1341      GetFileSecurityW (wfilename, 
1342                        GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1343                        psd,
1344                        sd_size,
1345                        &sd_size))
1346     {
1347       PSID psid = 0;
1348       BOOL defaulted;
1349       SID_NAME_USE name_use = 0; /* don't care? */
1350       wchar_t *name = NULL;
1351       wchar_t *domain = NULL;
1352       DWORD name_len = 0;
1353       DWORD domain_len = 0;
1354       /* get the user name */
1355       do {
1356         if (!user_name)
1357           break;
1358         if (!GetSecurityDescriptorOwner (psd, &psid, &defaulted))
1359           break;
1360         if (!LookupAccountSidW (NULL, /* local machine */
1361                                 psid, 
1362                                 name, &name_len,
1363                                 domain, &domain_len, /* no domain info yet */
1364                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1365           break;
1366         name = g_try_malloc (name_len * sizeof (wchar_t));
1367         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1368         if (name && domain &&
1369             LookupAccountSidW (NULL, /* local machine */
1370                                psid, 
1371                                name, &name_len,
1372                                domain, &domain_len, /* no domain info yet */
1373                                &name_use))
1374           {
1375             *user_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1376           }
1377         g_free (name);
1378         g_free (domain);
1379       } while (FALSE);
1380
1381       /* get the group name */
1382       do {
1383         if (!group_name)
1384           break;
1385         if (!GetSecurityDescriptorGroup (psd, &psid, &defaulted))
1386           break;
1387         if (!LookupAccountSidW (NULL, /* local machine */
1388                                 psid, 
1389                                 name, &name_len,
1390                                 domain, &domain_len, /* no domain info yet */
1391                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1392           break;
1393         name = g_try_malloc (name_len * sizeof (wchar_t));
1394         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1395         if (name && domain &&
1396             LookupAccountSidW (NULL, /* local machine */
1397                                psid, 
1398                                name, &name_len,
1399                                domain, &domain_len, /* no domain info yet */
1400                                &name_use))
1401           {
1402             *group_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1403           }
1404         g_free (name);
1405         g_free (domain);
1406       } while (FALSE);
1407
1408       /* TODO: get real name */
1409
1410       g_free (psd);
1411     }
1412   g_free (wfilename);
1413 }
1414 #endif /* G_OS_WIN32 */
1415
1416 GFileInfo *
1417 _g_local_file_info_get (const char             *basename,
1418                         const char             *path,
1419                         GFileAttributeMatcher  *attribute_matcher,
1420                         GFileQueryInfoFlags     flags,
1421                         GLocalParentFileInfo   *parent_info,
1422                         GError                **error)
1423 {
1424   GFileInfo *info;
1425   GLocalFileStat statbuf;
1426 #ifdef S_ISLNK
1427   struct stat statbuf2;
1428 #endif
1429   int res;
1430   gboolean is_symlink, symlink_broken;
1431 #ifdef G_OS_WIN32
1432   DWORD dos_attributes;
1433 #endif
1434   char *symlink_target;
1435   GVfs *vfs;
1436   GVfsClass *class;
1437   guint64 device;
1438
1439   info = g_file_info_new ();
1440
1441   /* Make sure we don't set any unwanted attributes */
1442   g_file_info_set_attribute_mask (info, attribute_matcher);
1443   
1444   g_file_info_set_name (info, basename);
1445
1446   /* Avoid stat in trivial case */
1447   if (attribute_matcher == NULL)
1448     return info;
1449
1450 #ifndef G_OS_WIN32
1451   res = g_lstat (path, &statbuf);
1452 #else
1453   {
1454     wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
1455     int len;
1456
1457     if (wpath == NULL)
1458       {
1459         g_object_unref (info);
1460         return NULL;
1461       }
1462
1463     len = wcslen (wpath);
1464     while (len > 0 && G_IS_DIR_SEPARATOR (wpath[len-1]))
1465       len--;
1466     if (len > 0 &&
1467         (!g_path_is_absolute (path) || len > g_path_skip_root (path) - path))
1468       wpath[len] = '\0';
1469
1470     res = _wstati64 (wpath, &statbuf);
1471     dos_attributes = GetFileAttributesW (wpath);
1472
1473     g_free (wpath);
1474   }
1475 #endif
1476
1477   if (res == -1)
1478     {
1479       int errsv = errno;
1480       char *display_name = g_filename_display_name (path);
1481       g_object_unref (info);
1482       g_set_error (error, G_IO_ERROR,
1483                    g_io_error_from_errno (errsv),
1484                    _("Error stating file '%s': %s"),
1485                    display_name, g_strerror (errsv));
1486       g_free (display_name);
1487       return NULL;
1488     }
1489
1490   device = statbuf.st_dev;
1491
1492 #ifdef S_ISLNK
1493   is_symlink = S_ISLNK (statbuf.st_mode);
1494 #else
1495   is_symlink = FALSE;
1496 #endif
1497   symlink_broken = FALSE;
1498 #ifdef S_ISLNK
1499   if (is_symlink)
1500     {
1501       g_file_info_set_is_symlink (info, TRUE);
1502
1503       /* Unless NOFOLLOW was set we default to following symlinks */
1504       if (!(flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS))
1505         {
1506           res = stat (path, &statbuf2);
1507
1508             /* Report broken links as symlinks */
1509           if (res != -1)
1510             statbuf = statbuf2;
1511           else
1512             symlink_broken = TRUE;
1513         }
1514     }
1515 #endif
1516
1517   set_info_from_stat (info, &statbuf, attribute_matcher);
1518   
1519 #ifndef G_OS_WIN32
1520   if (basename != NULL && basename[0] == '.')
1521     g_file_info_set_is_hidden (info, TRUE);
1522
1523   if (basename != NULL && basename[strlen (basename) -1] == '~' &&
1524       S_ISREG (statbuf.st_mode))
1525     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_IS_BACKUP, TRUE);
1526 #else
1527   if (dos_attributes & FILE_ATTRIBUTE_HIDDEN)
1528     g_file_info_set_is_hidden (info, TRUE);
1529
1530   if (dos_attributes & FILE_ATTRIBUTE_ARCHIVE)
1531     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_ARCHIVE, TRUE);
1532
1533   if (dos_attributes & FILE_ATTRIBUTE_SYSTEM)
1534     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_SYSTEM, TRUE);
1535 #endif
1536
1537   symlink_target = NULL;
1538 #ifdef S_ISLNK
1539   if (is_symlink)
1540     {
1541       symlink_target = read_link (path);
1542       if (symlink_target &&
1543           _g_file_attribute_matcher_matches_id (attribute_matcher,
1544                                                 G_FILE_ATTRIBUTE_ID_STANDARD_SYMLINK_TARGET))
1545         g_file_info_set_symlink_target (info, symlink_target);
1546     }
1547 #endif
1548   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1549                                             G_FILE_ATTRIBUTE_ID_STANDARD_DISPLAY_NAME))
1550     {
1551       char *display_name = g_filename_display_basename (path);
1552      
1553       /* look for U+FFFD REPLACEMENT CHARACTER */ 
1554       if (strstr (display_name, "\357\277\275") != NULL)
1555         {
1556           char *p = display_name;
1557           display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
1558           g_free (p);
1559         }
1560       g_file_info_set_display_name (info, display_name);
1561       g_free (display_name);
1562     }
1563   
1564   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1565                                             G_FILE_ATTRIBUTE_ID_STANDARD_EDIT_NAME))
1566     {
1567       char *edit_name = g_filename_display_basename (path);
1568       g_file_info_set_edit_name (info, edit_name);
1569       g_free (edit_name);
1570     }
1571
1572   
1573   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1574                                             G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME))
1575     {
1576       char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
1577       if (copy_name)
1578         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME, copy_name);
1579       g_free (copy_name);
1580     }
1581
1582   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1583                                             G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
1584       _g_file_attribute_matcher_matches_id (attribute_matcher,
1585                                             G_FILE_ATTRIBUTE_ID_STANDARD_ICON))
1586     {
1587       char *content_type = get_content_type (basename, path, &statbuf, is_symlink, symlink_broken, flags, FALSE);
1588
1589       if (content_type)
1590         {
1591           g_file_info_set_content_type (info, content_type);
1592
1593           if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1594                                                     G_FILE_ATTRIBUTE_ID_STANDARD_ICON))
1595             {
1596               GIcon *icon;
1597
1598               if (strcmp (path, g_get_home_dir ()) == 0)
1599                 icon = g_themed_icon_new ("user-home");
1600               else if (strcmp (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
1601                 icon = g_themed_icon_new ("user-desktop");
1602               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS)) == 0)
1603                 icon = g_themed_icon_new_with_default_fallbacks ("folder-documents");
1604               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD)) == 0)
1605                 icon = g_themed_icon_new_with_default_fallbacks ("folder-download");
1606               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_MUSIC)) == 0)
1607                 icon = g_themed_icon_new_with_default_fallbacks ("folder-music");
1608               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PICTURES)) == 0)
1609                 icon = g_themed_icon_new_with_default_fallbacks ("folder-pictures");
1610               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE)) == 0)
1611                 icon = g_themed_icon_new_with_default_fallbacks ("folder-publicshare");
1612               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES)) == 0)
1613                 icon = g_themed_icon_new_with_default_fallbacks ("folder-templates");
1614               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS)) == 0)
1615                 icon = g_themed_icon_new_with_default_fallbacks ("folder-videos");
1616               else
1617                 {
1618                   icon = g_content_type_get_icon (content_type);
1619                   if (G_IS_THEMED_ICON (icon))
1620                     {
1621                       const char *type_icon = NULL;
1622
1623                       if (S_ISDIR (statbuf.st_mode)) 
1624                         type_icon = "folder";
1625                       if (type_icon)
1626                         g_themed_icon_append_name (G_THEMED_ICON (icon), type_icon);
1627                     }
1628                 }
1629
1630               if (icon != NULL)
1631                 {
1632                   g_file_info_set_icon (info, icon);
1633                   g_object_unref (icon);
1634                 }
1635             }
1636           
1637           g_free (content_type);
1638         }
1639     }
1640
1641   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1642                                             G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))
1643     {
1644       char *content_type = get_content_type (basename, path, &statbuf, is_symlink, symlink_broken, flags, TRUE);
1645       
1646       if (content_type)
1647         {
1648           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);
1649           g_free (content_type);
1650         }
1651     }
1652
1653   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1654                                             G_FILE_ATTRIBUTE_ID_OWNER_USER))
1655     {
1656       char *name = NULL;
1657       
1658 #ifdef G_OS_WIN32
1659       win32_get_file_user_info (path, NULL, &name, NULL);
1660 #else
1661       name = get_username_from_uid (statbuf.st_uid);
1662 #endif
1663       if (name)
1664         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER, name);
1665       g_free (name);
1666     }
1667
1668   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1669                                             G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL))
1670     {
1671       char *name = NULL;
1672 #ifdef G_OS_WIN32
1673       win32_get_file_user_info (path, NULL, NULL, &name);
1674 #else
1675       name = get_realname_from_uid (statbuf.st_uid);
1676 #endif
1677       if (name)
1678         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL, name);
1679       g_free (name);
1680     }
1681   
1682   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1683                                             G_FILE_ATTRIBUTE_ID_OWNER_GROUP))
1684     {
1685       char *name = NULL;
1686 #ifdef G_OS_WIN32
1687       win32_get_file_user_info (path, &name, NULL, NULL);
1688 #else
1689       name = get_groupname_from_gid (statbuf.st_gid);
1690 #endif
1691       if (name)
1692         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_GROUP, name);
1693       g_free (name);
1694     }
1695
1696   if (parent_info && parent_info->device != 0 &&
1697       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT) &&
1698       statbuf.st_dev != parent_info->device) 
1699     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT, TRUE);
1700   
1701   get_access_rights (attribute_matcher, info, path, &statbuf, parent_info);
1702   
1703 #ifdef HAVE_SELINUX
1704   get_selinux_context (path, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1705 #endif
1706   get_xattrs (path, TRUE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1707   get_xattrs (path, FALSE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1708
1709   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1710                                             G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH))
1711     get_thumbnail_attributes (path, info);
1712
1713   vfs = g_vfs_get_default ();
1714   class = G_VFS_GET_CLASS (vfs);
1715   if (class->local_file_add_info)
1716     {
1717       class->local_file_add_info (vfs,
1718                                   path,
1719                                   device,
1720                                   attribute_matcher,
1721                                   info,
1722                                   NULL,
1723                                   &parent_info->extra_data,
1724                                   &parent_info->free_extra_data);
1725     }
1726
1727   g_file_info_unset_attribute_mask (info);
1728
1729   g_free (symlink_target);
1730
1731   return info;
1732 }
1733
1734 GFileInfo *
1735 _g_local_file_info_get_from_fd (int         fd,
1736                                 const char *attributes,
1737                                 GError    **error)
1738 {
1739   GLocalFileStat stat_buf;
1740   GFileAttributeMatcher *matcher;
1741   GFileInfo *info;
1742   
1743 #ifdef G_OS_WIN32
1744 #define FSTAT _fstati64
1745 #else
1746 #define FSTAT fstat
1747 #endif
1748
1749   if (FSTAT (fd, &stat_buf) == -1)
1750     {
1751       int errsv = errno;
1752
1753       g_set_error (error, G_IO_ERROR,
1754                    g_io_error_from_errno (errsv),
1755                    _("Error stating file descriptor: %s"),
1756                    g_strerror (errsv));
1757       return NULL;
1758     }
1759
1760   info = g_file_info_new ();
1761
1762   matcher = g_file_attribute_matcher_new (attributes);
1763
1764   /* Make sure we don't set any unwanted attributes */
1765   g_file_info_set_attribute_mask (info, matcher);
1766   
1767   set_info_from_stat (info, &stat_buf, matcher);
1768   
1769 #ifdef HAVE_SELINUX
1770   if (_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT) &&
1771       is_selinux_enabled ())
1772     {
1773       char *context;
1774       if (fgetfilecon_raw (fd, &context) >= 0)
1775         {
1776           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
1777           freecon (context);
1778         }
1779     }
1780 #endif
1781
1782   get_xattrs_from_fd (fd, TRUE, info, matcher);
1783   get_xattrs_from_fd (fd, FALSE, info, matcher);
1784   
1785   g_file_attribute_matcher_unref (matcher);
1786
1787   g_file_info_unset_attribute_mask (info);
1788   
1789   return info;
1790 }
1791
1792 static gboolean
1793 get_uint32 (const GFileAttributeValue  *value,
1794             guint32                    *val_out,
1795             GError                    **error)
1796 {
1797   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT32)
1798     {
1799       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1800                            _("Invalid attribute type (uint32 expected)"));
1801       return FALSE;
1802     }
1803
1804   *val_out = value->u.uint32;
1805   
1806   return TRUE;
1807 }
1808
1809 #ifdef HAVE_UTIMES
1810 static gboolean
1811 get_uint64 (const GFileAttributeValue  *value,
1812             guint64                    *val_out,
1813             GError                    **error)
1814 {
1815   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT64)
1816     {
1817       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1818                            _("Invalid attribute type (uint64 expected)"));
1819       return FALSE;
1820     }
1821
1822   *val_out = value->u.uint64;
1823   
1824   return TRUE;
1825 }
1826 #endif
1827
1828 #if defined(HAVE_SYMLINK)
1829 static gboolean
1830 get_byte_string (const GFileAttributeValue  *value,
1831                  const char                **val_out,
1832                  GError                    **error)
1833 {
1834   if (value->type != G_FILE_ATTRIBUTE_TYPE_BYTE_STRING)
1835     {
1836       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1837                            _("Invalid attribute type (byte string expected)"));
1838       return FALSE;
1839     }
1840
1841   *val_out = value->u.string;
1842   
1843   return TRUE;
1844 }
1845 #endif
1846
1847 #ifdef HAVE_SELINUX
1848 static gboolean
1849 get_string (const GFileAttributeValue  *value,
1850             const char                **val_out,
1851             GError                    **error)
1852 {
1853   if (value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
1854     {
1855       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1856                            _("Invalid attribute type (byte string expected)"));
1857       return FALSE;
1858     }
1859
1860   *val_out = value->u.string;
1861   
1862   return TRUE;
1863 }
1864 #endif
1865
1866 static gboolean
1867 set_unix_mode (char                       *filename,
1868                GFileQueryInfoFlags         flags,
1869                const GFileAttributeValue  *value,
1870                GError                    **error)
1871 {
1872   guint32 val;
1873   int res = 0;
1874   
1875   if (!get_uint32 (value, &val, error))
1876     return FALSE;
1877
1878 #ifdef HAVE_SYMLINK
1879   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) {
1880 #ifdef HAVE_LCHMOD
1881     res = lchmod (filename, val);
1882 #else
1883     struct stat statbuf;
1884     /* Calling chmod on a symlink changes permissions on the symlink.
1885      * We don't want to do this, so we need to check for a symlink */
1886     res = g_lstat (filename, &statbuf);
1887     if (res == 0 && S_ISLNK (statbuf.st_mode))
1888       {
1889         g_set_error_literal (error, G_IO_ERROR,
1890                              G_IO_ERROR_NOT_SUPPORTED,
1891                              _("Cannot set permissions on symlinks"));
1892         return FALSE;
1893       }
1894     else if (res == 0)
1895       res = g_chmod (filename, val);
1896 #endif
1897   } else
1898 #endif
1899     res = g_chmod (filename, val);
1900
1901   if (res == -1)
1902     {
1903       int errsv = errno;
1904
1905       g_set_error (error, G_IO_ERROR,
1906                    g_io_error_from_errno (errsv),
1907                    _("Error setting permissions: %s"),
1908                    g_strerror (errsv));
1909       return FALSE;
1910     }
1911   return TRUE;
1912 }
1913
1914 #ifdef HAVE_CHOWN
1915 static gboolean
1916 set_unix_uid_gid (char                       *filename,
1917                   const GFileAttributeValue  *uid_value,
1918                   const GFileAttributeValue  *gid_value,
1919                   GFileQueryInfoFlags         flags,
1920                   GError                    **error)
1921 {
1922   int res;
1923   guint32 val;
1924   uid_t uid;
1925   gid_t gid;
1926   
1927   if (uid_value)
1928     {
1929       if (!get_uint32 (uid_value, &val, error))
1930         return FALSE;
1931       uid = val;
1932     }
1933   else
1934     uid = -1;
1935   
1936   if (gid_value)
1937     {
1938       if (!get_uint32 (gid_value, &val, error))
1939         return FALSE;
1940       gid = val;
1941     }
1942   else
1943     gid = -1;
1944   
1945 #ifdef HAVE_LCHOWN
1946   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
1947     res = lchown (filename, uid, gid);
1948   else
1949 #endif
1950     res = chown (filename, uid, gid);
1951   
1952   if (res == -1)
1953     {
1954       int errsv = errno;
1955
1956       g_set_error (error, G_IO_ERROR,
1957                    g_io_error_from_errno (errsv),
1958                    _("Error setting owner: %s"),
1959                    g_strerror (errsv));
1960           return FALSE;
1961     }
1962   return TRUE;
1963 }
1964 #endif
1965
1966 #ifdef HAVE_SYMLINK
1967 static gboolean
1968 set_symlink (char                       *filename,
1969              const GFileAttributeValue  *value,
1970              GError                    **error)
1971 {
1972   const char *val;
1973   struct stat statbuf;
1974   
1975   if (!get_byte_string (value, &val, error))
1976     return FALSE;
1977   
1978   if (val == NULL)
1979     {
1980       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1981                            _("symlink must be non-NULL"));
1982       return FALSE;
1983     }
1984   
1985   if (g_lstat (filename, &statbuf))
1986     {
1987       int errsv = errno;
1988
1989       g_set_error (error, G_IO_ERROR,
1990                    g_io_error_from_errno (errsv),
1991                    _("Error setting symlink: %s"),
1992                    g_strerror (errsv));
1993       return FALSE;
1994     }
1995   
1996   if (!S_ISLNK (statbuf.st_mode))
1997     {
1998       g_set_error_literal (error, G_IO_ERROR,
1999                            G_IO_ERROR_NOT_SYMBOLIC_LINK,
2000                            _("Error setting symlink: file is not a symlink"));
2001       return FALSE;
2002     }
2003   
2004   if (g_unlink (filename))
2005     {
2006       int errsv = errno;
2007
2008       g_set_error (error, G_IO_ERROR,
2009                    g_io_error_from_errno (errsv),
2010                    _("Error setting symlink: %s"),
2011                    g_strerror (errsv));
2012       return FALSE;
2013     }
2014   
2015   if (symlink (filename, val) != 0)
2016     {
2017       int errsv = errno;
2018
2019       g_set_error (error, G_IO_ERROR,
2020                    g_io_error_from_errno (errsv),
2021                    _("Error setting symlink: %s"),
2022                    g_strerror (errsv));
2023       return FALSE;
2024     }
2025   
2026   return TRUE;
2027 }
2028 #endif
2029
2030 #ifdef HAVE_UTIMES
2031 static int
2032 lazy_stat (char        *filename, 
2033            struct stat *statbuf, 
2034            gboolean    *called_stat)
2035 {
2036   int res;
2037
2038   if (*called_stat)
2039     return 0;
2040   
2041   res = g_stat (filename, statbuf);
2042   
2043   if (res == 0)
2044     *called_stat = TRUE;
2045   
2046   return res;
2047 }
2048
2049
2050 static gboolean
2051 set_mtime_atime (char                       *filename,
2052                  const GFileAttributeValue  *mtime_value,
2053                  const GFileAttributeValue  *mtime_usec_value,
2054                  const GFileAttributeValue  *atime_value,
2055                  const GFileAttributeValue  *atime_usec_value,
2056                  GError                    **error)
2057 {
2058   int res;
2059   guint64 val;
2060   guint32 val_usec;
2061   struct stat statbuf;
2062   gboolean got_stat = FALSE;
2063   struct timeval times[2] = { {0, 0}, {0, 0} };
2064
2065   /* ATIME */
2066   if (atime_value)
2067     {
2068       if (!get_uint64 (atime_value, &val, error))
2069         return FALSE;
2070       times[0].tv_sec = val;
2071     }
2072   else
2073     {
2074       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2075         {
2076           times[0].tv_sec = statbuf.st_mtime;
2077 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
2078           times[0].tv_usec = statbuf.st_atimensec / 1000;
2079 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2080           times[0].tv_usec = statbuf.st_atim.tv_nsec / 1000;
2081 #endif
2082         }
2083     }
2084   
2085   if (atime_usec_value)
2086     {
2087       if (!get_uint32 (atime_usec_value, &val_usec, error))
2088         return FALSE;
2089       times[0].tv_usec = val_usec;
2090     }
2091
2092   /* MTIME */
2093   if (mtime_value)
2094     {
2095       if (!get_uint64 (mtime_value, &val, error))
2096         return FALSE;
2097       times[1].tv_sec = val;
2098     }
2099   else
2100     {
2101       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2102         {
2103           times[1].tv_sec = statbuf.st_mtime;
2104 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
2105           times[1].tv_usec = statbuf.st_mtimensec / 1000;
2106 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
2107           times[1].tv_usec = statbuf.st_mtim.tv_nsec / 1000;
2108 #endif
2109         }
2110     }
2111   
2112   if (mtime_usec_value)
2113     {
2114       if (!get_uint32 (mtime_usec_value, &val_usec, error))
2115         return FALSE;
2116       times[1].tv_usec = val_usec;
2117     }
2118   
2119   res = utimes (filename, times);
2120   if (res == -1)
2121     {
2122       int errsv = errno;
2123
2124       g_set_error (error, G_IO_ERROR,
2125                    g_io_error_from_errno (errsv),
2126                    _("Error setting modification or access time: %s"),
2127                    g_strerror (errsv));
2128           return FALSE;
2129     }
2130   return TRUE;
2131 }
2132 #endif
2133
2134
2135 #ifdef HAVE_SELINUX
2136 static gboolean
2137 set_selinux_context (char                       *filename,
2138                  const GFileAttributeValue  *value,
2139                  GError                    **error)
2140 {
2141   const char *val;
2142
2143   if (!get_string (value, &val, error))
2144     return FALSE;
2145
2146   if (val == NULL)
2147   {
2148     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2149                          _("SELinux context must be non-NULL"));
2150     return FALSE;
2151   }
2152
2153   if (is_selinux_enabled ()) {
2154         security_context_t val_s;
2155         
2156         val_s = g_strdup (val);
2157         
2158         if (setfilecon_raw (filename, val_s) < 0)
2159         {
2160             int errsv = errno;
2161             
2162             g_set_error (error, G_IO_ERROR,
2163                          g_io_error_from_errno (errsv),
2164                         _("Error setting SELinux context: %s"),
2165                          g_strerror (errsv));
2166             return FALSE;
2167         }
2168         g_free (val_s);
2169   } else {
2170     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2171                          _("SELinux is not enabled on this system"));
2172     return FALSE;
2173   }
2174                                                      
2175   return TRUE;
2176 }
2177 #endif 
2178
2179
2180 gboolean
2181 _g_local_file_info_set_attribute (char                 *filename,
2182                                   const char           *attribute,
2183                                   GFileAttributeType    type,
2184                                   gpointer              value_p,
2185                                   GFileQueryInfoFlags   flags,
2186                                   GCancellable         *cancellable,
2187                                   GError              **error)
2188 {
2189   GFileAttributeValue value = { 0 };
2190   GVfsClass *class;
2191   GVfs *vfs;
2192
2193   _g_file_attribute_value_set_from_pointer (&value, type, value_p, FALSE);
2194   
2195   if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
2196     return set_unix_mode (filename, flags, &value, error);
2197   
2198 #ifdef HAVE_CHOWN
2199   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_UID) == 0)
2200     return set_unix_uid_gid (filename, &value, NULL, flags, error);
2201   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_GID) == 0)
2202     return set_unix_uid_gid (filename, NULL, &value, flags, error);
2203 #endif
2204   
2205 #ifdef HAVE_SYMLINK
2206   else if (strcmp (attribute, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET) == 0)
2207     return set_symlink (filename, &value, error);
2208 #endif
2209
2210 #ifdef HAVE_UTIMES
2211   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED) == 0)
2212     return set_mtime_atime (filename, &value, NULL, NULL, NULL, error);
2213   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) == 0)
2214     return set_mtime_atime (filename, NULL, &value, NULL, NULL, error);
2215   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS) == 0)
2216     return set_mtime_atime (filename, NULL, NULL, &value, NULL, error);
2217   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) == 0)
2218     return set_mtime_atime (filename, NULL, NULL, NULL, &value, error);
2219 #endif
2220
2221 #ifdef HAVE_XATTR
2222   else if (g_str_has_prefix (attribute, "xattr::"))
2223     return set_xattr (filename, attribute, &value, error);
2224   else if (g_str_has_prefix (attribute, "xattr-sys::"))
2225     return set_xattr (filename, attribute, &value, error);
2226 #endif
2227
2228 #ifdef HAVE_SELINUX 
2229   else if (strcmp (attribute, G_FILE_ATTRIBUTE_SELINUX_CONTEXT) == 0)
2230     return set_selinux_context (filename, &value, error);
2231 #endif
2232
2233   vfs = g_vfs_get_default ();
2234   class = G_VFS_GET_CLASS (vfs);
2235   if (class->local_file_set_attributes)
2236     {
2237       GFileInfo *info;
2238
2239       info = g_file_info_new ();
2240       g_file_info_set_attribute (info,
2241                                  attribute,
2242                                  type,
2243                                  value_p);
2244       if (!class->local_file_set_attributes (vfs, filename,
2245                                              info,
2246                                              flags, cancellable,
2247                                              error))
2248         {
2249           g_object_unref (info);
2250           return FALSE;
2251         }
2252
2253       if (g_file_info_get_attribute_status (info, attribute) == G_FILE_ATTRIBUTE_STATUS_SET)
2254         {
2255           g_object_unref (info);
2256           return TRUE;
2257         }
2258
2259       g_object_unref (info);
2260     }
2261
2262   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2263                _("Setting attribute %s not supported"), attribute);
2264   return FALSE;
2265 }
2266
2267 gboolean
2268 _g_local_file_info_set_attributes  (char                 *filename,
2269                                     GFileInfo            *info,
2270                                     GFileQueryInfoFlags   flags,
2271                                     GCancellable         *cancellable,
2272                                     GError              **error)
2273 {
2274   GFileAttributeValue *value;
2275 #ifdef HAVE_CHOWN
2276   GFileAttributeValue *uid, *gid;
2277 #endif
2278 #ifdef HAVE_UTIMES
2279   GFileAttributeValue *mtime, *mtime_usec, *atime, *atime_usec;
2280 #endif
2281 #if defined (HAVE_CHOWN) || defined (HAVE_UTIMES)
2282   GFileAttributeStatus status;
2283 #endif
2284   gboolean res;
2285   GVfsClass *class;
2286   GVfs *vfs;
2287   
2288   /* Handles setting multiple specified data in a single set, and takes care
2289      of ordering restrictions when setting attributes */
2290
2291   res = TRUE;
2292
2293   /* Set symlink first, since this recreates the file */
2294 #ifdef HAVE_SYMLINK
2295   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET);
2296   if (value)
2297     {
2298       if (!set_symlink (filename, value, error))
2299         {
2300           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2301           res = FALSE;
2302           /* Don't set error multiple times */
2303           error = NULL;
2304         }
2305       else
2306         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2307         
2308     }
2309 #endif
2310
2311 #ifdef HAVE_CHOWN
2312   /* Group uid and gid setting into one call
2313    * Change ownership before permissions, since ownership changes can
2314      change permissions (e.g. setuid)
2315    */
2316   uid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_UID);
2317   gid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_GID);
2318   
2319   if (uid || gid)
2320     {
2321       if (!set_unix_uid_gid (filename, uid, gid, flags, error))
2322         {
2323           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2324           res = FALSE;
2325           /* Don't set error multiple times */
2326           error = NULL;
2327         }
2328       else
2329         status = G_FILE_ATTRIBUTE_STATUS_SET;
2330       if (uid)
2331         uid->status = status;
2332       if (gid)
2333         gid->status = status;
2334     }
2335 #endif
2336   
2337   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_MODE);
2338   if (value)
2339     {
2340       if (!set_unix_mode (filename, flags, value, error))
2341         {
2342           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2343           res = FALSE;
2344           /* Don't set error multiple times */
2345           error = NULL;
2346         }
2347       else
2348         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2349         
2350     }
2351
2352 #ifdef HAVE_UTIMES
2353   /* Group all time settings into one call
2354    * Change times as the last thing to avoid it changing due to metadata changes
2355    */
2356   
2357   mtime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
2358   mtime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
2359   atime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS);
2360   atime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC);
2361
2362   if (mtime || mtime_usec || atime || atime_usec)
2363     {
2364       if (!set_mtime_atime (filename, mtime, mtime_usec, atime, atime_usec, error))
2365         {
2366           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2367           res = FALSE;
2368           /* Don't set error multiple times */
2369           error = NULL;
2370         }
2371       else
2372         status = G_FILE_ATTRIBUTE_STATUS_SET;
2373       
2374       if (mtime)
2375         mtime->status = status;
2376       if (mtime_usec)
2377         mtime_usec->status = status;
2378       if (atime)
2379         atime->status = status;
2380       if (atime_usec)
2381         atime_usec->status = status;
2382     }
2383 #endif
2384
2385   /* xattrs are handled by default callback */
2386
2387
2388   /*  SELinux context */
2389 #ifdef HAVE_SELINUX 
2390   if (is_selinux_enabled ()) {
2391     value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_SELINUX_CONTEXT);
2392     if (value)
2393     {
2394       if (!set_selinux_context (filename, value, error))
2395         {
2396           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2397           res = FALSE;
2398           /* Don't set error multiple times */
2399           error = NULL;
2400         }
2401       else
2402         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2403     }
2404   }
2405 #endif
2406
2407   vfs = g_vfs_get_default ();
2408   class = G_VFS_GET_CLASS (vfs);
2409   if (class->local_file_set_attributes)
2410     {
2411       if (!class->local_file_set_attributes (vfs, filename,
2412                                              info,
2413                                              flags, cancellable,
2414                                              error))
2415         {
2416           res = FALSE;
2417           /* Don't set error multiple times */
2418           error = NULL;
2419         }
2420     }
2421
2422   return res;
2423 }