gio/: fully remove gioalias hacks
[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   GTimeVal tv;
123   
124   tv.tv_sec = statbuf->st_mtime;
125 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
126   tv.tv_usec = statbuf->st_mtimensec / 1000;
127 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
128   tv.tv_usec = statbuf->st_mtim.tv_nsec / 1000;
129 #else
130   tv.tv_usec = 0;
131 #endif
132
133   return g_strdup_printf ("%lu:%lu", tv.tv_sec, tv.tv_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 (S_ISDIR(statbuf->st_mode))
1220     return g_strdup ("inode/directory");
1221 #ifndef G_OS_WIN32
1222   else if (S_ISCHR(statbuf->st_mode))
1223     return g_strdup ("inode/chardevice");
1224   else if (S_ISBLK(statbuf->st_mode))
1225     return g_strdup ("inode/blockdevice");
1226   else if (S_ISFIFO(statbuf->st_mode))
1227     return g_strdup ("inode/fifo");
1228 #endif
1229 #ifdef S_ISSOCK
1230   else if (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 is_symlink, symlink_broken;
1425 #ifdef G_OS_WIN32
1426   DWORD dos_attributes;
1427 #endif
1428   char *symlink_target;
1429   GVfs *vfs;
1430   GVfsClass *class;
1431   guint64 device;
1432
1433   info = g_file_info_new ();
1434
1435   /* Make sure we don't set any unwanted attributes */
1436   g_file_info_set_attribute_mask (info, attribute_matcher);
1437   
1438   g_file_info_set_name (info, basename);
1439
1440   /* Avoid stat in trivial case */
1441   if (attribute_matcher == NULL)
1442     return info;
1443
1444 #ifndef G_OS_WIN32
1445   res = g_lstat (path, &statbuf);
1446 #else
1447   {
1448     wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
1449     int len;
1450
1451     if (wpath == NULL)
1452       {
1453         g_object_unref (info);
1454         return NULL;
1455       }
1456
1457     len = wcslen (wpath);
1458     while (len > 0 && G_IS_DIR_SEPARATOR (wpath[len-1]))
1459       len--;
1460     if (len > 0 &&
1461         (!g_path_is_absolute (path) || len > g_path_skip_root (path) - path))
1462       wpath[len] = '\0';
1463
1464     res = _wstati64 (wpath, &statbuf);
1465     dos_attributes = GetFileAttributesW (wpath);
1466
1467     g_free (wpath);
1468   }
1469 #endif
1470
1471   if (res == -1)
1472     {
1473       int errsv = errno;
1474       char *display_name = g_filename_display_name (path);
1475       g_object_unref (info);
1476       g_set_error (error, G_IO_ERROR,
1477                    g_io_error_from_errno (errsv),
1478                    _("Error stating file '%s': %s"),
1479                    display_name, g_strerror (errsv));
1480       g_free (display_name);
1481       return NULL;
1482     }
1483
1484   device = statbuf.st_dev;
1485
1486 #ifdef S_ISLNK
1487   is_symlink = S_ISLNK (statbuf.st_mode);
1488 #else
1489   is_symlink = FALSE;
1490 #endif
1491   symlink_broken = FALSE;
1492 #ifdef S_ISLNK
1493   if (is_symlink)
1494     {
1495       g_file_info_set_is_symlink (info, TRUE);
1496
1497       /* Unless NOFOLLOW was set we default to following symlinks */
1498       if (!(flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS))
1499         {
1500           res = stat (path, &statbuf2);
1501
1502             /* Report broken links as symlinks */
1503           if (res != -1)
1504             statbuf = statbuf2;
1505           else
1506             symlink_broken = TRUE;
1507         }
1508     }
1509 #endif
1510
1511   set_info_from_stat (info, &statbuf, attribute_matcher);
1512   
1513 #ifndef G_OS_WIN32
1514   if (basename != NULL && basename[0] == '.')
1515     g_file_info_set_is_hidden (info, TRUE);
1516
1517   if (basename != NULL && basename[strlen (basename) -1] == '~' &&
1518       S_ISREG (statbuf.st_mode))
1519     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_IS_BACKUP, TRUE);
1520 #else
1521   if (dos_attributes & FILE_ATTRIBUTE_HIDDEN)
1522     g_file_info_set_is_hidden (info, TRUE);
1523
1524   if (dos_attributes & FILE_ATTRIBUTE_ARCHIVE)
1525     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_ARCHIVE, TRUE);
1526
1527   if (dos_attributes & FILE_ATTRIBUTE_SYSTEM)
1528     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_DOS_IS_SYSTEM, TRUE);
1529 #endif
1530
1531   symlink_target = NULL;
1532 #ifdef S_ISLNK
1533   if (is_symlink)
1534     {
1535       symlink_target = read_link (path);
1536       if (symlink_target &&
1537           _g_file_attribute_matcher_matches_id (attribute_matcher,
1538                                                 G_FILE_ATTRIBUTE_ID_STANDARD_SYMLINK_TARGET))
1539         g_file_info_set_symlink_target (info, symlink_target);
1540     }
1541 #endif
1542   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1543                                             G_FILE_ATTRIBUTE_ID_STANDARD_DISPLAY_NAME))
1544     {
1545       char *display_name = g_filename_display_basename (path);
1546      
1547       /* look for U+FFFD REPLACEMENT CHARACTER */ 
1548       if (strstr (display_name, "\357\277\275") != NULL)
1549         {
1550           char *p = display_name;
1551           display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
1552           g_free (p);
1553         }
1554       g_file_info_set_display_name (info, display_name);
1555       g_free (display_name);
1556     }
1557   
1558   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1559                                             G_FILE_ATTRIBUTE_ID_STANDARD_EDIT_NAME))
1560     {
1561       char *edit_name = g_filename_display_basename (path);
1562       g_file_info_set_edit_name (info, edit_name);
1563       g_free (edit_name);
1564     }
1565
1566   
1567   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1568                                             G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME))
1569     {
1570       char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
1571       if (copy_name)
1572         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME, copy_name);
1573       g_free (copy_name);
1574     }
1575
1576   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1577                                             G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
1578       _g_file_attribute_matcher_matches_id (attribute_matcher,
1579                                             G_FILE_ATTRIBUTE_ID_STANDARD_ICON))
1580     {
1581       char *content_type = get_content_type (basename, path, &statbuf, is_symlink, symlink_broken, flags, FALSE);
1582
1583       if (content_type)
1584         {
1585           g_file_info_set_content_type (info, content_type);
1586
1587           if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1588                                                     G_FILE_ATTRIBUTE_ID_STANDARD_ICON))
1589             {
1590               GIcon *icon;
1591
1592               if (strcmp (path, g_get_home_dir ()) == 0)
1593                 icon = g_themed_icon_new ("user-home");
1594               else if (strcmp (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
1595                 icon = g_themed_icon_new ("user-desktop");
1596               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS)) == 0)
1597                 icon = g_themed_icon_new_with_default_fallbacks ("folder-documents");
1598               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD)) == 0)
1599                 icon = g_themed_icon_new_with_default_fallbacks ("folder-download");
1600               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_MUSIC)) == 0)
1601                 icon = g_themed_icon_new_with_default_fallbacks ("folder-music");
1602               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PICTURES)) == 0)
1603                 icon = g_themed_icon_new_with_default_fallbacks ("folder-pictures");
1604               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE)) == 0)
1605                 icon = g_themed_icon_new_with_default_fallbacks ("folder-publicshare");
1606               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES)) == 0)
1607                 icon = g_themed_icon_new_with_default_fallbacks ("folder-templates");
1608               else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS)) == 0)
1609                 icon = g_themed_icon_new_with_default_fallbacks ("folder-videos");
1610               else
1611                 {
1612                   icon = g_content_type_get_icon (content_type);
1613                   if (G_IS_THEMED_ICON (icon))
1614                     {
1615                       const char *type_icon = NULL;
1616
1617                       if (S_ISDIR (statbuf.st_mode)) 
1618                         type_icon = "folder";
1619                       if (type_icon)
1620                         g_themed_icon_append_name (G_THEMED_ICON (icon), type_icon);
1621                     }
1622                 }
1623
1624               if (icon != NULL)
1625                 {
1626                   g_file_info_set_icon (info, icon);
1627                   g_object_unref (icon);
1628                 }
1629             }
1630           
1631           g_free (content_type);
1632         }
1633     }
1634
1635   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1636                                             G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))
1637     {
1638       char *content_type = get_content_type (basename, path, &statbuf, is_symlink, symlink_broken, flags, TRUE);
1639       
1640       if (content_type)
1641         {
1642           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);
1643           g_free (content_type);
1644         }
1645     }
1646
1647   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1648                                             G_FILE_ATTRIBUTE_ID_OWNER_USER))
1649     {
1650       char *name = NULL;
1651       
1652 #ifdef G_OS_WIN32
1653       win32_get_file_user_info (path, NULL, &name, NULL);
1654 #else
1655       name = get_username_from_uid (statbuf.st_uid);
1656 #endif
1657       if (name)
1658         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER, name);
1659       g_free (name);
1660     }
1661
1662   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1663                                             G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL))
1664     {
1665       char *name = NULL;
1666 #ifdef G_OS_WIN32
1667       win32_get_file_user_info (path, NULL, NULL, &name);
1668 #else
1669       name = get_realname_from_uid (statbuf.st_uid);
1670 #endif
1671       if (name)
1672         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_USER_REAL, name);
1673       g_free (name);
1674     }
1675   
1676   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1677                                             G_FILE_ATTRIBUTE_ID_OWNER_GROUP))
1678     {
1679       char *name = NULL;
1680 #ifdef G_OS_WIN32
1681       win32_get_file_user_info (path, &name, NULL, NULL);
1682 #else
1683       name = get_groupname_from_gid (statbuf.st_gid);
1684 #endif
1685       if (name)
1686         _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_OWNER_GROUP, name);
1687       g_free (name);
1688     }
1689
1690   if (parent_info && parent_info->device != 0 &&
1691       _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT) &&
1692       statbuf.st_dev != parent_info->device) 
1693     _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT, TRUE);
1694   
1695   get_access_rights (attribute_matcher, info, path, &statbuf, parent_info);
1696   
1697 #ifdef HAVE_SELINUX
1698   get_selinux_context (path, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1699 #endif
1700   get_xattrs (path, TRUE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1701   get_xattrs (path, FALSE, info, attribute_matcher, (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) == 0);
1702
1703   if (_g_file_attribute_matcher_matches_id (attribute_matcher,
1704                                             G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH))
1705     get_thumbnail_attributes (path, info);
1706
1707   vfs = g_vfs_get_default ();
1708   class = G_VFS_GET_CLASS (vfs);
1709   if (class->local_file_add_info)
1710     {
1711       class->local_file_add_info (vfs,
1712                                   path,
1713                                   device,
1714                                   attribute_matcher,
1715                                   info,
1716                                   NULL,
1717                                   &parent_info->extra_data,
1718                                   &parent_info->free_extra_data);
1719     }
1720
1721   g_file_info_unset_attribute_mask (info);
1722
1723   g_free (symlink_target);
1724
1725   return info;
1726 }
1727
1728 GFileInfo *
1729 _g_local_file_info_get_from_fd (int         fd,
1730                                 const char *attributes,
1731                                 GError    **error)
1732 {
1733   GLocalFileStat stat_buf;
1734   GFileAttributeMatcher *matcher;
1735   GFileInfo *info;
1736   
1737 #ifdef G_OS_WIN32
1738 #define FSTAT _fstati64
1739 #else
1740 #define FSTAT fstat
1741 #endif
1742
1743   if (FSTAT (fd, &stat_buf) == -1)
1744     {
1745       int errsv = errno;
1746
1747       g_set_error (error, G_IO_ERROR,
1748                    g_io_error_from_errno (errsv),
1749                    _("Error stating file descriptor: %s"),
1750                    g_strerror (errsv));
1751       return NULL;
1752     }
1753
1754   info = g_file_info_new ();
1755
1756   matcher = g_file_attribute_matcher_new (attributes);
1757
1758   /* Make sure we don't set any unwanted attributes */
1759   g_file_info_set_attribute_mask (info, matcher);
1760   
1761   set_info_from_stat (info, &stat_buf, matcher);
1762   
1763 #ifdef HAVE_SELINUX
1764   if (_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT) &&
1765       is_selinux_enabled ())
1766     {
1767       char *context;
1768       if (fgetfilecon_raw (fd, &context) >= 0)
1769         {
1770           _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
1771           freecon (context);
1772         }
1773     }
1774 #endif
1775
1776   get_xattrs_from_fd (fd, TRUE, info, matcher);
1777   get_xattrs_from_fd (fd, FALSE, info, matcher);
1778   
1779   g_file_attribute_matcher_unref (matcher);
1780
1781   g_file_info_unset_attribute_mask (info);
1782   
1783   return info;
1784 }
1785
1786 static gboolean
1787 get_uint32 (const GFileAttributeValue  *value,
1788             guint32                    *val_out,
1789             GError                    **error)
1790 {
1791   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT32)
1792     {
1793       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1794                            _("Invalid attribute type (uint32 expected)"));
1795       return FALSE;
1796     }
1797
1798   *val_out = value->u.uint32;
1799   
1800   return TRUE;
1801 }
1802
1803 #ifdef HAVE_UTIMES
1804 static gboolean
1805 get_uint64 (const GFileAttributeValue  *value,
1806             guint64                    *val_out,
1807             GError                    **error)
1808 {
1809   if (value->type != G_FILE_ATTRIBUTE_TYPE_UINT64)
1810     {
1811       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1812                            _("Invalid attribute type (uint64 expected)"));
1813       return FALSE;
1814     }
1815
1816   *val_out = value->u.uint64;
1817   
1818   return TRUE;
1819 }
1820 #endif
1821
1822 #if defined(HAVE_SYMLINK)
1823 static gboolean
1824 get_byte_string (const GFileAttributeValue  *value,
1825                  const char                **val_out,
1826                  GError                    **error)
1827 {
1828   if (value->type != G_FILE_ATTRIBUTE_TYPE_BYTE_STRING)
1829     {
1830       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1831                            _("Invalid attribute type (byte string expected)"));
1832       return FALSE;
1833     }
1834
1835   *val_out = value->u.string;
1836   
1837   return TRUE;
1838 }
1839 #endif
1840
1841 #ifdef HAVE_SELINUX
1842 static gboolean
1843 get_string (const GFileAttributeValue  *value,
1844             const char                **val_out,
1845             GError                    **error)
1846 {
1847   if (value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
1848     {
1849       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1850                            _("Invalid attribute type (byte string expected)"));
1851       return FALSE;
1852     }
1853
1854   *val_out = value->u.string;
1855   
1856   return TRUE;
1857 }
1858 #endif
1859
1860 static gboolean
1861 set_unix_mode (char                       *filename,
1862                GFileQueryInfoFlags         flags,
1863                const GFileAttributeValue  *value,
1864                GError                    **error)
1865 {
1866   guint32 val;
1867   int res = 0;
1868   
1869   if (!get_uint32 (value, &val, error))
1870     return FALSE;
1871
1872 #ifdef HAVE_SYMLINK
1873   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS) {
1874 #ifdef HAVE_LCHMOD
1875     res = lchmod (filename, val);
1876 #else
1877     struct stat statbuf;
1878     /* Calling chmod on a symlink changes permissions on the symlink.
1879      * We don't want to do this, so we need to check for a symlink */
1880     res = g_lstat (filename, &statbuf);
1881     if (res == 0 && S_ISLNK (statbuf.st_mode))
1882       {
1883         g_set_error_literal (error, G_IO_ERROR,
1884                              G_IO_ERROR_NOT_SUPPORTED,
1885                              _("Cannot set permissions on symlinks"));
1886         return FALSE;
1887       }
1888     else if (res == 0)
1889       res = g_chmod (filename, val);
1890 #endif
1891   } else
1892 #endif
1893     res = g_chmod (filename, val);
1894
1895   if (res == -1)
1896     {
1897       int errsv = errno;
1898
1899       g_set_error (error, G_IO_ERROR,
1900                    g_io_error_from_errno (errsv),
1901                    _("Error setting permissions: %s"),
1902                    g_strerror (errsv));
1903       return FALSE;
1904     }
1905   return TRUE;
1906 }
1907
1908 #ifdef HAVE_CHOWN
1909 static gboolean
1910 set_unix_uid_gid (char                       *filename,
1911                   const GFileAttributeValue  *uid_value,
1912                   const GFileAttributeValue  *gid_value,
1913                   GFileQueryInfoFlags         flags,
1914                   GError                    **error)
1915 {
1916   int res;
1917   guint32 val;
1918   uid_t uid;
1919   gid_t gid;
1920   
1921   if (uid_value)
1922     {
1923       if (!get_uint32 (uid_value, &val, error))
1924         return FALSE;
1925       uid = val;
1926     }
1927   else
1928     uid = -1;
1929   
1930   if (gid_value)
1931     {
1932       if (!get_uint32 (gid_value, &val, error))
1933         return FALSE;
1934       gid = val;
1935     }
1936   else
1937     gid = -1;
1938   
1939 #ifdef HAVE_LCHOWN
1940   if (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)
1941     res = lchown (filename, uid, gid);
1942   else
1943 #endif
1944     res = chown (filename, uid, gid);
1945   
1946   if (res == -1)
1947     {
1948       int errsv = errno;
1949
1950       g_set_error (error, G_IO_ERROR,
1951                    g_io_error_from_errno (errsv),
1952                    _("Error setting owner: %s"),
1953                    g_strerror (errsv));
1954           return FALSE;
1955     }
1956   return TRUE;
1957 }
1958 #endif
1959
1960 #ifdef HAVE_SYMLINK
1961 static gboolean
1962 set_symlink (char                       *filename,
1963              const GFileAttributeValue  *value,
1964              GError                    **error)
1965 {
1966   const char *val;
1967   struct stat statbuf;
1968   
1969   if (!get_byte_string (value, &val, error))
1970     return FALSE;
1971   
1972   if (val == NULL)
1973     {
1974       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
1975                            _("symlink must be non-NULL"));
1976       return FALSE;
1977     }
1978   
1979   if (g_lstat (filename, &statbuf))
1980     {
1981       int errsv = errno;
1982
1983       g_set_error (error, G_IO_ERROR,
1984                    g_io_error_from_errno (errsv),
1985                    _("Error setting symlink: %s"),
1986                    g_strerror (errsv));
1987       return FALSE;
1988     }
1989   
1990   if (!S_ISLNK (statbuf.st_mode))
1991     {
1992       g_set_error_literal (error, G_IO_ERROR,
1993                            G_IO_ERROR_NOT_SYMBOLIC_LINK,
1994                            _("Error setting symlink: file is not a symlink"));
1995       return FALSE;
1996     }
1997   
1998   if (g_unlink (filename))
1999     {
2000       int errsv = errno;
2001
2002       g_set_error (error, G_IO_ERROR,
2003                    g_io_error_from_errno (errsv),
2004                    _("Error setting symlink: %s"),
2005                    g_strerror (errsv));
2006       return FALSE;
2007     }
2008   
2009   if (symlink (filename, val) != 0)
2010     {
2011       int errsv = errno;
2012
2013       g_set_error (error, G_IO_ERROR,
2014                    g_io_error_from_errno (errsv),
2015                    _("Error setting symlink: %s"),
2016                    g_strerror (errsv));
2017       return FALSE;
2018     }
2019   
2020   return TRUE;
2021 }
2022 #endif
2023
2024 #ifdef HAVE_UTIMES
2025 static int
2026 lazy_stat (char        *filename, 
2027            struct stat *statbuf, 
2028            gboolean    *called_stat)
2029 {
2030   int res;
2031
2032   if (*called_stat)
2033     return 0;
2034   
2035   res = g_stat (filename, statbuf);
2036   
2037   if (res == 0)
2038     *called_stat = TRUE;
2039   
2040   return res;
2041 }
2042
2043
2044 static gboolean
2045 set_mtime_atime (char                       *filename,
2046                  const GFileAttributeValue  *mtime_value,
2047                  const GFileAttributeValue  *mtime_usec_value,
2048                  const GFileAttributeValue  *atime_value,
2049                  const GFileAttributeValue  *atime_usec_value,
2050                  GError                    **error)
2051 {
2052   int res;
2053   guint64 val;
2054   guint32 val_usec;
2055   struct stat statbuf;
2056   gboolean got_stat = FALSE;
2057   struct timeval times[2] = { {0, 0}, {0, 0} };
2058
2059   /* ATIME */
2060   if (atime_value)
2061     {
2062       if (!get_uint64 (atime_value, &val, error))
2063         return FALSE;
2064       times[0].tv_sec = val;
2065     }
2066   else
2067     {
2068       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2069         {
2070           times[0].tv_sec = statbuf.st_mtime;
2071 #if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
2072           times[0].tv_usec = statbuf.st_atimensec / 1000;
2073 #elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
2074           times[0].tv_usec = statbuf.st_atim.tv_nsec / 1000;
2075 #endif
2076         }
2077     }
2078   
2079   if (atime_usec_value)
2080     {
2081       if (!get_uint32 (atime_usec_value, &val_usec, error))
2082         return FALSE;
2083       times[0].tv_usec = val_usec;
2084     }
2085
2086   /* MTIME */
2087   if (mtime_value)
2088     {
2089       if (!get_uint64 (mtime_value, &val, error))
2090         return FALSE;
2091       times[1].tv_sec = val;
2092     }
2093   else
2094     {
2095       if (lazy_stat (filename, &statbuf, &got_stat) == 0)
2096         {
2097           times[1].tv_sec = statbuf.st_mtime;
2098 #if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
2099           times[1].tv_usec = statbuf.st_mtimensec / 1000;
2100 #elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
2101           times[1].tv_usec = statbuf.st_mtim.tv_nsec / 1000;
2102 #endif
2103         }
2104     }
2105   
2106   if (mtime_usec_value)
2107     {
2108       if (!get_uint32 (mtime_usec_value, &val_usec, error))
2109         return FALSE;
2110       times[1].tv_usec = val_usec;
2111     }
2112   
2113   res = utimes (filename, times);
2114   if (res == -1)
2115     {
2116       int errsv = errno;
2117
2118       g_set_error (error, G_IO_ERROR,
2119                    g_io_error_from_errno (errsv),
2120                    _("Error setting modification or access time: %s"),
2121                    g_strerror (errsv));
2122           return FALSE;
2123     }
2124   return TRUE;
2125 }
2126 #endif
2127
2128
2129 #ifdef HAVE_SELINUX
2130 static gboolean
2131 set_selinux_context (char                       *filename,
2132                  const GFileAttributeValue  *value,
2133                  GError                    **error)
2134 {
2135   const char *val;
2136
2137   if (!get_string (value, &val, error))
2138     return FALSE;
2139
2140   if (val == NULL)
2141   {
2142     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2143                          _("SELinux context must be non-NULL"));
2144     return FALSE;
2145   }
2146
2147   if (is_selinux_enabled ()) {
2148         security_context_t val_s;
2149         
2150         val_s = g_strdup (val);
2151         
2152         if (setfilecon_raw (filename, val_s) < 0)
2153         {
2154             int errsv = errno;
2155             
2156             g_set_error (error, G_IO_ERROR,
2157                          g_io_error_from_errno (errsv),
2158                         _("Error setting SELinux context: %s"),
2159                          g_strerror (errsv));
2160             return FALSE;
2161         }
2162         g_free (val_s);
2163   } else {
2164     g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2165                          _("SELinux is not enabled on this system"));
2166     return FALSE;
2167   }
2168                                                      
2169   return TRUE;
2170 }
2171 #endif 
2172
2173
2174 gboolean
2175 _g_local_file_info_set_attribute (char                 *filename,
2176                                   const char           *attribute,
2177                                   GFileAttributeType    type,
2178                                   gpointer              value_p,
2179                                   GFileQueryInfoFlags   flags,
2180                                   GCancellable         *cancellable,
2181                                   GError              **error)
2182 {
2183   GFileAttributeValue value = { 0 };
2184   GVfsClass *class;
2185   GVfs *vfs;
2186
2187   _g_file_attribute_value_set_from_pointer (&value, type, value_p, FALSE);
2188   
2189   if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_MODE) == 0)
2190     return set_unix_mode (filename, flags, &value, error);
2191   
2192 #ifdef HAVE_CHOWN
2193   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_UID) == 0)
2194     return set_unix_uid_gid (filename, &value, NULL, flags, error);
2195   else if (strcmp (attribute, G_FILE_ATTRIBUTE_UNIX_GID) == 0)
2196     return set_unix_uid_gid (filename, NULL, &value, flags, error);
2197 #endif
2198   
2199 #ifdef HAVE_SYMLINK
2200   else if (strcmp (attribute, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET) == 0)
2201     return set_symlink (filename, &value, error);
2202 #endif
2203
2204 #ifdef HAVE_UTIMES
2205   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED) == 0)
2206     return set_mtime_atime (filename, &value, NULL, NULL, NULL, error);
2207   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) == 0)
2208     return set_mtime_atime (filename, NULL, &value, NULL, NULL, error);
2209   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS) == 0)
2210     return set_mtime_atime (filename, NULL, NULL, &value, NULL, error);
2211   else if (strcmp (attribute, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) == 0)
2212     return set_mtime_atime (filename, NULL, NULL, NULL, &value, error);
2213 #endif
2214
2215 #ifdef HAVE_XATTR
2216   else if (g_str_has_prefix (attribute, "xattr::"))
2217     return set_xattr (filename, attribute, &value, error);
2218   else if (g_str_has_prefix (attribute, "xattr-sys::"))
2219     return set_xattr (filename, attribute, &value, error);
2220 #endif
2221
2222 #ifdef HAVE_SELINUX 
2223   else if (strcmp (attribute, G_FILE_ATTRIBUTE_SELINUX_CONTEXT) == 0)
2224     return set_selinux_context (filename, &value, error);
2225 #endif
2226
2227   vfs = g_vfs_get_default ();
2228   class = G_VFS_GET_CLASS (vfs);
2229   if (class->local_file_set_attributes)
2230     {
2231       GFileInfo *info;
2232
2233       info = g_file_info_new ();
2234       g_file_info_set_attribute (info,
2235                                  attribute,
2236                                  type,
2237                                  value_p);
2238       if (!class->local_file_set_attributes (vfs, filename,
2239                                              info,
2240                                              flags, cancellable,
2241                                              error))
2242         {
2243           g_object_unref (info);
2244           return FALSE;
2245         }
2246
2247       if (g_file_info_get_attribute_status (info, attribute) == G_FILE_ATTRIBUTE_STATUS_SET)
2248         {
2249           g_object_unref (info);
2250           return TRUE;
2251         }
2252
2253       g_object_unref (info);
2254     }
2255
2256   g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
2257                _("Setting attribute %s not supported"), attribute);
2258   return FALSE;
2259 }
2260
2261 gboolean
2262 _g_local_file_info_set_attributes  (char                 *filename,
2263                                     GFileInfo            *info,
2264                                     GFileQueryInfoFlags   flags,
2265                                     GCancellable         *cancellable,
2266                                     GError              **error)
2267 {
2268   GFileAttributeValue *value;
2269 #ifdef HAVE_CHOWN
2270   GFileAttributeValue *uid, *gid;
2271 #endif
2272 #ifdef HAVE_UTIMES
2273   GFileAttributeValue *mtime, *mtime_usec, *atime, *atime_usec;
2274 #endif
2275 #if defined (HAVE_CHOWN) || defined (HAVE_UTIMES)
2276   GFileAttributeStatus status;
2277 #endif
2278   gboolean res;
2279   GVfsClass *class;
2280   GVfs *vfs;
2281   
2282   /* Handles setting multiple specified data in a single set, and takes care
2283      of ordering restrictions when setting attributes */
2284
2285   res = TRUE;
2286
2287   /* Set symlink first, since this recreates the file */
2288 #ifdef HAVE_SYMLINK
2289   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET);
2290   if (value)
2291     {
2292       if (!set_symlink (filename, value, error))
2293         {
2294           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2295           res = FALSE;
2296           /* Don't set error multiple times */
2297           error = NULL;
2298         }
2299       else
2300         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2301         
2302     }
2303 #endif
2304
2305 #ifdef HAVE_CHOWN
2306   /* Group uid and gid setting into one call
2307    * Change ownership before permissions, since ownership changes can
2308      change permissions (e.g. setuid)
2309    */
2310   uid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_UID);
2311   gid = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_GID);
2312   
2313   if (uid || gid)
2314     {
2315       if (!set_unix_uid_gid (filename, uid, gid, flags, error))
2316         {
2317           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2318           res = FALSE;
2319           /* Don't set error multiple times */
2320           error = NULL;
2321         }
2322       else
2323         status = G_FILE_ATTRIBUTE_STATUS_SET;
2324       if (uid)
2325         uid->status = status;
2326       if (gid)
2327         gid->status = status;
2328     }
2329 #endif
2330   
2331   value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_UNIX_MODE);
2332   if (value)
2333     {
2334       if (!set_unix_mode (filename, flags, value, error))
2335         {
2336           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2337           res = FALSE;
2338           /* Don't set error multiple times */
2339           error = NULL;
2340         }
2341       else
2342         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2343         
2344     }
2345
2346 #ifdef HAVE_UTIMES
2347   /* Group all time settings into one call
2348    * Change times as the last thing to avoid it changing due to metadata changes
2349    */
2350   
2351   mtime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED);
2352   mtime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC);
2353   atime = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS);
2354   atime_usec = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC);
2355
2356   if (mtime || mtime_usec || atime || atime_usec)
2357     {
2358       if (!set_mtime_atime (filename, mtime, mtime_usec, atime, atime_usec, error))
2359         {
2360           status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2361           res = FALSE;
2362           /* Don't set error multiple times */
2363           error = NULL;
2364         }
2365       else
2366         status = G_FILE_ATTRIBUTE_STATUS_SET;
2367       
2368       if (mtime)
2369         mtime->status = status;
2370       if (mtime_usec)
2371         mtime_usec->status = status;
2372       if (atime)
2373         atime->status = status;
2374       if (atime_usec)
2375         atime_usec->status = status;
2376     }
2377 #endif
2378
2379   /* xattrs are handled by default callback */
2380
2381
2382   /*  SELinux context */
2383 #ifdef HAVE_SELINUX 
2384   if (is_selinux_enabled ()) {
2385     value = _g_file_info_get_attribute_value (info, G_FILE_ATTRIBUTE_SELINUX_CONTEXT);
2386     if (value)
2387     {
2388       if (!set_selinux_context (filename, value, error))
2389         {
2390           value->status = G_FILE_ATTRIBUTE_STATUS_ERROR_SETTING;
2391           res = FALSE;
2392           /* Don't set error multiple times */
2393           error = NULL;
2394         }
2395       else
2396         value->status = G_FILE_ATTRIBUTE_STATUS_SET;
2397     }
2398   }
2399 #endif
2400
2401   vfs = g_vfs_get_default ();
2402   class = G_VFS_GET_CLASS (vfs);
2403   if (class->local_file_set_attributes)
2404     {
2405       if (!class->local_file_set_attributes (vfs, filename,
2406                                              info,
2407                                              flags, cancellable,
2408                                              error))
2409         {
2410           res = FALSE;
2411           /* Don't set error multiple times */
2412           error = NULL;
2413         }
2414     }
2415
2416   return res;
2417 }