follow lib naming convention working implementation for user and group
[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 static 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 required */
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;\r
1292       BOOL defaulted;
1293       SID_NAME_USE name_use = 0; /* don't care? */
1294       wchar_t *name = NULL;\r
1295       wchar_t *domain = NULL;\r
1296       DWORD name_len = 0;\r
1297       DWORD domain_len = 0;\r
1298       /* get the user name */\r
1299       do {\r
1300         if (!user_name)\r
1301           break;\r
1302         if (!GetSecurityDescriptorOwner (psd, &psid, &defaulted))\r
1303           break;\r
1304         if (!LookupAccountSidW (NULL, /* local machine */\r
1305                                 psid, \r
1306                                 name, &name_len,\r
1307                                 domain, &domain_len, /* no domain info yet */\r
1308                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))\r
1309           break;\r
1310         name = g_try_malloc (name_len*sizeof(wchar_t));\r
1311         domain = g_try_malloc (domain_len*sizeof(wchar_t));\r
1312         if (name && domain &&\r
1313             LookupAccountSidW (NULL, /* local machine */\r
1314                                psid, \r
1315                                name, &name_len,\r
1316                                domain, &domain_len, /* no domain info yet */\r
1317                                &name_use))\r
1318           {\r
1319             *user_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);\r
1320           }\r
1321         g_free (name);\r
1322         g_free (domain);\r
1323       } while (FALSE);\r
1324 \r
1325       /* get the group name */\r
1326       do {\r
1327         if (!group_name)\r
1328           break;\r
1329         if (!GetSecurityDescriptorGroup (psd, &psid, &defaulted))\r
1330           break;\r
1331         if (!LookupAccountSidW (NULL, /* local machine */\r
1332                                 psid, \r
1333                                 name, &name_len,\r
1334                                 domain, &domain_len, /* no domain info yet */\r
1335                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))\r
1336           break;\r
1337         name = g_try_malloc (name_len*sizeof(wchar_t));\r
1338         domain = g_try_malloc (domain_len*sizeof(wchar_t));\r
1339         if (name && domain &&\r
1340             LookupAccountSidW (NULL, /* local machine */\r
1341                                psid, \r
1342                                name, &name_len,\r
1343                                domain, &domain_len, /* no domain info yet */\r
1344                                &name_use))\r
1345           {\r
1346             *group_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);\r
1347           }\r
1348         g_free (name);\r
1349         g_free (domain);\r
1350       } while (FALSE);\r
1351 \r
1352       /* TODO: get real name */\r
1353 \r
1354       g_free (psd);\r
1355     }
1356   g_free (wfilename);
1357 }
1358 #endif /* G_OS_WIN32 */
1359
1360 GFileInfo *
1361 _g_local_file_info_get (const char             *basename,
1362                         const char             *path,
1363                         GFileAttributeMatcher  *attribute_matcher,
1364                         GFileQueryInfoFlags     flags,
1365                         GLocalParentFileInfo   *parent_info,
1366                         GError                **error)
1367 {
1368   GFileInfo *info;
1369   struct stat statbuf;
1370   struct stat statbuf2;
1371   int res;
1372   gboolean is_symlink, symlink_broken;
1373
1374   info = g_file_info_new ();
1375
1376   /* Make sure we don't set any unwanted attributes */
1377   g_file_info_set_attribute_mask (info, attribute_matcher);
1378   
1379   g_file_info_set_name (info, basename);
1380
1381   /* Avoid stat in trivial case */
1382   if (attribute_matcher == NULL)
1383     return info;
1384
1385   res = g_lstat (path, &statbuf);
1386   if (res == -1)
1387     {
1388       g_object_unref (info);
1389       g_set_error (error, G_IO_ERROR,
1390                    g_io_error_from_errno (errno),
1391                    _("Error stating file '%s': %s"),
1392                    path, g_strerror (errno));
1393       return NULL;
1394     }
1395   
1396 #ifdef S_ISLNK
1397   is_symlink = S_ISLNK (statbuf.st_mode);
1398 #else
1399   is_symlink = FALSE;
1400 #endif
1401   symlink_broken = FALSE;
1402   
1403   if (is_symlink)
1404     {
1405       g_file_info_set_is_symlink (info, TRUE);
1406
1407       /* Unless NOFOLLOW was set we default to following symlinks */
1408       if (!(flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS))
1409         {
1410           res = stat (path, &statbuf2);
1411
1412             /* Report broken links as symlinks */
1413           if (res != -1)
1414             statbuf = statbuf2;
1415           else
1416             symlink_broken = TRUE;
1417         }
1418     }
1419
1420   set_info_from_stat (info, &statbuf, attribute_matcher);
1421   
1422   if (basename != NULL && basename[0] == '.')
1423     g_file_info_set_is_hidden (info, TRUE);
1424
1425   if (basename != NULL && basename[strlen (basename) -1] == '~')
1426     g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_STD_IS_BACKUP, TRUE);
1427
1428   if (is_symlink &&
1429       g_file_attribute_matcher_matches (attribute_matcher,
1430                                         G_FILE_ATTRIBUTE_STD_SYMLINK_TARGET))
1431     {
1432       char *link = read_link (path);
1433       g_file_info_set_symlink_target (info, link);
1434       g_free (link);
1435     }
1436
1437   if (g_file_attribute_matcher_matches (attribute_matcher,
1438                                         G_FILE_ATTRIBUTE_STD_DISPLAY_NAME))
1439     {
1440       char *display_name = g_filename_display_basename (path);
1441       
1442       if (strstr (display_name, "\357\277\275") != NULL)
1443         {
1444           char *p = display_name;
1445           display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
1446           g_free (p);
1447         }
1448       g_file_info_set_display_name (info, display_name);
1449       g_free (display_name);
1450     }
1451   
1452   if (g_file_attribute_matcher_matches (attribute_matcher,
1453                                         G_FILE_ATTRIBUTE_STD_EDIT_NAME))
1454     {
1455       char *edit_name = g_filename_display_basename (path);
1456       g_file_info_set_edit_name (info, edit_name);
1457       g_free (edit_name);
1458     }
1459
1460   
1461   if (g_file_attribute_matcher_matches (attribute_matcher,
1462                                         G_FILE_ATTRIBUTE_STD_COPY_NAME))
1463     {
1464       char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
1465       if (copy_name)
1466         g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_STD_COPY_NAME, copy_name);
1467       g_free (copy_name);
1468     }
1469
1470   if (g_file_attribute_matcher_matches (attribute_matcher,
1471                                         G_FILE_ATTRIBUTE_STD_CONTENT_TYPE) ||
1472       g_file_attribute_matcher_matches (attribute_matcher,
1473                                         G_FILE_ATTRIBUTE_STD_ICON))
1474     {
1475       char *content_type = get_content_type (basename, path, &statbuf, is_symlink, symlink_broken, flags, FALSE);
1476
1477       if (content_type)
1478         {
1479           g_file_info_set_content_type (info, content_type);
1480
1481           if (g_file_attribute_matcher_matches (attribute_matcher,
1482                                                 G_FILE_ATTRIBUTE_STD_ICON))
1483             {
1484               char *mimetype_icon, *generic_mimetype_icon, *type_icon, *p;
1485               char *icon_names[3];
1486               GIcon *icon;
1487               int i;
1488
1489               mimetype_icon = g_strdup (content_type);
1490               
1491               while ((p = strchr(mimetype_icon, '/')) != NULL)
1492                 *p = '-';
1493
1494               p = strchr (content_type, '/');
1495               if (p == NULL)
1496                 p = content_type + strlen (content_type);
1497
1498               generic_mimetype_icon = g_malloc (p - content_type + strlen ("-x-generic") + 1);
1499               memcpy (generic_mimetype_icon, content_type, p - content_type);
1500               memcpy (generic_mimetype_icon + (p - content_type), "-x-generic", strlen ("-x-generic"));
1501               generic_mimetype_icon[(p - content_type) + strlen ("-x-generic")] = 0;
1502
1503               /* TODO: Special case desktop dir? That could be expensive with xdg dirs... */
1504               if (strcmp (path, g_get_home_dir ()) == 0)
1505                 type_icon = "user-home";
1506               else if (S_ISDIR (statbuf.st_mode)) 
1507                 type_icon = "folder";
1508               else if (statbuf.st_mode & S_IXUSR)
1509                 type_icon = "application-x-executable";
1510               else
1511                 type_icon = "text-x-generic";
1512
1513               i = 0;
1514               icon_names[i++] = mimetype_icon;
1515               icon_names[i++] = generic_mimetype_icon;
1516               if (strcmp (generic_mimetype_icon, type_icon) != 0 &&
1517                   strcmp (mimetype_icon, type_icon) != 0) 
1518                 icon_names[i++] = type_icon;
1519               
1520               icon = g_themed_icon_new_from_names (icon_names, i);
1521               g_file_info_set_icon (info, icon);
1522               
1523               g_object_unref (icon);
1524               g_free (mimetype_icon);
1525               g_free (generic_mimetype_icon);
1526             }
1527           
1528           g_free (content_type);
1529         }
1530     }
1531
1532   if (g_file_attribute_matcher_matches (attribute_matcher,
1533                                         G_FILE_ATTRIBUTE_STD_FAST_CONTENT_TYPE))
1534     {
1535       char *content_type = get_content_type (basename, path, &statbuf, is_symlink, symlink_broken, flags, TRUE);
1536       
1537       if (content_type)
1538         {
1539           g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_STD_FAST_CONTENT_TYPE, content_type);
1540           g_free (content_type);
1541         }
1542     }
1543
1544   if (g_file_attribute_matcher_matches (attribute_matcher,
1545                                         G_FILE_ATTRIBUTE_OWNER_USER))
1546     {
1547       char *name = NULL;
1548       
1549 #ifdef G_OS_WIN32
1550       win32_get_file_user_info (path, NULL, &name, NULL);
1551 #else
1552       name = get_username_from_uid (statbuf.st_uid);
1553 #endif
1554       if (name)
1555         g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_OWNER_USER, name);
1556       g_free (name);
1557     }
1558
1559   if (g_file_attribute_matcher_matches (attribute_matcher,
1560                                         G_FILE_ATTRIBUTE_OWNER_USER_REAL))
1561     {
1562       char *name = NULL;
1563 #ifdef G_OS_WIN32
1564       win32_get_file_user_info (path, NULL, NULL, &name);
1565 #else
1566       name = get_realname_from_uid (statbuf.st_uid);
1567 #endif
1568       if (name)
1569         g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_OWNER_USER_REAL, name);
1570       g_free (name);
1571     }
1572   
1573   if (g_file_attribute_matcher_matches (attribute_matcher,
1574                                         G_FILE_ATTRIBUTE_OWNER_GROUP))
1575     {
1576       char *name = NULL;
1577 #ifdef G_OS_WIN32
1578       win32_get_file_user_info (path, &name, NULL, NULL);
1579 #else
1580       name = get_groupname_from_gid (statbuf.st_gid);
1581 #endif
1582       if (name)
1583         g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_OWNER_GROUP, name);
1584       g_free (name);
1585     }
1586
1587   if (parent_info && parent_info->device != 0 &&
1588       g_file_attribute_matcher_matches (attribute_matcher, G_FILE_ATTRIBUTE_UNIX_IS_MOUNTPOINT) &&
1589       statbuf.st_dev != parent_info->device) 
1590     g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_UNIX_IS_MOUNTPOINT, TRUE);
1591   
1592   get_access_rights (attribute_matcher, info, path, &statbuf, parent_info);
1593   
1594   get_selinux_context (path, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1595   get_xattrs (path, TRUE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1596   get_xattrs (path, FALSE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1597
1598   if (g_file_attribute_matcher_matches (attribute_matcher,
1599                                         G_FILE_ATTRIBUTE_THUMBNAIL_PATH))
1600     get_thumbnail_attributes (path, info);
1601   
1602   g_file_info_unset_attribute_mask (info);
1603
1604   return info;
1605 }
1606
1607 GFileInfo *
1608 _g_local_file_info_get_from_fd (int      fd,
1609                                 char    *attributes,
1610                                 GError **error)
1611 {
1612   struct stat stat_buf;
1613   GFileAttributeMatcher *matcher;
1614   GFileInfo *info;
1615   
1616   if (fstat (fd, &stat_buf) == -1)
1617     {
1618       g_set_error (error, G_IO_ERROR,
1619                    g_io_error_from_errno (errno),
1620                    _("Error stating file descriptor: %s"),
1621                    g_strerror (errno));
1622       return NULL;
1623     }
1624
1625   info = g_file_info_new ();
1626
1627   matcher = g_file_attribute_matcher_new (attributes);
1628
1629   /* Make sure we don't set any unwanted attributes */
1630   g_file_info_set_attribute_mask (info, matcher);
1631   
1632   set_info_from_stat (info, &stat_buf, matcher);
1633   
1634 #ifdef HAVE_SELINUX
1635   if (g_file_attribute_matcher_matches (matcher, "selinux:context") &&
1636       is_selinux_enabled ())
1637     {
1638       char *context;
1639       if (fgetfilecon_raw (fd, &context) >= 0)
1640         {
1641           g_file_info_set_attribute_string (info, "selinux:context", context);
1642           freecon(context);
1643         }
1644     }
1645 #endif
1646
1647   get_xattrs_from_fd (fd, TRUE, info, matcher);
1648   get_xattrs_from_fd (fd, FALSE, info, matcher);
1649   
1650   g_file_attribute_matcher_unref (matcher);
1651
1652   g_file_info_unset_attribute_mask (info);
1653   
1654   return info;
1655 }
1656
1657 static gboolean
1658 get_uint32 (const GFileAttributeValue  *value,
1659             guint32                    *val_out,
1660             GError                    **error)
1661 {
1662   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT32)
1663     {
1664       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1665                    _("Invalid attribute type (uint32 expected)"));
1666       return FALSE;
1667     }
1668
1669   *val_out = value->u.uint32;
1670   
1671   return TRUE;
1672 }
1673
1674 static gboolean
1675 get_uint64 (const GFileAttributeValue  *value,
1676             guint64                    *val_out,
1677             GError                    **error)
1678 {
1679   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT64)
1680     {
1681       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1682                    _("Invalid attribute type (uint64 expected)"));
1683       return FALSE;
1684     }
1685
1686   *val_out = value->u.uint64;
1687   
1688   return TRUE;
1689 }
1690
1691 #if defined(HAVE_SYMLINK)
1692 static gboolean
1693 get_byte_string (const GFileAttributeValue  *value,
1694                  const char                **val_out,
1695                  GError                    **error)
1696 {
1697   if (value->type != G_FILE_ATTRIBUTE_TYPE_BYTE_STRING)
1698     {
1699       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1700                    _("Invalid attribute type (byte string expected)"));
1701       return FALSE;
1702     }
1703
1704   *val_out = value->u.string;
1705   
1706   return TRUE;
1707 }
1708 #endif
1709
1710 static gboolean
1711 set_unix_mode (char                       *filename,
1712                const GFileAttributeValue  *value,
1713                GError                    **error)
1714 {
1715   guint32 val;
1716   
1717   if (!get_uint32 (value, &val, error))
1718     return FALSE;
1719   
1720   if (g_chmod (filename, val) == -1)
1721     {
1722       g_set_error (error, G_IO_ERROR,
1723                    g_io_error_from_errno (errno),
1724                    _("Error setting permissions: %s"),
1725                    g_strerror (errno));
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   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
1763     res = lchown (filename, uid, gid);
1764   else
1765     res = chown (filename, uid, gid);
1766   
1767   if (res == -1)
1768     {
1769       g_set_error (error, G_IO_ERROR,
1770                    g_io_error_from_errno (errno),
1771                    _("Error setting owner: %s"),
1772                    g_strerror (errno));
1773           return FALSE;
1774     }
1775   return TRUE;
1776 }
1777 #endif
1778
1779 #ifdef HAVE_SYMLINK
1780 static gboolean
1781 set_symlink (char                       *filename,
1782              const GFileAttributeValue  *value,
1783              GError                    **error)
1784 {
1785   const char *val;
1786   struct stat statbuf;
1787   
1788   if (!get_byte_string (value, &val, error))
1789     return FALSE;
1790   
1791   if (val == NULL)
1792     {
1793       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1794                    _("symlink must be non-NULL"));
1795       return FALSE;
1796     }
1797   
1798   if (g_lstat (filename, &statbuf))
1799     {
1800       g_set_error (error, G_IO_ERROR,
1801                    g_io_error_from_errno (errno),
1802                    _("Error setting symlink: %s"),
1803                    g_strerror (errno));
1804       return FALSE;
1805     }
1806   
1807   if (!S_ISLNK (statbuf.st_mode))
1808     {
1809       g_set_error (error, G_IO_ERROR,
1810                    G_IO_ERROR_NOT_SYMBOLIC_LINK,
1811                    _("Error setting symlink: file is not a symlink"));
1812       return FALSE;
1813     }
1814   
1815   if (g_unlink (filename))
1816     {
1817       g_set_error (error, G_IO_ERROR,
1818                    g_io_error_from_errno (errno),
1819                    _("Error setting symlink: %s"),
1820                    g_strerror (errno));
1821       return FALSE;
1822     }
1823   
1824   if (symlink (filename, val) != 0)
1825     {
1826       g_set_error (error, G_IO_ERROR,
1827                    g_io_error_from_errno (errno),
1828                    _("Error setting symlink: %s"),
1829                    g_strerror (errno));
1830       return FALSE;
1831     }
1832   
1833   return TRUE;
1834 }
1835 #endif
1836
1837 static int
1838 lazy_stat (char        *filename, 
1839            struct stat *statbuf, 
1840            gboolean    *called_stat)
1841 {
1842   int res;
1843
1844   if (*called_stat)
1845     return 0;
1846   
1847   res = g_stat (filename, statbuf);
1848   
1849   if (res == 0)
1850     *called_stat = TRUE;
1851   
1852   return res;
1853 }
1854
1855
1856 #ifdef HAVE_UTIMES
1857 static gboolean
1858 set_mtime_atime (char                       *filename,
1859                  const GFileAttributeValue  *mtime_value,
1860                  const GFileAttributeValue  *mtime_usec_value,
1861                  const GFileAttributeValue  *atime_value,
1862                  const GFileAttributeValue  *atime_usec_value,
1863                  GError                    **error)
1864 {
1865   int res;
1866   guint64 val;
1867   guint32 val_usec;
1868   struct stat statbuf;
1869   gboolean got_stat = FALSE;
1870   struct timeval times[2] = { {0, 0}, {0, 0} };
1871
1872   /* ATIME */
1873   if (atime_value)
1874     {
1875       if (!get_uint64 (atime_value, &val, error))
1876         return FALSE;
1877       times[0].tv_sec = val;
1878     }
1879   else
1880     {
1881       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
1882         {
1883           times[0].tv_sec = statbuf.st_mtime;
1884 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
1885           times[0].tv_usec = statbuf.st_atimensec / 1000;
1886 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1887           times[0].tv_usec = statbuf.st_atim.tv_nsec / 1000;
1888 #endif
1889         }
1890     }
1891   
1892   if (atime_usec_value)
1893     {
1894       if (!get_uint32 (atime_usec_value, &val_usec, error))
1895         return FALSE;
1896       times[0].tv_usec = val_usec;
1897     }
1898
1899   /* MTIME */
1900   if (mtime_value)
1901     {
1902       if (!get_uint64 (mtime_value, &val, error))
1903         return FALSE;
1904       times[1].tv_sec = val;
1905     }
1906   else
1907     {
1908       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
1909         {
1910           times[1].tv_sec = statbuf.st_mtime;
1911 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
1912           times[1].tv_usec = statbuf.st_mtimensec / 1000;
1913 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
1914           times[1].tv_usec = statbuf.st_mtim.tv_nsec / 1000;
1915 #endif
1916         }
1917     }
1918   
1919   if (mtime_usec_value)
1920     {
1921       if (!get_uint32 (mtime_usec_value, &val_usec, error))
1922         return FALSE;
1923       times[1].tv_usec = val_usec;
1924     }
1925   
1926   res = utimes(filename, times);
1927   if (res == -1)
1928     {
1929       g_set_error (error, G_IO_ERROR,
1930                    g_io_error_from_errno (errno),
1931                    _("Error setting owner: %s"),
1932                    g_strerror (errno));
1933           return FALSE;
1934     }
1935   return TRUE;
1936 }
1937 #endif
1938
1939 gboolean
1940 _g_local_file_info_set_attribute (char                       *filename,
1941                                   const char                 *attribute,
1942                                   const GFileAttributeValue  *value,
1943                                   GFileQueryInfoFlags         flags,
1944                                   GCancellable               *cancellable,
1945                                   GError                    **error)
1946 {
1947   if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
1948     return set_unix_mode (filename, value, error);
1949   
1950 #ifdef HAVE_CHOWN
1951   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_UID) == 0)
1952     return set_unix_uid_gid (filename, value, NULL, flags, error);
1953   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_GID) == 0)
1954     return set_unix_uid_gid (filename, NULL, value, flags, error);
1955 #endif
1956   
1957 #ifdef HAVE_SYMLINK
1958   else if (strcmp (attribute, G_FILE_ATTRIBUTE_STD_SYMLINK_TARGET) == 0)
1959     return set_symlink (filename, value, error);
1960 #endif
1961
1962 #ifdef HAVE_UTIMES
1963   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED) == 0)
1964     return set_mtime_atime (filename, value, NULL, NULL, NULL, error);
1965   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) == 0)
1966     return set_mtime_atime (filename, NULL, value, NULL, NULL, error);
1967   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS) == 0)
1968     return set_mtime_atime (filename, NULL, NULL, value, NULL, error);
1969   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) == 0)
1970     return set_mtime_atime (filename, NULL, NULL, NULL, value, error);
1971 #endif
1972
1973 #ifdef HAVE_XATTR
1974   else if (g_str_has_prefix (attribute, "xattr:"))
1975     return set_xattr (filename, attribute, value, error);
1976   else if (g_str_has_prefix (attribute, "xattr_sys:"))
1977     return set_xattr (filename, attribute, value, error);
1978 #endif
1979   
1980   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1981                _("Setting attribute %s not supported"), attribute);
1982   return FALSE;
1983 }
1984
1985 gboolean
1986 _g_local_file_info_set_attributes  (char                 *filename,
1987                                     GFileInfo            *info,
1988                                     GFileQueryInfoFlags   flags,
1989                                     GCancellable         *cancellable,
1990                                     GError              **error)
1991 {
1992   GFileAttributeValue *value, *uid, *gid;
1993   GFileAttributeValue *mtime, *mtime_usec, *atime, *atime_usec;
1994   GFileAttributeStatus status;
1995   gboolean res;
1996   
1997   /* Handles setting multiple specified data in a single set, and takes care
1998      of ordering restrictions when setting attributes */
1999
2000   res = TRUE;
2001
2002   /* Set symlink first, since this recreates the file */
2003 #ifdef HAVE_SYMLINK
2004   value = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_STD_SYMLINK_TARGET);
2005   if (value)
2006     {
2007       if (!set_symlink (filename, value, error))
2008         {
2009           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2010           res = FALSE;
2011           /* Don't set error multiple times */
2012           error = NULL;
2013         }
2014       else
2015         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2016         
2017     }
2018 #endif
2019
2020 #ifdef HAVE_CHOWN
2021   /* Group uid and gid setting into one call
2022    * Change ownership before permissions, since ownership changes can
2023      change permissions (e.g. setuid)
2024    */
2025   uid = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_UNIX_UID);
2026   gid = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_UNIX_GID);
2027   
2028   if (uid || gid)
2029     {
2030       if (!set_unix_uid_gid (filename, uid, gid, flags, 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       if (uid)
2040         uid->status = status;
2041       if (gid)
2042         gid->status = status;
2043     }
2044 #endif
2045   
2046   value = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE);
2047   if (value)
2048     {
2049       if (!set_unix_mode (filename, value, error))
2050         {
2051           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2052           res = FALSE;
2053           /* Don't set error multiple times */
2054           error = NULL;
2055         }
2056       else
2057         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2058         
2059     }
2060
2061 #ifdef HAVE_UTIMES
2062   /* Group all time settings into one call
2063    * Change times as the last thing to avoid it changing due to metadata changes
2064    */
2065   
2066   mtime = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
2067   mtime_usec = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
2068   atime = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_TIME_ACCESS);
2069   atime_usec = g_file_info_get_attribute (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC);
2070
2071   if (mtime || mtime_usec || atime || atime_usec)
2072     {
2073       if (!set_mtime_atime (filename, mtime, mtime_usec, atime, atime_usec, error))
2074         {
2075           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2076           res = FALSE;
2077           /* Don't set error multiple times */
2078           error = NULL;
2079         }
2080       else
2081         status = G_FILE_ATTRIBUTE_STATUS_SET;
2082       
2083       if (mtime)
2084         mtime->status = status;
2085       if (mtime_usec)
2086         mtime_usec->status = status;
2087       if (atime)
2088         atime->status = status;
2089       if (atime_usec)
2090         atime_usec->status = status;
2091     }
2092 #endif
2093
2094   /* xattrs are handled by default callback */
2095
2096   return res;
2097 }