Docs: don't use <footnote>
[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 #include <glib.h>
28
29 #ifdef HAVE_SYS_TIME_H
30 #include <sys/time.h>
31 #endif
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <string.h>
35 #include <fcntl.h>
36 #include <errno.h>
37 #ifdef G_OS_UNIX
38 #include <grp.h>
39 #include <pwd.h>
40 #endif
41 #ifdef HAVE_SELINUX
42 #include <selinux/selinux.h>
43 #endif
44
45 #ifdef HAVE_XATTR
46
47 #if defined HAVE_SYS_XATTR_H
48   #include <sys/xattr.h>
49 #elif defined HAVE_ATTR_XATTR_H
50   #include <attr/xattr.h>
51 #else
52   #error "Neither <sys/xattr.h> nor <attr/xattr.h> is present but extended attribute support is enabled."
53 #endif /* defined HAVE_SYS_XATTR_H || HAVE_ATTR_XATTR_H */
54
55 #endif /* HAVE_XATTR */
56
57 #include <glib/gstdio.h>
58 #include <gfileattribute-priv.h>
59 #include <gfileinfo-priv.h>
60 #include <gvfs.h>
61
62 #ifdef G_OS_UNIX
63 #include <unistd.h>
64 #include "glib-unix.h"
65 #include "glib-private.h"
66 #endif
67
68 #include "thumbnail-verify.h"
69
70 #ifdef G_OS_WIN32
71 #include <windows.h>
72 #include <io.h>
73 #ifndef W_OK
74 #define W_OK 2
75 #endif
76 #ifndef R_OK
77 #define R_OK 4
78 #endif
79 #ifndef X_OK
80 #define X_OK 0 /* not really */
81 #endif
82 #ifndef S_ISREG
83 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
84 #endif
85 #ifndef S_ISDIR
86 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
87 #endif
88 #ifndef S_IXUSR
89 #define S_IXUSR _S_IEXEC
90 #endif
91 #endif
92
93 #include "glocalfileinfo.h"
94 #include "gioerror.h"
95 #include "gthemedicon.h"
96 #include "gcontenttypeprivate.h"
97 #include "glibintl.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               g_free (gio_attr);
668             }
669           
670           len = strlen (attr) + 1;
671           attr += len;
672           list_res_size -= len;
673         }
674
675       g_free (list);
676     }
677   else
678     {
679       while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
680         {
681           char *unescaped_attribute, *a;
682           gboolean free_unescaped_attribute;
683
684           attr2 = strchr (attr, ':');
685           if (attr2)
686             {
687               attr2++; /* Skip ':' */
688               unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
689               if (user)
690                 a = g_strconcat ("user.", unescaped_attribute, NULL);
691               else
692                 a = unescaped_attribute;
693               
694               get_one_xattr_from_fd (fd, info, attr, a);
695
696               if (user)
697                 g_free (a);
698               
699               if (free_unescaped_attribute)
700                 g_free (unescaped_attribute);
701             }
702         }
703     }
704 #endif /* defined HAVE_XATTR */
705 }
706
707 #ifdef HAVE_XATTR
708 static gboolean
709 set_xattr (char                       *filename,
710            const char                 *escaped_attribute,
711            const GFileAttributeValue  *attr_value,
712            GError                    **error)
713 {
714   char *attribute, *value;
715   gboolean free_attribute, free_value;
716   int val_len, res, errsv;
717   gboolean is_user;
718   char *a;
719
720   if (attr_value == NULL)
721     {
722       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
723                            _("Attribute value must be non-NULL"));
724       return FALSE;
725     }
726
727   if (attr_value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
728     {
729       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
730                            _("Invalid attribute type (string expected)"));
731       return FALSE;
732     }
733
734   if (!name_is_valid (escaped_attribute))
735     {
736       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
737                            _("Invalid extended attribute name"));
738       return FALSE;
739     }
740
741   if (g_str_has_prefix (escaped_attribute, "xattr::"))
742     {
743       escaped_attribute += strlen ("xattr::");
744       is_user = TRUE;
745     }
746   else
747     {
748       g_warn_if_fail (g_str_has_prefix (escaped_attribute, "xattr-sys::"));
749       escaped_attribute += strlen ("xattr-sys::");
750       is_user = FALSE;
751     }
752   
753   attribute = hex_unescape_string (escaped_attribute, NULL, &free_attribute);
754   value = hex_unescape_string (attr_value->u.string, &val_len, &free_value);
755
756   if (is_user)
757     a = g_strconcat ("user.", attribute, NULL);
758   else
759     a = attribute;
760   
761   res = g_setxattr (filename, a, value, val_len);
762   errsv = errno;
763   
764   if (is_user)
765     g_free (a);
766   
767   if (free_attribute)
768     g_free (attribute);
769   
770   if (free_value)
771     g_free (value);
772
773   if (res == -1)
774     {
775       g_set_error (error, G_IO_ERROR,
776                    g_io_error_from_errno (errsv),
777                    _("Error setting extended attribute '%s': %s"),
778                    escaped_attribute, g_strerror (errsv));
779       return FALSE;
780     }
781   
782   return TRUE;
783 }
784
785 #endif
786
787
788 void
789 _g_local_file_info_get_parent_info (const char            *dir,
790                                     GFileAttributeMatcher *attribute_matcher,
791                                     GLocalParentFileInfo  *parent_info)
792 {
793   GStatBuf statbuf;
794   int res;
795
796   parent_info->extra_data = NULL;
797   parent_info->free_extra_data = NULL;
798   parent_info->writable = FALSE;
799   parent_info->is_sticky = FALSE;
800   parent_info->has_trash_dir = FALSE;
801   parent_info->device = 0;
802
803   if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME) ||
804       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE) ||
805       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH) ||
806       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT))
807     {
808       /* FIXME: Windows: The underlying _waccess() call in the C
809        * library is mostly pointless as it only looks at the READONLY
810        * FAT-style attribute of the file, it doesn't check the ACL at
811        * all.
812        */
813       parent_info->writable = (g_access (dir, W_OK) == 0);
814       
815       res = g_stat (dir, &statbuf);
816
817       /*
818        * The sticky bit (S_ISVTX) on a directory means that a file in that directory can be
819        * renamed or deleted only by the owner of the file, by the owner of the directory, and
820        * by a privileged process.
821        */
822       if (res == 0)
823         {
824 #ifdef S_ISVTX
825           parent_info->is_sticky = (statbuf.st_mode & S_ISVTX) != 0;
826 #else
827           parent_info->is_sticky = FALSE;
828 #endif
829           parent_info->owner = statbuf.st_uid;
830           parent_info->device = statbuf.st_dev;
831           /* No need to find trash dir if it's not writable anyway */
832           if (parent_info->writable &&
833               _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
834             parent_info->has_trash_dir = _g_local_file_has_trash_dir (dir, statbuf.st_dev);
835         }
836     }
837 }
838
839 void
840 _g_local_file_info_free_parent_info (GLocalParentFileInfo *parent_info)
841 {
842   if (parent_info->extra_data &&
843       parent_info->free_extra_data)
844     parent_info->free_extra_data (parent_info->extra_data);
845 }
846
847 static void
848 get_access_rights (GFileAttributeMatcher *attribute_matcher,
849                    GFileInfo             *info,
850                    const gchar           *path,
851                    GLocalFileStat        *statbuf,
852                    GLocalParentFileInfo  *parent_info)
853 {
854   /* FIXME: Windows: The underlyin _waccess() is mostly pointless */
855   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
856                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ))
857     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ,
858                                              g_access (path, R_OK) == 0);
859   
860   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
861                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE))
862     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE,
863                                              g_access (path, W_OK) == 0);
864   
865   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
866                                             G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE))
867     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE,
868                                              g_access (path, X_OK) == 0);
869
870
871   if (parent_info)
872     {
873       gboolean writable;
874
875       writable = FALSE;
876       if (parent_info->writable)
877         {
878           if (parent_info->is_sticky)
879             {
880 #ifndef G_OS_WIN32
881               uid_t uid = geteuid ();
882
883               if (uid == statbuf->st_uid ||
884                   uid == parent_info->owner ||
885                   uid == 0)
886 #endif
887                 writable = TRUE;
888             }
889           else
890             writable = TRUE;
891         }
892
893       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME))
894         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME,
895                                                  writable);
896       
897       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE))
898         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE,
899                                                  writable);
900
901       if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
902         _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH,
903                                                  writable && parent_info->has_trash_dir);
904     }
905 }
906
907 static void
908 set_info_from_stat (GFileInfo             *info, 
909                     GLocalFileStat        *statbuf,
910                     GFileAttributeMatcher *attribute_matcher)
911 {
912   GFileType file_type;
913
914   file_type = G_FILE_TYPE_UNKNOWN;
915
916   if (S_ISREG (statbuf->st_mode))
917     file_type = G_FILE_TYPE_REGULAR;
918   else if (S_ISDIR (statbuf->st_mode))
919     file_type = G_FILE_TYPE_DIRECTORY;
920 #ifndef G_OS_WIN32
921   else if (S_ISCHR (statbuf->st_mode) ||
922            S_ISBLK (statbuf->st_mode) ||
923            S_ISFIFO (statbuf->st_mode)
924 #ifdef S_ISSOCK
925            || S_ISSOCK (statbuf->st_mode)
926 #endif
927            )
928     file_type = G_FILE_TYPE_SPECIAL;
929 #endif
930 #ifdef S_ISLNK
931   else if (S_ISLNK (statbuf->st_mode))
932     file_type = G_FILE_TYPE_SYMBOLIC_LINK;
933 #endif
934
935   g_file_info_set_file_type (info, file_type);
936   g_file_info_set_size (info, statbuf->st_size);
937
938   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_DEVICE, statbuf->st_dev);
939 #ifndef G_OS_WIN32
940   /* Pointless setting these on Windows even if they exist in the struct */
941   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_INODE, statbuf->st_ino);
942   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_NLINK, statbuf->st_nlink);
943   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_UID, statbuf->st_uid);
944   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_GID, statbuf->st_gid);
945   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_RDEV, statbuf->st_rdev);
946 #endif
947   /* FIXME: st_mode is mostly pointless on Windows, too. Set the attribute or not? */
948   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_MODE, statbuf->st_mode);
949 #if defined (HAVE_STRUCT_STAT_ST_BLKSIZE)
950   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCK_SIZE, statbuf->st_blksize);
951 #endif
952 #if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
953   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCKS, statbuf->st_blocks);
954   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_ALLOCATED_SIZE,
955                                           statbuf->st_blocks * G_GUINT64_CONSTANT (512));
956 #endif
957   
958   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED, statbuf->st_mtime);
959 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
960   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtimensec / 1000);
961 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
962   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtim.tv_nsec / 1000);
963 #endif
964   
965   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS, statbuf->st_atime);
966 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
967   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atimensec / 1000);
968 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
969   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atim.tv_nsec / 1000);
970 #endif
971   
972   _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED, statbuf->st_ctime);
973 #if defined (HAVE_STRUCT_STAT_ST_CTIMENSEC)
974   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctimensec / 1000);
975 #elif defined (HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC)
976   _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctim.tv_nsec / 1000);
977 #endif
978
979   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
980                                             G_FILE_ATTRIBUTE_ID_ETAG_VALUE))
981     {
982       char *etag = _g_local_file_info_create_etag (statbuf);
983       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ETAG_VALUE, etag);
984       g_free (etag);
985     }
986
987   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
988                                             G_FILE_ATTRIBUTE_ID_ID_FILE))
989     {
990       char *id = _g_local_file_info_create_file_id (statbuf);
991       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILE, id);
992       g_free (id);
993     }
994
995   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
996                                             G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM))
997     {
998       char *id = _g_local_file_info_create_fs_id (statbuf);
999       _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM, id);
1000       g_free (id);
1001     }
1002 }
1003
1004 #ifndef G_OS_WIN32
1005
1006 static char *
1007 make_valid_utf8 (const char *name)
1008 {
1009   GString *string;
1010   const gchar *remainder, *invalid;
1011   gint remaining_bytes, valid_bytes;
1012   
1013   string = NULL;
1014   remainder = name;
1015   remaining_bytes = strlen (name);
1016   
1017   while (remaining_bytes != 0) 
1018     {
1019       if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
1020         break;
1021       valid_bytes = invalid - remainder;
1022     
1023       if (string == NULL) 
1024         string = g_string_sized_new (remaining_bytes);
1025
1026       g_string_append_len (string, remainder, valid_bytes);
1027       /* append U+FFFD REPLACEMENT CHARACTER */
1028       g_string_append (string, "\357\277\275");
1029       
1030       remaining_bytes -= valid_bytes + 1;
1031       remainder = invalid + 1;
1032     }
1033   
1034   if (string == NULL)
1035     return g_strdup (name);
1036   
1037   g_string_append (string, remainder);
1038
1039   g_warn_if_fail (g_utf8_validate (string->str, -1, NULL));
1040   
1041   return g_string_free (string, FALSE);
1042 }
1043
1044 static char *
1045 convert_pwd_string_to_utf8 (char *pwd_str)
1046 {
1047   char *utf8_string;
1048   
1049   if (!g_utf8_validate (pwd_str, -1, NULL))
1050     {
1051       utf8_string = g_locale_to_utf8 (pwd_str, -1, NULL, NULL, NULL);
1052       if (utf8_string == NULL)
1053         utf8_string = make_valid_utf8 (pwd_str);
1054     }
1055   else 
1056     utf8_string = g_strdup (pwd_str);
1057   
1058   return utf8_string;
1059 }
1060
1061 static void
1062 uid_data_free (UidData *data)
1063 {
1064   g_free (data->user_name);
1065   g_free (data->real_name);
1066   g_free (data);
1067 }
1068
1069 /* called with lock held */
1070 static UidData *
1071 lookup_uid_data (uid_t uid)
1072 {
1073   UidData *data;
1074   char buffer[4096];
1075   struct passwd pwbuf;
1076   struct passwd *pwbufp;
1077   char *gecos, *comma;
1078   
1079   if (uid_cache == NULL)
1080     uid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)uid_data_free);
1081
1082   data = g_hash_table_lookup (uid_cache, GINT_TO_POINTER (uid));
1083
1084   if (data)
1085     return data;
1086
1087   data = g_new0 (UidData, 1);
1088
1089 #if defined(HAVE_POSIX_GETPWUID_R)
1090   getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer), &pwbufp);
1091 #elif defined(HAVE_NONPOSIX_GETPWUID_R)
1092   pwbufp = getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer));
1093 #else
1094   pwbufp = getpwuid (uid);
1095 #endif
1096
1097   if (pwbufp != NULL)
1098     {
1099       if (pwbufp->pw_name != NULL && pwbufp->pw_name[0] != 0)
1100         data->user_name = convert_pwd_string_to_utf8 (pwbufp->pw_name);
1101
1102 #ifndef __BIONIC__
1103       gecos = pwbufp->pw_gecos;
1104
1105       if (gecos)
1106         {
1107           comma = strchr (gecos, ',');
1108           if (comma)
1109             *comma = 0;
1110           data->real_name = convert_pwd_string_to_utf8 (gecos);
1111         }
1112 #endif
1113     }
1114
1115   /* Default fallbacks */
1116   if (data->real_name == NULL)
1117     {
1118       if (data->user_name != NULL)
1119         data->real_name = g_strdup (data->user_name);
1120       else
1121         data->real_name = g_strdup_printf ("user #%d", (int)uid);
1122     }
1123   
1124   if (data->user_name == NULL)
1125     data->user_name = g_strdup_printf ("%d", (int)uid);
1126   
1127   g_hash_table_replace (uid_cache, GINT_TO_POINTER (uid), data);
1128   
1129   return data;
1130 }
1131
1132 static char *
1133 get_username_from_uid (uid_t uid)
1134 {
1135   char *res;
1136   UidData *data;
1137   
1138   G_LOCK (uid_cache);
1139   data = lookup_uid_data (uid);
1140   res = g_strdup (data->user_name);  
1141   G_UNLOCK (uid_cache);
1142
1143   return res;
1144 }
1145
1146 static char *
1147 get_realname_from_uid (uid_t uid)
1148 {
1149   char *res;
1150   UidData *data;
1151   
1152   G_LOCK (uid_cache);
1153   data = lookup_uid_data (uid);
1154   res = g_strdup (data->real_name);  
1155   G_UNLOCK (uid_cache);
1156   
1157   return res;
1158 }
1159
1160 /* called with lock held */
1161 static char *
1162 lookup_gid_name (gid_t gid)
1163 {
1164   char *name;
1165   char buffer[4096];
1166   struct group gbuf;
1167   struct group *gbufp;
1168   
1169   if (gid_cache == NULL)
1170     gid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_free);
1171
1172   name = g_hash_table_lookup (gid_cache, GINT_TO_POINTER (gid));
1173
1174   if (name)
1175     return name;
1176
1177 #if defined (HAVE_POSIX_GETGRGID_R)
1178   getgrgid_r (gid, &gbuf, buffer, sizeof(buffer), &gbufp);
1179 #elif defined (HAVE_NONPOSIX_GETGRGID_R)
1180   gbufp = getgrgid_r (gid, &gbuf, buffer, sizeof(buffer));
1181 #else
1182   gbufp = getgrgid (gid);
1183 #endif
1184
1185   if (gbufp != NULL &&
1186       gbufp->gr_name != NULL &&
1187       gbufp->gr_name[0] != 0)
1188     name = convert_pwd_string_to_utf8 (gbufp->gr_name);
1189   else
1190     name = g_strdup_printf("%d", (int)gid);
1191   
1192   g_hash_table_replace (gid_cache, GINT_TO_POINTER (gid), name);
1193   
1194   return name;
1195 }
1196
1197 static char *
1198 get_groupname_from_gid (gid_t gid)
1199 {
1200   char *res;
1201   char *name;
1202   
1203   G_LOCK (gid_cache);
1204   name = lookup_gid_name (gid);
1205   res = g_strdup (name);  
1206   G_UNLOCK (gid_cache);
1207   return res;
1208 }
1209
1210 #endif /* !G_OS_WIN32 */
1211
1212 static char *
1213 get_content_type (const char          *basename,
1214                   const char          *path,
1215                   GLocalFileStat      *statbuf,
1216                   gboolean             is_symlink,
1217                   gboolean             symlink_broken,
1218                   GFileQueryInfoFlags  flags,
1219                   gboolean             fast)
1220 {
1221   if (is_symlink &&
1222       (symlink_broken || (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)))
1223     return g_strdup ("inode/symlink");
1224   else if (statbuf != NULL && S_ISDIR(statbuf->st_mode))
1225     return g_strdup ("inode/directory");
1226 #ifndef G_OS_WIN32
1227   else if (statbuf != NULL && S_ISCHR(statbuf->st_mode))
1228     return g_strdup ("inode/chardevice");
1229   else if (statbuf != NULL && S_ISBLK(statbuf->st_mode))
1230     return g_strdup ("inode/blockdevice");
1231   else if (statbuf != NULL && S_ISFIFO(statbuf->st_mode))
1232     return g_strdup ("inode/fifo");
1233 #endif
1234 #ifdef S_ISSOCK
1235   else if (statbuf != NULL && S_ISSOCK(statbuf->st_mode))
1236     return g_strdup ("inode/socket");
1237 #endif
1238   else
1239     {
1240       char *content_type;
1241       gboolean result_uncertain;
1242       
1243       content_type = g_content_type_guess (basename, NULL, 0, &result_uncertain);
1244       
1245 #ifndef G_OS_WIN32
1246       if (!fast && result_uncertain && path != NULL)
1247         {
1248           guchar sniff_buffer[4096];
1249           gsize sniff_length;
1250           int fd;
1251
1252           sniff_length = _g_unix_content_type_get_sniff_len ();
1253           if (sniff_length > 4096)
1254             sniff_length = 4096;
1255
1256 #ifdef O_NOATIME          
1257           fd = g_open (path, O_RDONLY | O_NOATIME, 0);
1258           if (fd < 0 && errno == EPERM)
1259 #endif
1260             fd = g_open (path, O_RDONLY, 0);
1261
1262           if (fd != -1)
1263             {
1264               ssize_t res;
1265               
1266               res = read (fd, sniff_buffer, sniff_length);
1267               (void) g_close (fd, NULL);
1268               if (res >= 0)
1269                 {
1270                   g_free (content_type);
1271                   content_type = g_content_type_guess (basename, sniff_buffer, res, NULL);
1272                 }
1273             }
1274         }
1275 #endif
1276       
1277       return content_type;
1278     }
1279   
1280 }
1281
1282 /* @stat_buf is the pre-calculated result of stat(path), or %NULL if that failed. */
1283 static void
1284 get_thumbnail_attributes (const char     *path,
1285                           GFileInfo      *info,
1286                           const GLocalFileStat *stat_buf)
1287 {
1288   GChecksum *checksum;
1289   char *uri;
1290   char *filename;
1291   char *basename;
1292
1293   uri = g_filename_to_uri (path, NULL, NULL);
1294
1295   checksum = g_checksum_new (G_CHECKSUM_MD5);
1296   g_checksum_update (checksum, (const guchar *) uri, strlen (uri));
1297
1298   basename = g_strconcat (g_checksum_get_string (checksum), ".png", NULL);
1299   g_checksum_free (checksum);
1300
1301   filename = g_build_filename (g_get_user_cache_dir (),
1302                                "thumbnails", "large", basename,
1303                                NULL);
1304
1305   if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1306     {
1307       _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1308       _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_IS_VALID,
1309                                                 thumbnail_verify (filename, uri, stat_buf));
1310     }
1311   else
1312     {
1313       g_free (filename);
1314       filename = g_build_filename (g_get_user_cache_dir (),
1315                                    "thumbnails", "normal", basename,
1316                                    NULL);
1317
1318       if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1319         {
1320           _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
1321           _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_IS_VALID,
1322                                                     thumbnail_verify (filename, uri, stat_buf));
1323         }
1324       else
1325         {
1326           g_free (filename);
1327           filename = g_build_filename (g_get_user_cache_dir (),
1328                                        "thumbnails", "fail",
1329                                        "gnome-thumbnail-factory",
1330                                        basename,
1331                                        NULL);
1332
1333           if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1334             {
1335               _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAILING_FAILED, TRUE);
1336               _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_IS_VALID,
1337                                                         thumbnail_verify (filename, uri, stat_buf));
1338             }
1339         }
1340     }
1341   g_free (basename);
1342   g_free (filename);
1343   g_free (uri);
1344 }
1345
1346 #ifdef G_OS_WIN32
1347 static void
1348 win32_get_file_user_info (const gchar  *filename,
1349                           gchar       **group_name, 
1350                           gchar       **user_name, 
1351                           gchar       **real_name)
1352 {
1353   PSECURITY_DESCRIPTOR psd = NULL;
1354   DWORD sd_size = 0; /* first call calculates the size required */
1355   
1356   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
1357   if ((GetFileSecurityW (wfilename, 
1358                         GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1359                         NULL,
1360                         sd_size,
1361                         &sd_size) || (ERROR_INSUFFICIENT_BUFFER == GetLastError())) &&
1362      (psd = g_try_malloc (sd_size)) != NULL &&
1363      GetFileSecurityW (wfilename, 
1364                        GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
1365                        psd,
1366                        sd_size,
1367                        &sd_size))
1368     {
1369       PSID psid = 0;
1370       BOOL defaulted;
1371       SID_NAME_USE name_use = 0; /* don't care? */
1372       wchar_t *name = NULL;
1373       wchar_t *domain = NULL;
1374       DWORD name_len = 0;
1375       DWORD domain_len = 0;
1376       /* get the user name */
1377       do {
1378         if (!user_name)
1379           break;
1380         if (!GetSecurityDescriptorOwner (psd, &psid, &defaulted))
1381           break;
1382         if (!LookupAccountSidW (NULL, /* local machine */
1383                                 psid, 
1384                                 name, &name_len,
1385                                 domain, &domain_len, /* no domain info yet */
1386                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1387           break;
1388         name = g_try_malloc (name_len * sizeof (wchar_t));
1389         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1390         if (name && domain &&
1391             LookupAccountSidW (NULL, /* local machine */
1392                                psid, 
1393                                name, &name_len,
1394                                domain, &domain_len, /* no domain info yet */
1395                                &name_use))
1396           {
1397             *user_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1398           }
1399         g_free (name);
1400         g_free (domain);
1401       } while (FALSE);
1402
1403       /* get the group name */
1404       do {
1405         if (!group_name)
1406           break;
1407         if (!GetSecurityDescriptorGroup (psd, &psid, &defaulted))
1408           break;
1409         if (!LookupAccountSidW (NULL, /* local machine */
1410                                 psid, 
1411                                 name, &name_len,
1412                                 domain, &domain_len, /* no domain info yet */
1413                                 &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
1414           break;
1415         name = g_try_malloc (name_len * sizeof (wchar_t));
1416         domain = g_try_malloc (domain_len * sizeof (wchar_t));
1417         if (name && domain &&
1418             LookupAccountSidW (NULL, /* local machine */
1419                                psid, 
1420                                name, &name_len,
1421                                domain, &domain_len, /* no domain info yet */
1422                                &name_use))
1423           {
1424             *group_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
1425           }
1426         g_free (name);
1427         g_free (domain);
1428       } while (FALSE);
1429
1430       /* TODO: get real name */
1431
1432       g_free (psd);
1433     }
1434   g_free (wfilename);
1435 }
1436 #endif /* G_OS_WIN32 */
1437
1438 #ifndef G_OS_WIN32
1439 /* support for '.hidden' files */
1440 G_LOCK_DEFINE_STATIC (hidden_cache);
1441 static GHashTable *hidden_cache;
1442
1443 static gboolean
1444 remove_from_hidden_cache (gpointer user_data)
1445 {
1446   G_LOCK (hidden_cache);
1447   g_hash_table_remove (hidden_cache, user_data);
1448   G_UNLOCK (hidden_cache);
1449
1450   return FALSE;
1451 }
1452
1453 static GHashTable *
1454 read_hidden_file (const gchar *dirname)
1455 {
1456   gchar *contents = NULL;
1457   gchar *filename;
1458
1459   filename = g_build_path ("/", dirname, ".hidden", NULL);
1460   g_file_get_contents (filename, &contents, NULL, NULL);
1461   g_free (filename);
1462
1463   if (contents != NULL)
1464     {
1465       GHashTable *table;
1466       gchar **lines;
1467       gint i;
1468
1469       table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1470
1471       lines = g_strsplit (contents, "\n", 0);
1472       g_free (contents);
1473
1474       for (i = 0; lines[i]; i++)
1475         /* hash table takes the individual strings... */
1476         g_hash_table_add (table, lines[i]);
1477
1478       /* ... so we only free the container. */
1479       g_free (lines);
1480
1481       return table;
1482     }
1483   else
1484     return NULL;
1485 }
1486
1487 static void
1488 maybe_unref_hash_table (gpointer data)
1489 {
1490   if (data != NULL)
1491     g_hash_table_unref (data);
1492 }
1493
1494 static gboolean
1495 file_is_hidden (const gchar *path,
1496                 const gchar *basename)
1497 {
1498   gboolean result;
1499   gchar *dirname;
1500   gpointer table;
1501
1502   dirname = g_path_get_dirname (path);
1503
1504   G_LOCK (hidden_cache);
1505
1506   if G_UNLIKELY (hidden_cache == NULL)
1507     hidden_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
1508                                           g_free, maybe_unref_hash_table);
1509
1510   if (!g_hash_table_lookup_extended (hidden_cache, dirname,
1511                                      NULL, &table))
1512     {
1513       gchar *mydirname;
1514       GSource *remove_from_cache_source;
1515
1516       g_hash_table_insert (hidden_cache,
1517                            mydirname = g_strdup (dirname),
1518                            table = read_hidden_file (dirname));
1519
1520       remove_from_cache_source = g_timeout_source_new_seconds (5);
1521       g_source_set_priority (remove_from_cache_source, G_PRIORITY_DEFAULT);
1522       g_source_set_callback (remove_from_cache_source, 
1523                              remove_from_hidden_cache, 
1524                              mydirname, 
1525                              NULL);
1526       g_source_attach (remove_from_cache_source, 
1527                        GLIB_PRIVATE_CALL (g_get_worker_context) ());
1528       g_source_unref (remove_from_cache_source);
1529     }
1530
1531   result = table != NULL && g_hash_table_contains (table, basename);
1532
1533   G_UNLOCK (hidden_cache);
1534
1535   g_free (dirname);
1536
1537   return result;
1538 }
1539 #endif /* !G_OS_WIN32 */
1540
1541 void
1542 _g_local_file_info_get_nostat (GFileInfo              *info,
1543                                const char             *basename,
1544                                const char             *path,
1545                                GFileAttributeMatcher  *attribute_matcher)
1546 {
1547   g_file_info_set_name (info, basename);
1548
1549   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1550                                             G_FILE_ATTRIBUTE_ID_STANDARD_DISPLAY_NAME))
1551     {
1552       char *display_name = g_filename_display_basename (path);
1553      
1554       /* look for U+FFFD REPLACEMENT CHARACTER */ 
1555       if (strstr (display_name, "\357\277\275") != NULL)
1556         {
1557           char *p = display_name;
1558           display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
1559           g_free (p);
1560         }
1561       g_file_info_set_display_name (info, display_name);
1562       g_free (display_name);
1563     }
1564   
1565   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1566                                             G_FILE_ATTRIBUTE_ID_STANDARD_EDIT_NAME))
1567     {
1568       char *edit_name = g_filename_display_basename (path);
1569       g_file_info_set_edit_name (info, edit_name);
1570       g_free (edit_name);
1571     }
1572
1573   
1574   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1575                                             G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME))
1576     {
1577       char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
1578       if (copy_name)
1579         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME, copy_name);
1580       g_free (copy_name);
1581     }
1582 }
1583
1584 static const char *
1585 get_icon_name (const char *path,
1586                gboolean    use_symbolic,
1587                gboolean   *with_fallbacks_out)
1588 {
1589   const char *name = NULL;
1590   gboolean with_fallbacks = TRUE;
1591
1592   if (strcmp (path, g_get_home_dir ()) == 0)
1593     {
1594       name = use_symbolic ? "user-home-symbolic" : "user-home";
1595       with_fallbacks = FALSE;
1596     }
1597   else if (strcmp (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
1598     {
1599       name = use_symbolic ? "user-desktop-symbolic" : "user-desktop";
1600       with_fallbacks = FALSE;
1601     }
1602   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS)) == 0)
1603     {
1604       name = use_symbolic ? "folder-documents-symbolic" : "folder-documents";
1605     }
1606   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD)) == 0)
1607     {
1608       name = use_symbolic ? "folder-download-symbolic" : "folder-download";
1609     }
1610   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_MUSIC)) == 0)
1611     {
1612       name = use_symbolic ? "folder-music-symbolic" : "folder-music";
1613     }
1614   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PICTURES)) == 0)
1615     {
1616       name = use_symbolic ? "folder-pictures-symbolic" : "folder-pictures";
1617     }
1618   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE)) == 0)
1619     {
1620       name = use_symbolic ? "folder-publicshare-symbolic" : "folder-publicshare";
1621     }
1622   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES)) == 0)
1623     {
1624       name = use_symbolic ? "folder-templates-symbolic" : "folder-templates";
1625     }
1626   else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS)) == 0)
1627     {
1628       name = use_symbolic ? "folder-videos-symbolic" : "folder-videos";
1629     }
1630   else
1631     {
1632       name = NULL;
1633     }
1634
1635   if (with_fallbacks_out != NULL)
1636     *with_fallbacks_out = with_fallbacks;
1637
1638   return name;
1639 }
1640
1641 static GIcon *
1642 get_icon (const char *path,
1643           const char *content_type,
1644           gboolean    is_folder,
1645           gboolean    use_symbolic)
1646 {
1647   GIcon *icon = NULL;
1648   const char *icon_name;
1649   gboolean with_fallbacks;
1650
1651   icon_name = get_icon_name (path, use_symbolic, &with_fallbacks);
1652   if (icon_name != NULL)
1653     {
1654       if (with_fallbacks)
1655         icon = g_themed_icon_new_with_default_fallbacks (icon_name);
1656       else
1657         icon = g_themed_icon_new (icon_name);
1658     }
1659   else
1660     {
1661       if (use_symbolic)
1662         icon = g_content_type_get_symbolic_icon (content_type);
1663       else
1664         icon = g_content_type_get_icon (content_type);
1665
1666       if (G_IS_THEMED_ICON (icon) && is_folder)
1667         {
1668           g_themed_icon_append_name (G_THEMED_ICON (icon), use_symbolic ? "folder-symbolic" : "folder");
1669         }
1670     }
1671
1672   return icon;
1673 }
1674
1675 GFileInfo *
1676 _g_local_file_info_get (const char             *basename,
1677                         const char             *path,
1678                         GFileAttributeMatcher  *attribute_matcher,
1679                         GFileQueryInfoFlags     flags,
1680                         GLocalParentFileInfo   *parent_info,
1681                         GError                **error)
1682 {
1683   GFileInfo *info;
1684   GLocalFileStat statbuf;
1685 #ifdef S_ISLNK
1686   struct stat statbuf2;
1687 #endif
1688   int res;
1689   gboolean stat_ok;
1690   gboolean is_symlink, symlink_broken;
1691 #ifdef G_OS_WIN32
1692   DWORD dos_attributes;
1693 #endif
1694   char *symlink_target;
1695   GVfs *vfs;
1696   GVfsClass *class;
1697   guint64 device;
1698
1699   info = g_file_info_new ();
1700
1701   /* Make sure we don't set any unwanted attributes */
1702   g_file_info_set_attribute_mask (info, attribute_matcher);
1703   
1704   _g_local_file_info_get_nostat (info, basename, path, attribute_matcher);
1705
1706   if (attribute_matcher == NULL)
1707     {
1708       g_file_info_unset_attribute_mask (info);
1709       return info;
1710     }
1711
1712 #ifndef G_OS_WIN32
1713   res = g_lstat (path, &statbuf);
1714 #else
1715   {
1716     wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
1717     int len;
1718
1719     if (wpath == NULL)
1720       {
1721         g_object_unref (info);
1722         return NULL;
1723       }
1724
1725     len = wcslen (wpath);
1726     while (len > 0 && G_IS_DIR_SEPARATOR (wpath[len-1]))
1727       len--;
1728     if (len > 0 &&
1729         (!g_path_is_absolute (path) || len > g_path_skip_root (path) - path))
1730       wpath[len] = '\0';
1731
1732     res = _wstati64 (wpath, &statbuf);
1733     dos_attributes = GetFileAttributesW (wpath);
1734
1735     g_free (wpath);
1736   }
1737 #endif
1738
1739   if (res == -1)
1740     {
1741       int errsv = errno;
1742
1743       /* Don't bail out if we get Permission denied (SELinux?) */
1744       if (errsv != EACCES)
1745         {
1746           char *display_name = g_filename_display_name (path);
1747           g_object_unref (info);
1748           g_set_error (error, G_IO_ERROR,
1749                        g_io_error_from_errno (errsv),
1750                        _("Error when getting information for file '%s': %s"),
1751                        display_name, g_strerror (errsv));
1752           g_free (display_name);
1753           return NULL;
1754         }
1755     }
1756
1757   /* Even if stat() fails, try to get as much as other attributes possible */
1758   stat_ok = res != -1;
1759
1760   if (stat_ok)
1761     device = statbuf.st_dev;
1762   else
1763     device = 0;
1764
1765 #ifdef S_ISLNK
1766   is_symlink = stat_ok && S_ISLNK (statbuf.st_mode);
1767 #else
1768   is_symlink = FALSE;
1769 #endif
1770   symlink_broken = FALSE;
1771 #ifdef S_ISLNK
1772   if (is_symlink)
1773     {
1774       g_file_info_set_is_symlink (info, TRUE);
1775
1776       /* Unless NOFOLLOW was set we default to following symlinks */
1777       if (!(flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS))
1778         {
1779           res = stat (path, &statbuf2);
1780
1781           /* Report broken links as symlinks */
1782           if (res != -1)
1783             {
1784               statbuf = statbuf2;
1785               stat_ok = TRUE;
1786             }
1787           else
1788             symlink_broken = TRUE;
1789         }
1790     }
1791 #endif
1792
1793   if (stat_ok)
1794     set_info_from_stat (info, &statbuf, attribute_matcher);
1795
1796 #ifdef G_OS_UNIX
1797   if (stat_ok && _g_local_file_is_lost_found_dir (path, statbuf.st_dev))
1798     g_file_info_set_is_hidden (info, TRUE);
1799 #endif
1800
1801 #ifndef G_OS_WIN32
1802   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1803                                             G_FILE_ATTRIBUTE_ID_STANDARD_IS_HIDDEN))
1804     {
1805       if (basename != NULL &&
1806           (basename[0] == '.' ||
1807            file_is_hidden (path, basename)))
1808         g_file_info_set_is_hidden (info, TRUE);
1809     }
1810
1811   if (basename != NULL && basename[strlen (basename) -1] == '~' &&
1812       (stat_ok && S_ISREG (statbuf.st_mode)))
1813     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_IS_BACKUP, TRUE);
1814 #else
1815   if (dos_attributes & FILE_ATTRIBUTE_HIDDEN)
1816     g_file_info_set_is_hidden (info, TRUE);
1817
1818   if (dos_attributes & FILE_ATTRIBUTE_ARCHIVE)
1819     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_ARCHIVE, TRUE);
1820
1821   if (dos_attributes & FILE_ATTRIBUTE_SYSTEM)
1822     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_SYSTEM, TRUE);
1823 #endif
1824
1825   symlink_target = NULL;
1826 #ifdef S_ISLNK
1827   if (is_symlink)
1828     {
1829       symlink_target = read_link (path);
1830       if (symlink_target &&
1831           _g_file_attribute_matcher_matches_id (attribute_matcher,
1832                                                 G_FILE_ATTRIBUTE_ID_STANDARD_SYMLINK_TARGET))
1833         g_file_info_set_symlink_target (info, symlink_target);
1834     }
1835 #endif
1836   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1837                                             G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
1838       _g_file_attribute_matcher_matches_id (attribute_matcher,
1839                                             G_FILE_ATTRIBUTE_ID_STANDARD_ICON) ||
1840       _g_file_attribute_matcher_matches_id (attribute_matcher,
1841                                             G_FILE_ATTRIBUTE_ID_STANDARD_SYMBOLIC_ICON))
1842     {
1843       char *content_type = get_content_type (basename, path, stat_ok ? &statbuf : NULL, is_symlink, symlink_broken, flags, FALSE);
1844
1845       if (content_type)
1846         {
1847           g_file_info_set_content_type (info, content_type);
1848
1849           if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1850                                                      G_FILE_ATTRIBUTE_ID_STANDARD_ICON)
1851                || _g_file_attribute_matcher_matches_id (attribute_matcher,
1852                                                         G_FILE_ATTRIBUTE_ID_STANDARD_SYMBOLIC_ICON))
1853             {
1854               GIcon *icon;
1855
1856               /* non symbolic icon */
1857               icon = get_icon (path, content_type, S_ISDIR (statbuf.st_mode), FALSE);
1858               if (icon != NULL)
1859                 {
1860                   g_file_info_set_icon (info, icon);
1861                   g_object_unref (icon);
1862                 }
1863
1864               /* symbolic icon */
1865               icon = get_icon (path, content_type, S_ISDIR (statbuf.st_mode), TRUE);
1866               if (icon != NULL)
1867                 {
1868                   g_file_info_set_symbolic_icon (info, icon);
1869                   g_object_unref (icon);
1870                 }
1871
1872             }
1873           
1874           g_free (content_type);
1875         }
1876     }
1877
1878   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1879                                             G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))
1880     {
1881       char *content_type = get_content_type (basename, path, stat_ok ? &statbuf : NULL, is_symlink, symlink_broken, flags, TRUE);
1882       
1883       if (content_type)
1884         {
1885           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);
1886           g_free (content_type);
1887         }
1888     }
1889
1890   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1891                                             G_FILE_ATTRIBUTE_ID_OWNER_USER))
1892     {
1893       char *name = NULL;
1894       
1895 #ifdef G_OS_WIN32
1896       win32_get_file_user_info (path, NULL, &name, NULL);
1897 #else
1898       if (stat_ok)
1899         name = get_username_from_uid (statbuf.st_uid);
1900 #endif
1901       if (name)
1902         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER, name);
1903       g_free (name);
1904     }
1905
1906   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1907                                             G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL))
1908     {
1909       char *name = NULL;
1910 #ifdef G_OS_WIN32
1911       win32_get_file_user_info (path, NULL, NULL, &name);
1912 #else
1913       if (stat_ok)
1914         name = get_realname_from_uid (statbuf.st_uid);
1915 #endif
1916       if (name)
1917         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL, name);
1918       g_free (name);
1919     }
1920   
1921   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1922                                             G_FILE_ATTRIBUTE_ID_OWNER_GROUP))
1923     {
1924       char *name = NULL;
1925 #ifdef G_OS_WIN32
1926       win32_get_file_user_info (path, &name, NULL, NULL);
1927 #else
1928       if (stat_ok)
1929         name = get_groupname_from_gid (statbuf.st_gid);
1930 #endif
1931       if (name)
1932         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_GROUP, name);
1933       g_free (name);
1934     }
1935
1936   if (stat_ok && parent_info && parent_info->device != 0 &&
1937       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT) &&
1938       statbuf.st_dev != parent_info->device) 
1939     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT, TRUE);
1940   
1941   if (stat_ok)
1942     get_access_rights (attribute_matcher, info, path, &statbuf, parent_info);
1943   
1944 #ifdef HAVE_SELINUX
1945   get_selinux_context (path, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1946 #endif
1947   get_xattrs (path, TRUE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1948   get_xattrs (path, FALSE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1949
1950   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1951                                             G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH))
1952     {
1953       if (stat_ok)
1954           get_thumbnail_attributes (path, info, &statbuf);
1955       else
1956           get_thumbnail_attributes (path, info, NULL);
1957     }
1958
1959   vfs = g_vfs_get_default ();
1960   class = G_VFS_GET_CLASS (vfs);
1961   if (class->local_file_add_info)
1962     {
1963       class->local_file_add_info (vfs,
1964                                   path,
1965                                   device,
1966                                   attribute_matcher,
1967                                   info,
1968                                   NULL,
1969                                   &parent_info->extra_data,
1970                                   &parent_info->free_extra_data);
1971     }
1972
1973   g_file_info_unset_attribute_mask (info);
1974
1975   g_free (symlink_target);
1976
1977   return info;
1978 }
1979
1980 GFileInfo *
1981 _g_local_file_info_get_from_fd (int         fd,
1982                                 const char *attributes,
1983                                 GError    **error)
1984 {
1985   GLocalFileStat stat_buf;
1986   GFileAttributeMatcher *matcher;
1987   GFileInfo *info;
1988   
1989 #ifdef G_OS_WIN32
1990 #define FSTAT _fstati64
1991 #else
1992 #define FSTAT fstat
1993 #endif
1994
1995   if (FSTAT (fd, &stat_buf) == -1)
1996     {
1997       int errsv = errno;
1998
1999       g_set_error (error, G_IO_ERROR,
2000                    g_io_error_from_errno (errsv),
2001                    _("Error when getting information for file descriptor: %s"),
2002                    g_strerror (errsv));
2003       return NULL;
2004     }
2005
2006   info = g_file_info_new ();
2007
2008   matcher = g_file_attribute_matcher_new (attributes);
2009
2010   /* Make sure we don't set any unwanted attributes */
2011   g_file_info_set_attribute_mask (info, matcher);
2012   
2013   set_info_from_stat (info, &stat_buf, matcher);
2014   
2015 #ifdef HAVE_SELINUX
2016   if (_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT) &&
2017       is_selinux_enabled ())
2018     {
2019       char *context;
2020       if (fgetfilecon_raw (fd, &context) >= 0)
2021         {
2022           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
2023           freecon (context);
2024         }
2025     }
2026 #endif
2027
2028   get_xattrs_from_fd (fd, TRUE, info, matcher);
2029   get_xattrs_from_fd (fd, FALSE, info, matcher);
2030   
2031   g_file_attribute_matcher_unref (matcher);
2032
2033   g_file_info_unset_attribute_mask (info);
2034   
2035   return info;
2036 }
2037
2038 static gboolean
2039 get_uint32 (const GFileAttributeValue  *value,
2040             guint32                    *val_out,
2041             GError                    **error)
2042 {
2043   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT32)
2044     {
2045       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2046                            _("Invalid attribute type (uint32 expected)"));
2047       return FALSE;
2048     }
2049
2050   *val_out = value->u.uint32;
2051   
2052   return TRUE;
2053 }
2054
2055 #ifdef HAVE_UTIMES
2056 static gboolean
2057 get_uint64 (const GFileAttributeValue  *value,
2058             guint64                    *val_out,
2059             GError                    **error)
2060 {
2061   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT64)
2062     {
2063       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2064                            _("Invalid attribute type (uint64 expected)"));
2065       return FALSE;
2066     }
2067
2068   *val_out = value->u.uint64;
2069   
2070   return TRUE;
2071 }
2072 #endif
2073
2074 #if defined(HAVE_SYMLINK)
2075 static gboolean
2076 get_byte_string (const GFileAttributeValue  *value,
2077                  const char                **val_out,
2078                  GError                    **error)
2079 {
2080   if (value->type != G_FILE_ATTRIBUTE_TYPE_BYTE_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 #ifdef HAVE_SELINUX
2094 static gboolean
2095 get_string (const GFileAttributeValue  *value,
2096             const char                **val_out,
2097             GError                    **error)
2098 {
2099   if (value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
2100     {
2101       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2102                            _("Invalid attribute type (byte string expected)"));
2103       return FALSE;
2104     }
2105
2106   *val_out = value->u.string;
2107   
2108   return TRUE;
2109 }
2110 #endif
2111
2112 static gboolean
2113 set_unix_mode (char                       *filename,
2114                GFileQueryInfoFlags         flags,
2115                const GFileAttributeValue  *value,
2116                GError                    **error)
2117 {
2118   guint32 val = 0;
2119   int res = 0;
2120   
2121   if (!get_uint32 (value, &val, error))
2122     return FALSE;
2123
2124 #ifdef HAVE_SYMLINK
2125   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) {
2126 #ifdef HAVE_LCHMOD
2127     res = lchmod (filename, val);
2128 #else
2129     struct stat statbuf;
2130     /* Calling chmod on a symlink changes permissions on the symlink.
2131      * We don't want to do this, so we need to check for a symlink */
2132     res = g_lstat (filename, &statbuf);
2133     if (res == 0 && S_ISLNK (statbuf.st_mode))
2134       {
2135         g_set_error_literal (error, G_IO_ERROR,
2136                              G_IO_ERROR_NOT_SUPPORTED,
2137                              _("Cannot set permissions on symlinks"));
2138         return FALSE;
2139       }
2140     else if (res == 0)
2141       res = g_chmod (filename, val);
2142 #endif
2143   } else
2144 #endif
2145     res = g_chmod (filename, val);
2146
2147   if (res == -1)
2148     {
2149       int errsv = errno;
2150
2151       g_set_error (error, G_IO_ERROR,
2152                    g_io_error_from_errno (errsv),
2153                    _("Error setting permissions: %s"),
2154                    g_strerror (errsv));
2155       return FALSE;
2156     }
2157   return TRUE;
2158 }
2159
2160 #ifdef G_OS_UNIX
2161 static gboolean
2162 set_unix_uid_gid (char                       *filename,
2163                   const GFileAttributeValue  *uid_value,
2164                   const GFileAttributeValue  *gid_value,
2165                   GFileQueryInfoFlags         flags,
2166                   GError                    **error)
2167 {
2168   int res;
2169   guint32 val = 0;
2170   uid_t uid;
2171   gid_t gid;
2172   
2173   if (uid_value)
2174     {
2175       if (!get_uint32 (uid_value, &val, error))
2176         return FALSE;
2177       uid = val;
2178     }
2179   else
2180     uid = -1;
2181   
2182   if (gid_value)
2183     {
2184       if (!get_uint32 (gid_value, &val, error))
2185         return FALSE;
2186       gid = val;
2187     }
2188   else
2189     gid = -1;
2190   
2191 #ifdef HAVE_LCHOWN
2192   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
2193     res = lchown (filename, uid, gid);
2194   else
2195 #endif
2196     res = chown (filename, uid, gid);
2197   
2198   if (res == -1)
2199     {
2200       int errsv = errno;
2201
2202       g_set_error (error, G_IO_ERROR,
2203                    g_io_error_from_errno (errsv),
2204                    _("Error setting owner: %s"),
2205                    g_strerror (errsv));
2206           return FALSE;
2207     }
2208   return TRUE;
2209 }
2210 #endif
2211
2212 #ifdef HAVE_SYMLINK
2213 static gboolean
2214 set_symlink (char                       *filename,
2215              const GFileAttributeValue  *value,
2216              GError                    **error)
2217 {
2218   const char *val;
2219   struct stat statbuf;
2220   
2221   if (!get_byte_string (value, &val, error))
2222     return FALSE;
2223   
2224   if (val == NULL)
2225     {
2226       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2227                            _("symlink must be non-NULL"));
2228       return FALSE;
2229     }
2230   
2231   if (g_lstat (filename, &statbuf))
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 (!S_ISLNK (statbuf.st_mode))
2243     {
2244       g_set_error_literal (error, G_IO_ERROR,
2245                            G_IO_ERROR_NOT_SYMBOLIC_LINK,
2246                            _("Error setting symlink: file is not a symlink"));
2247       return FALSE;
2248     }
2249   
2250   if (g_unlink (filename))
2251     {
2252       int errsv = errno;
2253
2254       g_set_error (error, G_IO_ERROR,
2255                    g_io_error_from_errno (errsv),
2256                    _("Error setting symlink: %s"),
2257                    g_strerror (errsv));
2258       return FALSE;
2259     }
2260   
2261   if (symlink (filename, val) != 0)
2262     {
2263       int errsv = errno;
2264
2265       g_set_error (error, G_IO_ERROR,
2266                    g_io_error_from_errno (errsv),
2267                    _("Error setting symlink: %s"),
2268                    g_strerror (errsv));
2269       return FALSE;
2270     }
2271   
2272   return TRUE;
2273 }
2274 #endif
2275
2276 #ifdef HAVE_UTIMES
2277 static int
2278 lazy_stat (char        *filename, 
2279            struct stat *statbuf, 
2280            gboolean    *called_stat)
2281 {
2282   int res;
2283
2284   if (*called_stat)
2285     return 0;
2286   
2287   res = g_stat (filename, statbuf);
2288   
2289   if (res == 0)
2290     *called_stat = TRUE;
2291   
2292   return res;
2293 }
2294
2295
2296 static gboolean
2297 set_mtime_atime (char                       *filename,
2298                  const GFileAttributeValue  *mtime_value,
2299                  const GFileAttributeValue  *mtime_usec_value,
2300                  const GFileAttributeValue  *atime_value,
2301                  const GFileAttributeValue  *atime_usec_value,
2302                  GError                    **error)
2303 {
2304   int res;
2305   guint64 val = 0;
2306   guint32 val_usec = 0;
2307   struct stat statbuf;
2308   gboolean got_stat = FALSE;
2309   struct timeval times[2] = { {0, 0}, {0, 0} };
2310
2311   /* ATIME */
2312   if (atime_value)
2313     {
2314       if (!get_uint64 (atime_value, &val, error))
2315         return FALSE;
2316       times[0].tv_sec = val;
2317     }
2318   else
2319     {
2320       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2321         {
2322           times[0].tv_sec = statbuf.st_mtime;
2323 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
2324           times[0].tv_usec = statbuf.st_atimensec / 1000;
2325 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2326           times[0].tv_usec = statbuf.st_atim.tv_nsec / 1000;
2327 #endif
2328         }
2329     }
2330   
2331   if (atime_usec_value)
2332     {
2333       if (!get_uint32 (atime_usec_value, &val_usec, error))
2334         return FALSE;
2335       times[0].tv_usec = val_usec;
2336     }
2337
2338   /* MTIME */
2339   if (mtime_value)
2340     {
2341       if (!get_uint64 (mtime_value, &val, error))
2342         return FALSE;
2343       times[1].tv_sec = val;
2344     }
2345   else
2346     {
2347       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2348         {
2349           times[1].tv_sec = statbuf.st_mtime;
2350 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
2351           times[1].tv_usec = statbuf.st_mtimensec / 1000;
2352 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
2353           times[1].tv_usec = statbuf.st_mtim.tv_nsec / 1000;
2354 #endif
2355         }
2356     }
2357   
2358   if (mtime_usec_value)
2359     {
2360       if (!get_uint32 (mtime_usec_value, &val_usec, error))
2361         return FALSE;
2362       times[1].tv_usec = val_usec;
2363     }
2364   
2365   res = utimes (filename, times);
2366   if (res == -1)
2367     {
2368       int errsv = errno;
2369
2370       g_set_error (error, G_IO_ERROR,
2371                    g_io_error_from_errno (errsv),
2372                    _("Error setting modification or access time: %s"),
2373                    g_strerror (errsv));
2374           return FALSE;
2375     }
2376   return TRUE;
2377 }
2378 #endif
2379
2380
2381 #ifdef HAVE_SELINUX
2382 static gboolean
2383 set_selinux_context (char                       *filename,
2384                  const GFileAttributeValue  *value,
2385                  GError                    **error)
2386 {
2387   const char *val;
2388
2389   if (!get_string (value, &val, error))
2390     return FALSE;
2391
2392   if (val == NULL)
2393   {
2394     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2395                          _("SELinux context must be non-NULL"));
2396     return FALSE;
2397   }
2398
2399   if (is_selinux_enabled ()) {
2400         security_context_t val_s;
2401         
2402         val_s = g_strdup (val);
2403         
2404         if (setfilecon_raw (filename, val_s) < 0)
2405         {
2406             int errsv = errno;
2407             
2408             g_set_error (error, G_IO_ERROR,
2409                          g_io_error_from_errno (errsv),
2410                         _("Error setting SELinux context: %s"),
2411                          g_strerror (errsv));
2412             return FALSE;
2413         }
2414         g_free (val_s);
2415   } else {
2416     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2417                          _("SELinux is not enabled on this system"));
2418     return FALSE;
2419   }
2420                                                      
2421   return TRUE;
2422 }
2423 #endif 
2424
2425
2426 gboolean
2427 _g_local_file_info_set_attribute (char                 *filename,
2428                                   const char           *attribute,
2429                                   GFileAttributeType    type,
2430                                   gpointer              value_p,
2431                                   GFileQueryInfoFlags   flags,
2432                                   GCancellable         *cancellable,
2433                                   GError              **error)
2434 {
2435   GFileAttributeValue value = { 0 };
2436   GVfsClass *class;
2437   GVfs *vfs;
2438
2439   _g_file_attribute_value_set_from_pointer (&value, type, value_p, FALSE);
2440   
2441   if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
2442     return set_unix_mode (filename, flags, &value, error);
2443   
2444 #ifdef G_OS_UNIX
2445   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_UID) == 0)
2446     return set_unix_uid_gid (filename, &value, NULL, flags, error);
2447   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_GID) == 0)
2448     return set_unix_uid_gid (filename, NULL, &value, flags, error);
2449 #endif
2450   
2451 #ifdef HAVE_SYMLINK
2452   else if (strcmp (attribute, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET) == 0)
2453     return set_symlink (filename, &value, error);
2454 #endif
2455
2456 #ifdef HAVE_UTIMES
2457   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED) == 0)
2458     return set_mtime_atime (filename, &value, NULL, NULL, NULL, error);
2459   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) == 0)
2460     return set_mtime_atime (filename, NULL, &value, NULL, NULL, error);
2461   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS) == 0)
2462     return set_mtime_atime (filename, NULL, NULL, &value, NULL, error);
2463   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) == 0)
2464     return set_mtime_atime (filename, NULL, NULL, NULL, &value, error);
2465 #endif
2466
2467 #ifdef HAVE_XATTR
2468   else if (g_str_has_prefix (attribute, "xattr::"))
2469     return set_xattr (filename, attribute, &value, error);
2470   else if (g_str_has_prefix (attribute, "xattr-sys::"))
2471     return set_xattr (filename, attribute, &value, error);
2472 #endif
2473
2474 #ifdef HAVE_SELINUX 
2475   else if (strcmp (attribute, G_FILE_ATTRIBUTE_SELINUX_CONTEXT) == 0)
2476     return set_selinux_context (filename, &value, error);
2477 #endif
2478
2479   vfs = g_vfs_get_default ();
2480   class = G_VFS_GET_CLASS (vfs);
2481   if (class->local_file_set_attributes)
2482     {
2483       GFileInfo *info;
2484
2485       info = g_file_info_new ();
2486       g_file_info_set_attribute (info,
2487                                  attribute,
2488                                  type,
2489                                  value_p);
2490       if (!class->local_file_set_attributes (vfs, filename,
2491                                              info,
2492                                              flags, cancellable,
2493                                              error))
2494         {
2495           g_object_unref (info);
2496           return FALSE;
2497         }
2498
2499       if (g_file_info_get_attribute_status (info, attribute) == G_FILE_ATTRIBUTE_STATUS_SET)
2500         {
2501           g_object_unref (info);
2502           return TRUE;
2503         }
2504
2505       g_object_unref (info);
2506     }
2507
2508   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2509                _("Setting attribute %s not supported"), attribute);
2510   return FALSE;
2511 }
2512
2513 gboolean
2514 _g_local_file_info_set_attributes  (char                 *filename,
2515                                     GFileInfo            *info,
2516                                     GFileQueryInfoFlags   flags,
2517                                     GCancellable         *cancellable,
2518                                     GError              **error)
2519 {
2520   GFileAttributeValue *value;
2521 #ifdef G_OS_UNIX
2522   GFileAttributeValue *uid, *gid;
2523 #ifdef HAVE_UTIMES
2524   GFileAttributeValue *mtime, *mtime_usec, *atime, *atime_usec;
2525 #endif
2526   GFileAttributeStatus status;
2527 #endif
2528   gboolean res;
2529   GVfsClass *class;
2530   GVfs *vfs;
2531   
2532   /* Handles setting multiple specified data in a single set, and takes care
2533      of ordering restrictions when setting attributes */
2534
2535   res = TRUE;
2536
2537   /* Set symlink first, since this recreates the file */
2538 #ifdef HAVE_SYMLINK
2539   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET);
2540   if (value)
2541     {
2542       if (!set_symlink (filename, value, error))
2543         {
2544           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2545           res = FALSE;
2546           /* Don't set error multiple times */
2547           error = NULL;
2548         }
2549       else
2550         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2551         
2552     }
2553 #endif
2554
2555 #ifdef G_OS_UNIX
2556   /* Group uid and gid setting into one call
2557    * Change ownership before permissions, since ownership changes can
2558      change permissions (e.g. setuid)
2559    */
2560   uid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_UID);
2561   gid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_GID);
2562   
2563   if (uid || gid)
2564     {
2565       if (!set_unix_uid_gid (filename, uid, gid, flags, error))
2566         {
2567           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2568           res = FALSE;
2569           /* Don't set error multiple times */
2570           error = NULL;
2571         }
2572       else
2573         status = G_FILE_ATTRIBUTE_STATUS_SET;
2574       if (uid)
2575         uid->status = status;
2576       if (gid)
2577         gid->status = status;
2578     }
2579 #endif
2580   
2581   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_MODE);
2582   if (value)
2583     {
2584       if (!set_unix_mode (filename, flags, value, error))
2585         {
2586           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2587           res = FALSE;
2588           /* Don't set error multiple times */
2589           error = NULL;
2590         }
2591       else
2592         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2593         
2594     }
2595
2596 #ifdef HAVE_UTIMES
2597   /* Group all time settings into one call
2598    * Change times as the last thing to avoid it changing due to metadata changes
2599    */
2600   
2601   mtime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
2602   mtime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
2603   atime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS);
2604   atime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC);
2605
2606   if (mtime || mtime_usec || atime || atime_usec)
2607     {
2608       if (!set_mtime_atime (filename, mtime, mtime_usec, atime, atime_usec, error))
2609         {
2610           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2611           res = FALSE;
2612           /* Don't set error multiple times */
2613           error = NULL;
2614         }
2615       else
2616         status = G_FILE_ATTRIBUTE_STATUS_SET;
2617       
2618       if (mtime)
2619         mtime->status = status;
2620       if (mtime_usec)
2621         mtime_usec->status = status;
2622       if (atime)
2623         atime->status = status;
2624       if (atime_usec)
2625         atime_usec->status = status;
2626     }
2627 #endif
2628
2629   /* xattrs are handled by default callback */
2630
2631
2632   /*  SELinux context */
2633 #ifdef HAVE_SELINUX 
2634   if (is_selinux_enabled ()) {
2635     value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_SELINUX_CONTEXT);
2636     if (value)
2637     {
2638       if (!set_selinux_context (filename, value, error))
2639         {
2640           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2641           res = FALSE;
2642           /* Don't set error multiple times */
2643           error = NULL;
2644         }
2645       else
2646         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2647     }
2648   }
2649 #endif
2650
2651   vfs = g_vfs_get_default ();
2652   class = G_VFS_GET_CLASS (vfs);
2653   if (class->local_file_set_attributes)
2654     {
2655       if (!class->local_file_set_attributes (vfs, filename,
2656                                              info,
2657                                              flags, cancellable,
2658                                              error))
2659         {
2660           res = FALSE;
2661           /* Don't set error multiple times */
2662           error = NULL;
2663         }
2664     }
2665
2666   return res;
2667 }