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