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