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