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