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