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