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