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