Fix compilation on Android with the bionic C library
[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 #ifndef __BIONIC__
1102       gecos = pwbufp->pw_gecos;
1103
1104       if (gecos)
1105         {
1106           comma = strchr (gecos, ',');
1107           if (comma)
1108             *comma = 0;
1109           data->real_name = convert_pwd_string_to_utf8 (gecos);
1110         }
1111 #endif
1112     }
1113
1114   /* Default fallbacks */
1115   if (data->real_name == NULL)
1116     {
1117       if (data->user_name != NULL)
1118         data->real_name = g_strdup (data->user_name);
1119       else
1120         data->real_name = g_strdup_printf ("user #%d", (int)uid);
1121     }
1122   
1123   if (data->user_name == NULL)
1124     data->user_name = g_strdup_printf ("%d", (int)uid);
1125   
1126   g_hash_table_replace (uid_cache, GINT_TO_POINTER (uid), data);
1127   
1128   return data;
1129 }
1130
1131 static char *
1132 get_username_from_uid (uid_t uid)
1133 {
1134   char *res;
1135   UidData *data;
1136   
1137   G_LOCK (uid_cache);
1138   data = lookup_uid_data (uid);
1139   res = g_strdup (data->user_name);  
1140   G_UNLOCK (uid_cache);
1141
1142   return res;
1143 }
1144
1145 static char *
1146 get_realname_from_uid (uid_t uid)
1147 {
1148   char *res;
1149   UidData *data;
1150   
1151   G_LOCK (uid_cache);
1152   data = lookup_uid_data (uid);
1153   res = g_strdup (data->real_name);  
1154   G_UNLOCK (uid_cache);
1155   
1156   return res;
1157 }
1158
1159 /* called with lock held */
1160 static char *
1161 lookup_gid_name (gid_t gid)
1162 {
1163   char *name;
1164   char buffer[4096];
1165   struct group gbuf;
1166   struct group *gbufp;
1167   
1168   if (gid_cache == NULL)
1169     gid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_free);
1170
1171   name = g_hash_table_lookup (gid_cache, GINT_TO_POINTER (gid));
1172
1173   if (name)
1174     return name;
1175
1176 #if defined (HAVE_POSIX_GETGRGID_R)
1177   getgrgid_r (gid, &gbuf, buffer, sizeof(buffer), &gbufp);
1178 #elif defined (HAVE_NONPOSIX_GETGRGID_R)
1179   gbufp = getgrgid_r (gid, &gbuf, buffer, sizeof(buffer));
1180 #else
1181   gbufp = getgrgid (gid);
1182 #endif
1183
1184   if (gbufp != NULL &&
1185       gbufp->gr_name != NULL &&
1186       gbufp->gr_name[0] != 0)
1187     name = convert_pwd_string_to_utf8 (gbufp->gr_name);
1188   else
1189     name = g_strdup_printf("%d", (int)gid);
1190   
1191   g_hash_table_replace (gid_cache, GINT_TO_POINTER (gid), name);
1192   
1193   return name;
1194 }
1195
1196 static char *
1197 get_groupname_from_gid (gid_t gid)
1198 {
1199   char *res;
1200   char *name;
1201   
1202   G_LOCK (gid_cache);
1203   name = lookup_gid_name (gid);
1204   res = g_strdup (name);  
1205   G_UNLOCK (gid_cache);
1206   return res;
1207 }
1208
1209 #endif /* !G_OS_WIN32 */
1210
1211 static char *
1212 get_content_type (const char          *basename,
1213                   const char          *path,
1214                   GLocalFileStat      *statbuf,
1215                   gboolean             is_symlink,
1216                   gboolean             symlink_broken,
1217                   GFileQueryInfoFlags  flags,
1218                   gboolean             fast)
1219 {
1220   if (is_symlink &&
1221       (symlink_broken || (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)))
1222     return g_strdup ("inode/symlink");
1223   else if (statbuf != NULL && S_ISDIR(statbuf->st_mode))
1224     return g_strdup ("inode/directory");
1225 #ifndef G_OS_WIN32
1226   else if (statbuf != NULL && S_ISCHR(statbuf->st_mode))
1227     return g_strdup ("inode/chardevice");
1228   else if (statbuf != NULL && S_ISBLK(statbuf->st_mode))
1229     return g_strdup ("inode/blockdevice");
1230   else if (statbuf != NULL && S_ISFIFO(statbuf->st_mode))
1231     return g_strdup ("inode/fifo");
1232 #endif
1233 #ifdef S_ISSOCK
1234   else if (statbuf != NULL && S_ISSOCK(statbuf->st_mode))
1235     return g_strdup ("inode/socket");
1236 #endif
1237   else
1238     {
1239       char *content_type;
1240       gboolean result_uncertain;
1241       
1242       content_type = g_content_type_guess (basename, NULL, 0, &result_uncertain);
1243       
1244 #ifndef G_OS_WIN32
1245       if (!fast && result_uncertain && path != NULL)
1246         {
1247           guchar sniff_buffer[4096];
1248           gsize sniff_length;
1249           int fd;
1250
1251           sniff_length = _g_unix_content_type_get_sniff_len ();
1252           if (sniff_length > 4096)
1253             sniff_length = 4096;
1254
1255 #ifdef O_NOATIME          
1256           fd = g_open (path, O_RDONLY | O_NOATIME, 0);
1257           if (fd < 0 && errno == EPERM)
1258 #endif
1259             fd = g_open (path, O_RDONLY, 0);
1260
1261           if (fd != -1)
1262             {
1263               ssize_t res;
1264               
1265               res = read (fd, sniff_buffer, sniff_length);
1266               (void) g_close (fd, NULL);
1267               if (res >= 0)
1268                 {
1269                   g_free (content_type);
1270                   content_type = g_content_type_guess (basename, sniff_buffer, res, NULL);
1271                 }
1272             }
1273         }
1274 #endif
1275       
1276       return content_type;
1277     }
1278   
1279 }
1280
1281 static void
1282 get_thumbnail_attributes (const char *path,
1283                           GFileInfo  *info)
1284 {
1285   GChecksum *checksum;
1286   char *uri;
1287   char *filename;
1288   char *basename;
1289
1290   uri = g_filename_to_uri (path, NULL, NULL);
1291
1292   checksum = g_checksum_new (G_CHECKSUM_MD5);
1293   g_checksum_update (checksum, (const guchar *) uri, strlen (uri));
1294   
1295   g_free (uri);
1296
1297   basename = g_strconcat (g_checksum_get_string (checksum), ".png", NULL);
1298   g_checksum_free (checksum);
1299
1300   filename = g_build_filename (g_get_user_cache_dir (),
1301                                "thumbnails", "large", basename,
1302                                NULL);
1303
1304   if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1305     _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1306   else
1307     {
1308       g_free (filename);
1309       filename = g_build_filename (g_get_user_cache_dir (),
1310                                    "thumbnails", "normal", basename,
1311                                    NULL);
1312
1313       if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1314         _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1315       else
1316         {
1317           g_free (filename);
1318           filename = g_build_filename (g_get_user_cache_dir (),
1319                                        "thumbnails", "fail",
1320                                        "gnome-thumbnail-factory",
1321                                        basename,
1322                                        NULL);
1323
1324           if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1325             _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAILING_FAILED, TRUE);
1326         }
1327     }
1328   g_free (basename);
1329   g_free (filename);
1330 }
1331
1332 #ifdef G_OS_WIN32
1333 static void
1334 win32_get_file_user_info (const gchar  *filename,
1335                           gchar       **group_name, 
1336                           gchar       **user_name, 
1337                           gchar       **real_name)
1338 {
1339   PSECURITY_DESCRIPTOR psd = NULL;
1340   DWORD sd_size = 0; /* first call calculates the size required */
1341   
1342   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1343   if ((GetFileSecurityW (wfilename, 
1344                         GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1345                         NULL,
1346                         sd_size,
1347                         &sd_size) || (ERROR_INSUFFICIENT_BUFFER == GetLastError())) &&
1348      (psd = g_try_malloc (sd_size)) != NULL &&
1349      GetFileSecurityW (wfilename, 
1350                        GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1351                        psd,
1352                        sd_size,
1353                        &sd_size))
1354     {
1355       PSID psid = 0;
1356       BOOL defaulted;
1357       SID_NAME_USE name_use = 0; /* don't care? */
1358       wchar_t *name = NULL;
1359       wchar_t *domain = NULL;
1360       DWORD name_len = 0;
1361       DWORD domain_len = 0;
1362       /* get the user name */
1363       do {
1364         if (!user_name)
1365           break;
1366         if (!GetSecurityDescriptorOwner (psd, &psid, &defaulted))
1367           break;
1368         if (!LookupAccountSidW (NULL, /* local machine */
1369                                 psid, 
1370                                 name, &name_len,
1371                                 domain, &domain_len, /* no domain info yet */
1372                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1373           break;
1374         name = g_try_malloc (name_len * sizeof (wchar_t));
1375         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1376         if (name && domain &&
1377             LookupAccountSidW (NULL, /* local machine */
1378                                psid, 
1379                                name, &name_len,
1380                                domain, &domain_len, /* no domain info yet */
1381                                &name_use))
1382           {
1383             *user_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1384           }
1385         g_free (name);
1386         g_free (domain);
1387       } while (FALSE);
1388
1389       /* get the group name */
1390       do {
1391         if (!group_name)
1392           break;
1393         if (!GetSecurityDescriptorGroup (psd, &psid, &defaulted))
1394           break;
1395         if (!LookupAccountSidW (NULL, /* local machine */
1396                                 psid, 
1397                                 name, &name_len,
1398                                 domain, &domain_len, /* no domain info yet */
1399                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1400           break;
1401         name = g_try_malloc (name_len * sizeof (wchar_t));
1402         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1403         if (name && domain &&
1404             LookupAccountSidW (NULL, /* local machine */
1405                                psid, 
1406                                name, &name_len,
1407                                domain, &domain_len, /* no domain info yet */
1408                                &name_use))
1409           {
1410             *group_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1411           }
1412         g_free (name);
1413         g_free (domain);
1414       } while (FALSE);
1415
1416       /* TODO: get real name */
1417
1418       g_free (psd);
1419     }
1420   g_free (wfilename);
1421 }
1422 #endif /* G_OS_WIN32 */
1423
1424 #ifndef G_OS_WIN32
1425 /* support for '.hidden' files */
1426 G_LOCK_DEFINE_STATIC (hidden_cache);
1427 static GHashTable *hidden_cache;
1428
1429 static gboolean
1430 remove_from_hidden_cache (gpointer user_data)
1431 {
1432   G_LOCK (hidden_cache);
1433   g_hash_table_remove (hidden_cache, user_data);
1434   G_UNLOCK (hidden_cache);
1435
1436   return FALSE;
1437 }
1438
1439 static GHashTable *
1440 read_hidden_file (const gchar *dirname)
1441 {
1442   gchar *contents = NULL;
1443   gchar *filename;
1444
1445   filename = g_build_path ("/", dirname, ".hidden", NULL);
1446   g_file_get_contents (filename, &contents, NULL, NULL);
1447   g_free (filename);
1448
1449   if (contents != NULL)
1450     {
1451       GHashTable *table;
1452       gchar **lines;
1453       gint i;
1454
1455       table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1456
1457       lines = g_strsplit (contents, "\n", 0);
1458       g_free (contents);
1459
1460       for (i = 0; lines[i]; i++)
1461         /* hash table takes the individual strings... */
1462         g_hash_table_add (table, lines[i]);
1463
1464       /* ... so we only free the container. */
1465       g_free (lines);
1466
1467       return table;
1468     }
1469   else
1470     return NULL;
1471 }
1472
1473 static void
1474 maybe_unref_hash_table (gpointer data)
1475 {
1476   if (data != NULL)
1477     g_hash_table_unref (data);
1478 }
1479
1480 static gboolean
1481 file_is_hidden (const gchar *path,
1482                 const gchar *basename)
1483 {
1484   gboolean result;
1485   gchar *dirname;
1486   gpointer table;
1487
1488   dirname = g_path_get_dirname (path);
1489
1490   G_LOCK (hidden_cache);
1491
1492   if G_UNLIKELY (hidden_cache == NULL)
1493     hidden_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
1494                                           g_free, maybe_unref_hash_table);
1495
1496   if (!g_hash_table_lookup_extended (hidden_cache, dirname,
1497                                      NULL, &table))
1498     {
1499       gchar *mydirname;
1500       GSource *remove_from_cache_source;
1501
1502       g_hash_table_insert (hidden_cache,
1503                            mydirname = g_strdup (dirname),
1504                            table = read_hidden_file (dirname));
1505
1506       remove_from_cache_source = g_timeout_source_new_seconds (5);
1507       g_source_set_priority (remove_from_cache_source, G_PRIORITY_DEFAULT);
1508       g_source_set_callback (remove_from_cache_source, 
1509                              remove_from_hidden_cache, 
1510                              mydirname, 
1511                              NULL);
1512       g_source_attach (remove_from_cache_source, 
1513                        GLIB_PRIVATE_CALL (g_get_worker_context) ());
1514       g_source_unref (remove_from_cache_source);
1515     }
1516
1517   result = table != NULL && g_hash_table_contains (table, basename);
1518
1519   G_UNLOCK (hidden_cache);
1520
1521   g_free (dirname);
1522
1523   return result;
1524 }
1525 #endif /* !G_OS_WIN32 */
1526
1527 void
1528 _g_local_file_info_get_nostat (GFileInfo              *info,
1529                                const char             *basename,
1530                                const char             *path,
1531                                GFileAttributeMatcher  *attribute_matcher)
1532 {
1533   g_file_info_set_name (info, basename);
1534
1535   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1536                                             G_FILE_ATTRIBUTE_ID_STANDARD_DISPLAY_NAME))
1537     {
1538       char *display_name = g_filename_display_basename (path);
1539      
1540       /* look for U+FFFD REPLACEMENT CHARACTER */ 
1541       if (strstr (display_name, "\357\277\275") != NULL)
1542         {
1543           char *p = display_name;
1544           display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
1545           g_free (p);
1546         }
1547       g_file_info_set_display_name (info, display_name);
1548       g_free (display_name);
1549     }
1550   
1551   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1552                                             G_FILE_ATTRIBUTE_ID_STANDARD_EDIT_NAME))
1553     {
1554       char *edit_name = g_filename_display_basename (path);
1555       g_file_info_set_edit_name (info, edit_name);
1556       g_free (edit_name);
1557     }
1558
1559   
1560   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1561                                             G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME))
1562     {
1563       char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
1564       if (copy_name)
1565         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME, copy_name);
1566       g_free (copy_name);
1567     }
1568 }
1569
1570 static const char *
1571 get_icon_name (const char *path,
1572                gboolean    use_symbolic,
1573                gboolean   *with_fallbacks_out)
1574 {
1575   const char *name = NULL;
1576   gboolean with_fallbacks = TRUE;
1577
1578   if (strcmp (path, g_get_home_dir ()) == 0)
1579     {
1580       name = use_symbolic ? "user-home-symbolic" : "user-home";
1581       with_fallbacks = FALSE;
1582     }
1583   else if (strcmp (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
1584     {
1585       name = use_symbolic ? "user-desktop-symbolic" : "user-desktop";
1586       with_fallbacks = FALSE;
1587     }
1588   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS)) == 0)
1589     {
1590       name = use_symbolic ? "folder-documents-symbolic" : "folder-documents";
1591     }
1592   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD)) == 0)
1593     {
1594       name = use_symbolic ? "folder-download-symbolic" : "folder-download";
1595     }
1596   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_MUSIC)) == 0)
1597     {
1598       name = use_symbolic ? "folder-music-symbolic" : "folder-music";
1599     }
1600   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PICTURES)) == 0)
1601     {
1602       name = use_symbolic ? "folder-pictures-symbolic" : "folder-pictures";
1603     }
1604   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE)) == 0)
1605     {
1606       name = use_symbolic ? "folder-publicshare-symbolic" : "folder-publicshare";
1607     }
1608   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES)) == 0)
1609     {
1610       name = use_symbolic ? "folder-templates-symbolic" : "folder-templates";
1611     }
1612   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS)) == 0)
1613     {
1614       name = use_symbolic ? "folder-videos-symbolic" : "folder-videos";
1615     }
1616   else
1617     {
1618       name = NULL;
1619     }
1620
1621   if (with_fallbacks_out != NULL)
1622     *with_fallbacks_out = with_fallbacks;
1623
1624   return name;
1625 }
1626
1627 static GIcon *
1628 get_icon (const char *path,
1629           const char *content_type,
1630           gboolean    is_folder,
1631           gboolean    use_symbolic)
1632 {
1633   GIcon *icon = NULL;
1634   const char *icon_name;
1635   gboolean with_fallbacks;
1636
1637   icon_name = get_icon_name (path, use_symbolic, &with_fallbacks);
1638   if (icon_name != NULL)
1639     {
1640       if (with_fallbacks)
1641         icon = g_themed_icon_new_with_default_fallbacks (icon_name);
1642       else
1643         icon = g_themed_icon_new (icon_name);
1644     }
1645   else
1646     {
1647       if (use_symbolic)
1648         icon = g_content_type_get_symbolic_icon (content_type);
1649       else
1650         icon = g_content_type_get_icon (content_type);
1651
1652       if (G_IS_THEMED_ICON (icon) && is_folder)
1653         {
1654           g_themed_icon_append_name (G_THEMED_ICON (icon), use_symbolic ? "folder-symbolic" : "folder");
1655         }
1656     }
1657
1658   return icon;
1659 }
1660
1661 GFileInfo *
1662 _g_local_file_info_get (const char             *basename,
1663                         const char             *path,
1664                         GFileAttributeMatcher  *attribute_matcher,
1665                         GFileQueryInfoFlags     flags,
1666                         GLocalParentFileInfo   *parent_info,
1667                         GError                **error)
1668 {
1669   GFileInfo *info;
1670   GLocalFileStat statbuf;
1671 #ifdef S_ISLNK
1672   struct stat statbuf2;
1673 #endif
1674   int res;
1675   gboolean stat_ok;
1676   gboolean is_symlink, symlink_broken;
1677 #ifdef G_OS_WIN32
1678   DWORD dos_attributes;
1679 #endif
1680   char *symlink_target;
1681   GVfs *vfs;
1682   GVfsClass *class;
1683   guint64 device;
1684
1685   info = g_file_info_new ();
1686
1687   /* Make sure we don't set any unwanted attributes */
1688   g_file_info_set_attribute_mask (info, attribute_matcher);
1689   
1690   _g_local_file_info_get_nostat (info, basename, path, attribute_matcher);
1691
1692   if (attribute_matcher == NULL)
1693     {
1694       g_file_info_unset_attribute_mask (info);
1695       return info;
1696     }
1697
1698 #ifndef G_OS_WIN32
1699   res = g_lstat (path, &statbuf);
1700 #else
1701   {
1702     wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
1703     int len;
1704
1705     if (wpath == NULL)
1706       {
1707         g_object_unref (info);
1708         return NULL;
1709       }
1710
1711     len = wcslen (wpath);
1712     while (len > 0 && G_IS_DIR_SEPARATOR (wpath[len-1]))
1713       len--;
1714     if (len > 0 &&
1715         (!g_path_is_absolute (path) || len > g_path_skip_root (path) - path))
1716       wpath[len] = '\0';
1717
1718     res = _wstati64 (wpath, &statbuf);
1719     dos_attributes = GetFileAttributesW (wpath);
1720
1721     g_free (wpath);
1722   }
1723 #endif
1724
1725   if (res == -1)
1726     {
1727       int errsv = errno;
1728
1729       /* Don't bail out if we get Permission denied (SELinux?) */
1730       if (errsv != EACCES)
1731         {
1732           char *display_name = g_filename_display_name (path);
1733           g_object_unref (info);
1734           g_set_error (error, G_IO_ERROR,
1735                        g_io_error_from_errno (errsv),
1736                        _("Error when getting information for file '%s': %s"),
1737                        display_name, g_strerror (errsv));
1738           g_free (display_name);
1739           return NULL;
1740         }
1741     }
1742
1743   /* Even if stat() fails, try to get as much as other attributes possible */
1744   stat_ok = res != -1;
1745
1746   if (stat_ok)
1747     device = statbuf.st_dev;
1748   else
1749     device = 0;
1750
1751 #ifdef S_ISLNK
1752   is_symlink = stat_ok && S_ISLNK (statbuf.st_mode);
1753 #else
1754   is_symlink = FALSE;
1755 #endif
1756   symlink_broken = FALSE;
1757 #ifdef S_ISLNK
1758   if (is_symlink)
1759     {
1760       g_file_info_set_is_symlink (info, TRUE);
1761
1762       /* Unless NOFOLLOW was set we default to following symlinks */
1763       if (!(flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS))
1764         {
1765           res = stat (path, &statbuf2);
1766
1767           /* Report broken links as symlinks */
1768           if (res != -1)
1769             {
1770               statbuf = statbuf2;
1771               stat_ok = TRUE;
1772             }
1773           else
1774             symlink_broken = TRUE;
1775         }
1776     }
1777 #endif
1778
1779   if (stat_ok)
1780     set_info_from_stat (info, &statbuf, attribute_matcher);
1781
1782 #ifdef G_OS_UNIX
1783   if (stat_ok && _g_local_file_is_lost_found_dir (path, statbuf.st_dev))
1784     g_file_info_set_is_hidden (info, TRUE);
1785 #endif
1786
1787 #ifndef G_OS_WIN32
1788   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1789                                             G_FILE_ATTRIBUTE_ID_STANDARD_IS_HIDDEN))
1790     {
1791       if (basename != NULL &&
1792           (basename[0] == '.' ||
1793            file_is_hidden (path, basename)))
1794         g_file_info_set_is_hidden (info, TRUE);
1795     }
1796
1797   if (basename != NULL && basename[strlen (basename) -1] == '~' &&
1798       (stat_ok && S_ISREG (statbuf.st_mode)))
1799     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_IS_BACKUP, TRUE);
1800 #else
1801   if (dos_attributes & FILE_ATTRIBUTE_HIDDEN)
1802     g_file_info_set_is_hidden (info, TRUE);
1803
1804   if (dos_attributes & FILE_ATTRIBUTE_ARCHIVE)
1805     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_ARCHIVE, TRUE);
1806
1807   if (dos_attributes & FILE_ATTRIBUTE_SYSTEM)
1808     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_SYSTEM, TRUE);
1809 #endif
1810
1811   symlink_target = NULL;
1812 #ifdef S_ISLNK
1813   if (is_symlink)
1814     {
1815       symlink_target = read_link (path);
1816       if (symlink_target &&
1817           _g_file_attribute_matcher_matches_id (attribute_matcher,
1818                                                 G_FILE_ATTRIBUTE_ID_STANDARD_SYMLINK_TARGET))
1819         g_file_info_set_symlink_target (info, symlink_target);
1820     }
1821 #endif
1822   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1823                                             G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
1824       _g_file_attribute_matcher_matches_id (attribute_matcher,
1825                                             G_FILE_ATTRIBUTE_ID_STANDARD_ICON) ||
1826       _g_file_attribute_matcher_matches_id (attribute_matcher,
1827                                             G_FILE_ATTRIBUTE_ID_STANDARD_SYMBOLIC_ICON))
1828     {
1829       char *content_type = get_content_type (basename, path, stat_ok ? &statbuf : NULL, is_symlink, symlink_broken, flags, FALSE);
1830
1831       if (content_type)
1832         {
1833           g_file_info_set_content_type (info, content_type);
1834
1835           if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1836                                                      G_FILE_ATTRIBUTE_ID_STANDARD_ICON)
1837                || _g_file_attribute_matcher_matches_id (attribute_matcher,
1838                                                         G_FILE_ATTRIBUTE_ID_STANDARD_SYMBOLIC_ICON))
1839             {
1840               GIcon *icon;
1841
1842               /* non symbolic icon */
1843               icon = get_icon (path, content_type, S_ISDIR (statbuf.st_mode), FALSE);
1844               if (icon != NULL)
1845                 {
1846                   g_file_info_set_icon (info, icon);
1847                   g_object_unref (icon);
1848                 }
1849
1850               /* symbolic icon */
1851               icon = get_icon (path, content_type, S_ISDIR (statbuf.st_mode), TRUE);
1852               if (icon != NULL)
1853                 {
1854                   g_file_info_set_symbolic_icon (info, icon);
1855                   g_object_unref (icon);
1856                 }
1857
1858             }
1859           
1860           g_free (content_type);
1861         }
1862     }
1863
1864   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1865                                             G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))
1866     {
1867       char *content_type = get_content_type (basename, path, stat_ok ? &statbuf : NULL, is_symlink, symlink_broken, flags, TRUE);
1868       
1869       if (content_type)
1870         {
1871           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);
1872           g_free (content_type);
1873         }
1874     }
1875
1876   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1877                                             G_FILE_ATTRIBUTE_ID_OWNER_USER))
1878     {
1879       char *name = NULL;
1880       
1881 #ifdef G_OS_WIN32
1882       win32_get_file_user_info (path, NULL, &name, NULL);
1883 #else
1884       if (stat_ok)
1885         name = get_username_from_uid (statbuf.st_uid);
1886 #endif
1887       if (name)
1888         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER, name);
1889       g_free (name);
1890     }
1891
1892   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1893                                             G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL))
1894     {
1895       char *name = NULL;
1896 #ifdef G_OS_WIN32
1897       win32_get_file_user_info (path, NULL, NULL, &name);
1898 #else
1899       if (stat_ok)
1900         name = get_realname_from_uid (statbuf.st_uid);
1901 #endif
1902       if (name)
1903         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL, name);
1904       g_free (name);
1905     }
1906   
1907   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1908                                             G_FILE_ATTRIBUTE_ID_OWNER_GROUP))
1909     {
1910       char *name = NULL;
1911 #ifdef G_OS_WIN32
1912       win32_get_file_user_info (path, &name, NULL, NULL);
1913 #else
1914       if (stat_ok)
1915         name = get_groupname_from_gid (statbuf.st_gid);
1916 #endif
1917       if (name)
1918         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_GROUP, name);
1919       g_free (name);
1920     }
1921
1922   if (stat_ok && parent_info && parent_info->device != 0 &&
1923       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT) &&
1924       statbuf.st_dev != parent_info->device) 
1925     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT, TRUE);
1926   
1927   if (stat_ok)
1928     get_access_rights (attribute_matcher, info, path, &statbuf, parent_info);
1929   
1930 #ifdef HAVE_SELINUX
1931   get_selinux_context (path, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1932 #endif
1933   get_xattrs (path, TRUE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1934   get_xattrs (path, FALSE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1935
1936   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1937                                             G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH))
1938     get_thumbnail_attributes (path, info);
1939
1940   vfs = g_vfs_get_default ();
1941   class = G_VFS_GET_CLASS (vfs);
1942   if (class->local_file_add_info)
1943     {
1944       class->local_file_add_info (vfs,
1945                                   path,
1946                                   device,
1947                                   attribute_matcher,
1948                                   info,
1949                                   NULL,
1950                                   &parent_info->extra_data,
1951                                   &parent_info->free_extra_data);
1952     }
1953
1954   g_file_info_unset_attribute_mask (info);
1955
1956   g_free (symlink_target);
1957
1958   return info;
1959 }
1960
1961 GFileInfo *
1962 _g_local_file_info_get_from_fd (int         fd,
1963                                 const char *attributes,
1964                                 GError    **error)
1965 {
1966   GLocalFileStat stat_buf;
1967   GFileAttributeMatcher *matcher;
1968   GFileInfo *info;
1969   
1970 #ifdef G_OS_WIN32
1971 #define FSTAT _fstati64
1972 #else
1973 #define FSTAT fstat
1974 #endif
1975
1976   if (FSTAT (fd, &stat_buf) == -1)
1977     {
1978       int errsv = errno;
1979
1980       g_set_error (error, G_IO_ERROR,
1981                    g_io_error_from_errno (errsv),
1982                    _("Error when getting information for file descriptor: %s"),
1983                    g_strerror (errsv));
1984       return NULL;
1985     }
1986
1987   info = g_file_info_new ();
1988
1989   matcher = g_file_attribute_matcher_new (attributes);
1990
1991   /* Make sure we don't set any unwanted attributes */
1992   g_file_info_set_attribute_mask (info, matcher);
1993   
1994   set_info_from_stat (info, &stat_buf, matcher);
1995   
1996 #ifdef HAVE_SELINUX
1997   if (_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT) &&
1998       is_selinux_enabled ())
1999     {
2000       char *context;
2001       if (fgetfilecon_raw (fd, &context) >= 0)
2002         {
2003           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
2004           freecon (context);
2005         }
2006     }
2007 #endif
2008
2009   get_xattrs_from_fd (fd, TRUE, info, matcher);
2010   get_xattrs_from_fd (fd, FALSE, info, matcher);
2011   
2012   g_file_attribute_matcher_unref (matcher);
2013
2014   g_file_info_unset_attribute_mask (info);
2015   
2016   return info;
2017 }
2018
2019 static gboolean
2020 get_uint32 (const GFileAttributeValue  *value,
2021             guint32                    *val_out,
2022             GError                    **error)
2023 {
2024   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT32)
2025     {
2026       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2027                            _("Invalid attribute type (uint32 expected)"));
2028       return FALSE;
2029     }
2030
2031   *val_out = value->u.uint32;
2032   
2033   return TRUE;
2034 }
2035
2036 #ifdef HAVE_UTIMES
2037 static gboolean
2038 get_uint64 (const GFileAttributeValue  *value,
2039             guint64                    *val_out,
2040             GError                    **error)
2041 {
2042   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT64)
2043     {
2044       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2045                            _("Invalid attribute type (uint64 expected)"));
2046       return FALSE;
2047     }
2048
2049   *val_out = value->u.uint64;
2050   
2051   return TRUE;
2052 }
2053 #endif
2054
2055 #if defined(HAVE_SYMLINK)
2056 static gboolean
2057 get_byte_string (const GFileAttributeValue  *value,
2058                  const char                **val_out,
2059                  GError                    **error)
2060 {
2061   if (value->type != G_FILE_ATTRIBUTE_TYPE_BYTE_STRING)
2062     {
2063       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2064                            _("Invalid attribute type (byte string expected)"));
2065       return FALSE;
2066     }
2067
2068   *val_out = value->u.string;
2069   
2070   return TRUE;
2071 }
2072 #endif
2073
2074 #ifdef HAVE_SELINUX
2075 static gboolean
2076 get_string (const GFileAttributeValue  *value,
2077             const char                **val_out,
2078             GError                    **error)
2079 {
2080   if (value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
2081     {
2082       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2083                            _("Invalid attribute type (byte string expected)"));
2084       return FALSE;
2085     }
2086
2087   *val_out = value->u.string;
2088   
2089   return TRUE;
2090 }
2091 #endif
2092
2093 static gboolean
2094 set_unix_mode (char                       *filename,
2095                GFileQueryInfoFlags         flags,
2096                const GFileAttributeValue  *value,
2097                GError                    **error)
2098 {
2099   guint32 val = 0;
2100   int res = 0;
2101   
2102   if (!get_uint32 (value, &val, error))
2103     return FALSE;
2104
2105 #ifdef HAVE_SYMLINK
2106   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) {
2107 #ifdef HAVE_LCHMOD
2108     res = lchmod (filename, val);
2109 #else
2110     struct stat statbuf;
2111     /* Calling chmod on a symlink changes permissions on the symlink.
2112      * We don't want to do this, so we need to check for a symlink */
2113     res = g_lstat (filename, &statbuf);
2114     if (res == 0 && S_ISLNK (statbuf.st_mode))
2115       {
2116         g_set_error_literal (error, G_IO_ERROR,
2117                              G_IO_ERROR_NOT_SUPPORTED,
2118                              _("Cannot set permissions on symlinks"));
2119         return FALSE;
2120       }
2121     else if (res == 0)
2122       res = g_chmod (filename, val);
2123 #endif
2124   } else
2125 #endif
2126     res = g_chmod (filename, val);
2127
2128   if (res == -1)
2129     {
2130       int errsv = errno;
2131
2132       g_set_error (error, G_IO_ERROR,
2133                    g_io_error_from_errno (errsv),
2134                    _("Error setting permissions: %s"),
2135                    g_strerror (errsv));
2136       return FALSE;
2137     }
2138   return TRUE;
2139 }
2140
2141 #ifdef HAVE_CHOWN
2142 static gboolean
2143 set_unix_uid_gid (char                       *filename,
2144                   const GFileAttributeValue  *uid_value,
2145                   const GFileAttributeValue  *gid_value,
2146                   GFileQueryInfoFlags         flags,
2147                   GError                    **error)
2148 {
2149   int res;
2150   guint32 val = 0;
2151   uid_t uid;
2152   gid_t gid;
2153   
2154   if (uid_value)
2155     {
2156       if (!get_uint32 (uid_value, &val, error))
2157         return FALSE;
2158       uid = val;
2159     }
2160   else
2161     uid = -1;
2162   
2163   if (gid_value)
2164     {
2165       if (!get_uint32 (gid_value, &val, error))
2166         return FALSE;
2167       gid = val;
2168     }
2169   else
2170     gid = -1;
2171   
2172 #ifdef HAVE_LCHOWN
2173   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
2174     res = lchown (filename, uid, gid);
2175   else
2176 #endif
2177     res = chown (filename, uid, gid);
2178   
2179   if (res == -1)
2180     {
2181       int errsv = errno;
2182
2183       g_set_error (error, G_IO_ERROR,
2184                    g_io_error_from_errno (errsv),
2185                    _("Error setting owner: %s"),
2186                    g_strerror (errsv));
2187           return FALSE;
2188     }
2189   return TRUE;
2190 }
2191 #endif
2192
2193 #ifdef HAVE_SYMLINK
2194 static gboolean
2195 set_symlink (char                       *filename,
2196              const GFileAttributeValue  *value,
2197              GError                    **error)
2198 {
2199   const char *val;
2200   struct stat statbuf;
2201   
2202   if (!get_byte_string (value, &val, error))
2203     return FALSE;
2204   
2205   if (val == NULL)
2206     {
2207       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2208                            _("symlink must be non-NULL"));
2209       return FALSE;
2210     }
2211   
2212   if (g_lstat (filename, &statbuf))
2213     {
2214       int errsv = errno;
2215
2216       g_set_error (error, G_IO_ERROR,
2217                    g_io_error_from_errno (errsv),
2218                    _("Error setting symlink: %s"),
2219                    g_strerror (errsv));
2220       return FALSE;
2221     }
2222   
2223   if (!S_ISLNK (statbuf.st_mode))
2224     {
2225       g_set_error_literal (error, G_IO_ERROR,
2226                            G_IO_ERROR_NOT_SYMBOLIC_LINK,
2227                            _("Error setting symlink: file is not a symlink"));
2228       return FALSE;
2229     }
2230   
2231   if (g_unlink (filename))
2232     {
2233       int errsv = errno;
2234
2235       g_set_error (error, G_IO_ERROR,
2236                    g_io_error_from_errno (errsv),
2237                    _("Error setting symlink: %s"),
2238                    g_strerror (errsv));
2239       return FALSE;
2240     }
2241   
2242   if (symlink (filename, val) != 0)
2243     {
2244       int errsv = errno;
2245
2246       g_set_error (error, G_IO_ERROR,
2247                    g_io_error_from_errno (errsv),
2248                    _("Error setting symlink: %s"),
2249                    g_strerror (errsv));
2250       return FALSE;
2251     }
2252   
2253   return TRUE;
2254 }
2255 #endif
2256
2257 #ifdef HAVE_UTIMES
2258 static int
2259 lazy_stat (char        *filename, 
2260            struct stat *statbuf, 
2261            gboolean    *called_stat)
2262 {
2263   int res;
2264
2265   if (*called_stat)
2266     return 0;
2267   
2268   res = g_stat (filename, statbuf);
2269   
2270   if (res == 0)
2271     *called_stat = TRUE;
2272   
2273   return res;
2274 }
2275
2276
2277 static gboolean
2278 set_mtime_atime (char                       *filename,
2279                  const GFileAttributeValue  *mtime_value,
2280                  const GFileAttributeValue  *mtime_usec_value,
2281                  const GFileAttributeValue  *atime_value,
2282                  const GFileAttributeValue  *atime_usec_value,
2283                  GError                    **error)
2284 {
2285   int res;
2286   guint64 val = 0;
2287   guint32 val_usec = 0;
2288   struct stat statbuf;
2289   gboolean got_stat = FALSE;
2290   struct timeval times[2] = { {0, 0}, {0, 0} };
2291
2292   /* ATIME */
2293   if (atime_value)
2294     {
2295       if (!get_uint64 (atime_value, &val, error))
2296         return FALSE;
2297       times[0].tv_sec = val;
2298     }
2299   else
2300     {
2301       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2302         {
2303           times[0].tv_sec = statbuf.st_mtime;
2304 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
2305           times[0].tv_usec = statbuf.st_atimensec / 1000;
2306 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2307           times[0].tv_usec = statbuf.st_atim.tv_nsec / 1000;
2308 #endif
2309         }
2310     }
2311   
2312   if (atime_usec_value)
2313     {
2314       if (!get_uint32 (atime_usec_value, &val_usec, error))
2315         return FALSE;
2316       times[0].tv_usec = val_usec;
2317     }
2318
2319   /* MTIME */
2320   if (mtime_value)
2321     {
2322       if (!get_uint64 (mtime_value, &val, error))
2323         return FALSE;
2324       times[1].tv_sec = val;
2325     }
2326   else
2327     {
2328       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2329         {
2330           times[1].tv_sec = statbuf.st_mtime;
2331 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
2332           times[1].tv_usec = statbuf.st_mtimensec / 1000;
2333 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
2334           times[1].tv_usec = statbuf.st_mtim.tv_nsec / 1000;
2335 #endif
2336         }
2337     }
2338   
2339   if (mtime_usec_value)
2340     {
2341       if (!get_uint32 (mtime_usec_value, &val_usec, error))
2342         return FALSE;
2343       times[1].tv_usec = val_usec;
2344     }
2345   
2346   res = utimes (filename, times);
2347   if (res == -1)
2348     {
2349       int errsv = errno;
2350
2351       g_set_error (error, G_IO_ERROR,
2352                    g_io_error_from_errno (errsv),
2353                    _("Error setting modification or access time: %s"),
2354                    g_strerror (errsv));
2355           return FALSE;
2356     }
2357   return TRUE;
2358 }
2359 #endif
2360
2361
2362 #ifdef HAVE_SELINUX
2363 static gboolean
2364 set_selinux_context (char                       *filename,
2365                  const GFileAttributeValue  *value,
2366                  GError                    **error)
2367 {
2368   const char *val;
2369
2370   if (!get_string (value, &val, error))
2371     return FALSE;
2372
2373   if (val == NULL)
2374   {
2375     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2376                          _("SELinux context must be non-NULL"));
2377     return FALSE;
2378   }
2379
2380   if (is_selinux_enabled ()) {
2381         security_context_t val_s;
2382         
2383         val_s = g_strdup (val);
2384         
2385         if (setfilecon_raw (filename, val_s) < 0)
2386         {
2387             int errsv = errno;
2388             
2389             g_set_error (error, G_IO_ERROR,
2390                          g_io_error_from_errno (errsv),
2391                         _("Error setting SELinux context: %s"),
2392                          g_strerror (errsv));
2393             return FALSE;
2394         }
2395         g_free (val_s);
2396   } else {
2397     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2398                          _("SELinux is not enabled on this system"));
2399     return FALSE;
2400   }
2401                                                      
2402   return TRUE;
2403 }
2404 #endif 
2405
2406
2407 gboolean
2408 _g_local_file_info_set_attribute (char                 *filename,
2409                                   const char           *attribute,
2410                                   GFileAttributeType    type,
2411                                   gpointer              value_p,
2412                                   GFileQueryInfoFlags   flags,
2413                                   GCancellable         *cancellable,
2414                                   GError              **error)
2415 {
2416   GFileAttributeValue value = { 0 };
2417   GVfsClass *class;
2418   GVfs *vfs;
2419
2420   _g_file_attribute_value_set_from_pointer (&value, type, value_p, FALSE);
2421   
2422   if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
2423     return set_unix_mode (filename, flags, &value, error);
2424   
2425 #ifdef HAVE_CHOWN
2426   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_UID) == 0)
2427     return set_unix_uid_gid (filename, &value, NULL, flags, error);
2428   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_GID) == 0)
2429     return set_unix_uid_gid (filename, NULL, &value, flags, error);
2430 #endif
2431   
2432 #ifdef HAVE_SYMLINK
2433   else if (strcmp (attribute, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET) == 0)
2434     return set_symlink (filename, &value, error);
2435 #endif
2436
2437 #ifdef HAVE_UTIMES
2438   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED) == 0)
2439     return set_mtime_atime (filename, &value, NULL, NULL, NULL, error);
2440   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) == 0)
2441     return set_mtime_atime (filename, NULL, &value, NULL, NULL, error);
2442   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS) == 0)
2443     return set_mtime_atime (filename, NULL, NULL, &value, NULL, error);
2444   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) == 0)
2445     return set_mtime_atime (filename, NULL, NULL, NULL, &value, error);
2446 #endif
2447
2448 #ifdef HAVE_XATTR
2449   else if (g_str_has_prefix (attribute, "xattr::"))
2450     return set_xattr (filename, attribute, &value, error);
2451   else if (g_str_has_prefix (attribute, "xattr-sys::"))
2452     return set_xattr (filename, attribute, &value, error);
2453 #endif
2454
2455 #ifdef HAVE_SELINUX 
2456   else if (strcmp (attribute, G_FILE_ATTRIBUTE_SELINUX_CONTEXT) == 0)
2457     return set_selinux_context (filename, &value, error);
2458 #endif
2459
2460   vfs = g_vfs_get_default ();
2461   class = G_VFS_GET_CLASS (vfs);
2462   if (class->local_file_set_attributes)
2463     {
2464       GFileInfo *info;
2465
2466       info = g_file_info_new ();
2467       g_file_info_set_attribute (info,
2468                                  attribute,
2469                                  type,
2470                                  value_p);
2471       if (!class->local_file_set_attributes (vfs, filename,
2472                                              info,
2473                                              flags, cancellable,
2474                                              error))
2475         {
2476           g_object_unref (info);
2477           return FALSE;
2478         }
2479
2480       if (g_file_info_get_attribute_status (info, attribute) == G_FILE_ATTRIBUTE_STATUS_SET)
2481         {
2482           g_object_unref (info);
2483           return TRUE;
2484         }
2485
2486       g_object_unref (info);
2487     }
2488
2489   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2490                _("Setting attribute %s not supported"), attribute);
2491   return FALSE;
2492 }
2493
2494 gboolean
2495 _g_local_file_info_set_attributes  (char                 *filename,
2496                                     GFileInfo            *info,
2497                                     GFileQueryInfoFlags   flags,
2498                                     GCancellable         *cancellable,
2499                                     GError              **error)
2500 {
2501   GFileAttributeValue *value;
2502 #ifdef HAVE_CHOWN
2503   GFileAttributeValue *uid, *gid;
2504 #endif
2505 #ifdef HAVE_UTIMES
2506   GFileAttributeValue *mtime, *mtime_usec, *atime, *atime_usec;
2507 #endif
2508 #if defined (HAVE_CHOWN) || defined (HAVE_UTIMES)
2509   GFileAttributeStatus status;
2510 #endif
2511   gboolean res;
2512   GVfsClass *class;
2513   GVfs *vfs;
2514   
2515   /* Handles setting multiple specified data in a single set, and takes care
2516      of ordering restrictions when setting attributes */
2517
2518   res = TRUE;
2519
2520   /* Set symlink first, since this recreates the file */
2521 #ifdef HAVE_SYMLINK
2522   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET);
2523   if (value)
2524     {
2525       if (!set_symlink (filename, value, error))
2526         {
2527           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2528           res = FALSE;
2529           /* Don't set error multiple times */
2530           error = NULL;
2531         }
2532       else
2533         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2534         
2535     }
2536 #endif
2537
2538 #ifdef HAVE_CHOWN
2539   /* Group uid and gid setting into one call
2540    * Change ownership before permissions, since ownership changes can
2541      change permissions (e.g. setuid)
2542    */
2543   uid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_UID);
2544   gid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_GID);
2545   
2546   if (uid || gid)
2547     {
2548       if (!set_unix_uid_gid (filename, uid, gid, flags, error))
2549         {
2550           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2551           res = FALSE;
2552           /* Don't set error multiple times */
2553           error = NULL;
2554         }
2555       else
2556         status = G_FILE_ATTRIBUTE_STATUS_SET;
2557       if (uid)
2558         uid->status = status;
2559       if (gid)
2560         gid->status = status;
2561     }
2562 #endif
2563   
2564   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_MODE);
2565   if (value)
2566     {
2567       if (!set_unix_mode (filename, flags, value, error))
2568         {
2569           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2570           res = FALSE;
2571           /* Don't set error multiple times */
2572           error = NULL;
2573         }
2574       else
2575         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2576         
2577     }
2578
2579 #ifdef HAVE_UTIMES
2580   /* Group all time settings into one call
2581    * Change times as the last thing to avoid it changing due to metadata changes
2582    */
2583   
2584   mtime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
2585   mtime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
2586   atime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS);
2587   atime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC);
2588
2589   if (mtime || mtime_usec || atime || atime_usec)
2590     {
2591       if (!set_mtime_atime (filename, mtime, mtime_usec, atime, atime_usec, error))
2592         {
2593           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2594           res = FALSE;
2595           /* Don't set error multiple times */
2596           error = NULL;
2597         }
2598       else
2599         status = G_FILE_ATTRIBUTE_STATUS_SET;
2600       
2601       if (mtime)
2602         mtime->status = status;
2603       if (mtime_usec)
2604         mtime_usec->status = status;
2605       if (atime)
2606         atime->status = status;
2607       if (atime_usec)
2608         atime_usec->status = status;
2609     }
2610 #endif
2611
2612   /* xattrs are handled by default callback */
2613
2614
2615   /*  SELinux context */
2616 #ifdef HAVE_SELINUX 
2617   if (is_selinux_enabled ()) {
2618     value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_SELINUX_CONTEXT);
2619     if (value)
2620     {
2621       if (!set_selinux_context (filename, value, error))
2622         {
2623           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2624           res = FALSE;
2625           /* Don't set error multiple times */
2626           error = NULL;
2627         }
2628       else
2629         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2630     }
2631   }
2632 #endif
2633
2634   vfs = g_vfs_get_default ();
2635   class = G_VFS_GET_CLASS (vfs);
2636   if (class->local_file_set_attributes)
2637     {
2638       if (!class->local_file_set_attributes (vfs, filename,
2639                                              info,
2640                                              flags, cancellable,
2641                                              error))
2642         {
2643           res = FALSE;
2644           /* Don't set error multiple times */
2645           error = NULL;
2646         }
2647     }
2648
2649   return res;
2650 }