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