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