glocalfileinfo.c 69.9 KB
Newer Older
1 2
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* GIO - GLib Input, Output and Streaming Library
 * 
 * Copyright (C) 2006-2007 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
18
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 20 21 22
 *
 * Author: Alexander Larsson <alexl@redhat.com>
 */

23
#include "config.h"
24

25 26
#include <glib.h>

27
#ifdef HAVE_SYS_TIME_H
28
#include <sys/time.h>
29
#endif
30 31 32 33 34
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
35
#ifdef G_OS_UNIX
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include <grp.h>
#include <pwd.h>
#endif
#ifdef HAVE_SELINUX
#include <selinux/selinux.h>
#endif

#ifdef HAVE_XATTR

#if defined HAVE_SYS_XATTR_H
  #include <sys/xattr.h>
#elif defined HAVE_ATTR_XATTR_H
  #include <attr/xattr.h>
#else
  #error "Neither <sys/xattr.h> nor <attr/xattr.h> is present but extended attribute support is enabled."
#endif /* defined HAVE_SYS_XATTR_H || HAVE_ATTR_XATTR_H */

#endif /* HAVE_XATTR */

#include <glib/gstdio.h>
56
#include <gfileattribute-priv.h>
57
#include <gfileinfo-priv.h>
58
#include <gvfs.h>
59

60 61
#ifdef G_OS_UNIX
#include <unistd.h>
Colin Walters's avatar
Colin Walters committed
62
#include "glib-unix.h"
63 64
#include "glib-private.h"
#endif
65

66 67
#include "thumbnail-verify.h"

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
#ifdef G_OS_WIN32
#include <windows.h>
#include <io.h>
#ifndef W_OK
#define W_OK 2
#endif
#ifndef R_OK
#define R_OK 4
#endif
#ifndef X_OK
#define X_OK 0 /* not really */
#endif
#ifndef S_ISREG
#define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
#endif
#ifndef S_ISDIR
#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
#endif
#ifndef S_IXUSR
#define S_IXUSR _S_IEXEC
#endif
#endif

91 92 93 94
#include "glocalfileinfo.h"
#include "gioerror.h"
#include "gthemedicon.h"
#include "gcontenttypeprivate.h"
95
#include "glibintl.h"
96

97

98 99 100 101 102
struct ThumbMD5Context {
	guint32 buf[4];
	guint32 bits[2];
	unsigned char in[64];
};
103

104
#ifndef G_OS_WIN32
105

106 107 108 109
typedef struct {
  char *user_name;
  char *real_name;
} UidData;
110

111 112 113 114 115 116
G_LOCK_DEFINE_STATIC (uid_cache);
static GHashTable *uid_cache = NULL;

G_LOCK_DEFINE_STATIC (gid_cache);
static GHashTable *gid_cache = NULL;

117 118
#endif  /* !G_OS_WIN32 */

119
char *
120
_g_local_file_info_create_etag (GLocalFileStat *statbuf)
121
{
122 123 124
  glong sec, usec;

  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 132
#endif

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 140 141 142 143 144
{
  return g_strdup_printf ("l%" G_GUINT64_FORMAT ":%" G_GUINT64_FORMAT,
			  (guint64) statbuf->st_dev, 
			  (guint64) statbuf->st_ino);
}

static char *
145
_g_local_file_info_create_fs_id (GLocalFileStat *statbuf)
146 147 148 149 150 151
{
  return g_strdup_printf ("l%" G_GUINT64_FORMAT,
			  (guint64) statbuf->st_dev);
}


152 153
#ifdef S_ISLNK

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
static gchar *
read_link (const gchar *full_name)
{
#ifdef HAVE_READLINK
  gchar *buffer;
  guint size;
  
  size = 256;
  buffer = g_malloc (size);
  
  while (1)
    {
      int read_size;
      
      read_size = readlink (full_name, buffer, size);
      if (read_size < 0)
	{
	  g_free (buffer);
	  return NULL;
	}
      if (read_size < size)
	{
	  buffer[read_size] = 0;
	  return buffer;
	}
      size *= 2;
      buffer = g_realloc (buffer, size);
    }
#else
  return NULL;
#endif
}

187 188
#endif  /* S_ISLNK */

189
#ifdef HAVE_SELINUX
190 191
/* Get the SELinux security context */
static void
192 193
get_selinux_context (const char            *path,
		     GFileInfo             *info,
194
		     GFileAttributeMatcher *attribute_matcher,
195
		     gboolean               follow_symlinks)
196 197 198
{
  char *context;

199
  if (!_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT))
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    return;
  
  if (is_selinux_enabled ())
    {
      if (follow_symlinks)
	{
	  if (lgetfilecon_raw (path, &context) < 0)
	    return;
	}
      else
	{
	  if (getfilecon_raw (path, &context) < 0)
	    return;
	}

      if (context)
	{
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 225

#ifdef HAVE_XATTR

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
/* Wrappers to hide away differences between (Linux) getxattr/lgetxattr and
 * (Mac) getxattr(..., XATTR_NOFOLLOW)
 */
#ifdef HAVE_XATTR_NOFOLLOW
#define g_fgetxattr(fd,name,value,size)  fgetxattr(fd,name,value,size,0,0)
#define g_flistxattr(fd,name,size)       flistxattr(fd,name,size,0)
#define g_setxattr(path,name,value,size) setxattr(path,name,value,size,0,0)
#else
#define g_fgetxattr     fgetxattr
#define g_flistxattr    flistxattr
#define g_setxattr(path,name,value,size) setxattr(path,name,value,size,0)
#endif

static ssize_t
g_getxattr (const char *path, const char *name, void *value, size_t size,
            gboolean follow_symlinks)
{
#ifdef HAVE_XATTR_NOFOLLOW
  return getxattr (path, name, value, size, 0, follow_symlinks ? 0 : XATTR_NOFOLLOW);
#else
  if (follow_symlinks)
    return getxattr (path, name, value, size);
  else
    return lgetxattr (path, name, value, size);
#endif
}

static ssize_t
g_listxattr(const char *path, char *namebuf, size_t size,
            gboolean follow_symlinks)
{
#ifdef HAVE_XATTR_NOFOLLOW
  return listxattr (path, namebuf, size, follow_symlinks ? 0 : XATTR_NOFOLLOW);
#else
  if (follow_symlinks)
    return listxattr (path, namebuf, size);
  else
    return llistxattr (path, namebuf, size);
#endif
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
static gboolean
valid_char (char c)
{
  return c >= 32 && c <= 126 && c != '\\';
}

static gboolean
name_is_valid (const char *str)
{
  while (*str)
    {
      if (!valid_char (*str++))
	return FALSE;
    }
  return TRUE;
}

static char *
285 286
hex_escape_string (const char *str, 
                   gboolean   *free_return)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
{
  int num_invalid, i;
  char *escaped_str, *p;
  unsigned char c;
  static char *hex_digits = "0123456789abcdef";
  int len;

  len = strlen (str);
  
  num_invalid = 0;
  for (i = 0; i < len; i++)
    {
      if (!valid_char (str[i]))
	num_invalid++;
    }

  if (num_invalid == 0)
    {
      *free_return = FALSE;
      return (char *)str;
    }

  escaped_str = g_malloc (len + num_invalid*3 + 1);

  p = escaped_str;
  for (i = 0; i < len; i++)
    {
      if (valid_char (str[i]))
	*p++ = str[i];
      else
	{
	  c = str[i];
	  *p++ = '\\';
	  *p++ = 'x';
	  *p++ = hex_digits[(c >> 4) & 0xf];
	  *p++ = hex_digits[c & 0xf];
	}
    }
325
  *p = 0;
326 327 328 329 330 331

  *free_return = TRUE;
  return escaped_str;
}

static char *
332 333 334
hex_unescape_string (const char *str, 
                     int        *out_len, 
                     gboolean   *free_return)
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
{
  int i;
  char *unescaped_str, *p;
  unsigned char c;
  int len;

  len = strlen (str);
  
  if (strchr (str, '\\') == NULL)
    {
      if (out_len)
	*out_len = len;
      *free_return = FALSE;
      return (char *)str;
    }
  
  unescaped_str = g_malloc (len + 1);

  p = unescaped_str;
  for (i = 0; i < len; i++)
    {
      if (str[i] == '\\' &&
	  str[i+1] == 'x' &&
	  len - i >= 4)
	{
	  c =
	    (g_ascii_xdigit_value (str[i+2]) << 4) |
	    g_ascii_xdigit_value (str[i+3]);
	  *p++ = c;
	  i += 3;
	}
      else
	*p++ = str[i];
    }
  *p++ = 0;

  if (out_len)
    *out_len = p - unescaped_str;
  *free_return = TRUE;
  return unescaped_str;
}

static void
378
escape_xattr (GFileInfo  *info,
379 380
	      const char *gio_attr, /* gio attribute name */
	      const char *value, /* Is zero terminated */
381
	      size_t      len /* not including zero termination */)
382 383 384 385 386 387 388 389 390 391 392 393 394 395
{
  char *escaped_val;
  gboolean free_escaped_val;
  
  escaped_val = hex_escape_string (value, &free_escaped_val);
  
  g_file_info_set_attribute_string (info, gio_attr, escaped_val);
  
  if (free_escaped_val)
    g_free (escaped_val);
}

static void
get_one_xattr (const char *path,
396
	       GFileInfo  *info,
397 398
	       const char *gio_attr,
	       const char *xattr,
399
	       gboolean    follow_symlinks)
400 401 402 403 404
{
  char value[64];
  char *value_p;
  ssize_t len;

405
  len = g_getxattr (path, xattr, value, sizeof (value)-1, follow_symlinks);
406 407 408 409 410 411

  value_p = NULL;
  if (len >= 0)
    value_p = value;
  else if (len == -1 && errno == ERANGE)
    {
412
      len = g_getxattr (path, xattr, NULL, 0, follow_symlinks);
413 414 415 416 417 418

      if (len < 0)
	return;

      value_p = g_malloc (len+1);

419
      len = g_getxattr (path, xattr, value_p, len, follow_symlinks);
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

      if (len < 0)
	{
	  g_free (value_p);
	  return;
	}
    }
  else
    return;
  
  /* Null terminate */
  value_p[len] = 0;

  escape_xattr (info, gio_attr, value_p, len);
  
  if (value_p != value)
    g_free (value_p);
}

#endif /* defined HAVE_XATTR */

static void
442 443 444
get_xattrs (const char            *path,
	    gboolean               user,
	    GFileInfo             *info,
445
	    GFileAttributeMatcher *matcher,
446
	    gboolean               follow_symlinks)
447 448 449 450 451 452 453 454 455 456 457 458
{
#ifdef HAVE_XATTR
  gboolean all;
  gsize list_size;
  ssize_t list_res_size;
  size_t len;
  char *list;
  const char *attr, *attr2;

  if (user)
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
  else
459
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
460 461 462

  if (all)
    {
463
      list_res_size = g_listxattr (path, NULL, 0, follow_symlinks);
464 465 466 467 468 469 470 471 472 473

      if (list_res_size == -1 ||
	  list_res_size == 0)
	return;

      list_size = list_res_size;
      list = g_malloc (list_size);

    retry:
      
474
      list_res_size = g_listxattr (path, list, list_size, follow_symlinks);
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
      
      if (list_res_size == -1 && errno == ERANGE)
	{
	  list_size = list_size * 2;
	  list = g_realloc (list, list_size);
	  goto retry;
	}

      if (list_res_size == -1)
	return;

      attr = list;
      while (list_res_size > 0)
	{
	  if ((user && g_str_has_prefix (attr, "user.")) ||
	      (!user && !g_str_has_prefix (attr, "user.")))
	    {
	      char *escaped_attr, *gio_attr;
	      gboolean free_escaped_attr;
	      
	      if (user)
		{
		  escaped_attr = hex_escape_string (attr + 5, &free_escaped_attr);
498
		  gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
499 500 501 502
		}
	      else
		{
		  escaped_attr = hex_escape_string (attr, &free_escaped_attr);
503
		  gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
504 505 506 507 508 509
		}
	      
	      if (free_escaped_attr)
		g_free (escaped_attr);
	      
	      get_one_xattr (path, info, gio_attr, attr, follow_symlinks);
Paolo Borelli's avatar
Paolo Borelli committed
510 511

	      g_free (gio_attr);
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
	    }
	      
	  len = strlen (attr) + 1;
	  attr += len;
	  list_res_size -= len;
	}

      g_free (list);
    }
  else
    {
      while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
	{
	  char *unescaped_attribute, *a;
	  gboolean free_unescaped_attribute;

	  attr2 = strchr (attr, ':');
	  if (attr2)
	    {
531
	      attr2 += 2; /* Skip '::' */
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
	      unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
	      if (user)
		a = g_strconcat ("user.", unescaped_attribute, NULL);
	      else
		a = unescaped_attribute;
	      
	      get_one_xattr (path, info, attr, a, follow_symlinks);

	      if (user)
		g_free (a);
	      
	      if (free_unescaped_attribute)
		g_free (unescaped_attribute);
	    }
	}
    }
#endif /* defined HAVE_XATTR */
}

#ifdef HAVE_XATTR
static void
553 554
get_one_xattr_from_fd (int         fd,
		       GFileInfo  *info,
555 556 557 558 559 560 561
		       const char *gio_attr,
		       const char *xattr)
{
  char value[64];
  char *value_p;
  ssize_t len;

Matthias Clasen's avatar
Matthias Clasen committed
562
  len = g_fgetxattr (fd, xattr, value, sizeof (value) - 1);
563 564 565 566 567 568

  value_p = NULL;
  if (len >= 0)
    value_p = value;
  else if (len == -1 && errno == ERANGE)
    {
569
      len = g_fgetxattr (fd, xattr, NULL, 0);
570 571 572 573

      if (len < 0)
	return;

Matthias Clasen's avatar
Matthias Clasen committed
574
      value_p = g_malloc (len + 1);
575

576
      len = g_fgetxattr (fd, xattr, value_p, len);
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597

      if (len < 0)
	{
	  g_free (value_p);
	  return;
	}
    }
  else
    return;
  
  /* Null terminate */
  value_p[len] = 0;

  escape_xattr (info, gio_attr, value_p, len);
  
  if (value_p != value)
    g_free (value_p);
}
#endif /* defined HAVE_XATTR */

static void
598 599 600
get_xattrs_from_fd (int                    fd,
		    gboolean               user,
		    GFileInfo             *info,
601 602 603 604 605 606 607 608 609 610 611 612 613
		    GFileAttributeMatcher *matcher)
{
#ifdef HAVE_XATTR
  gboolean all;
  gsize list_size;
  ssize_t list_res_size;
  size_t len;
  char *list;
  const char *attr, *attr2;

  if (user)
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
  else
614
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
615 616 617

  if (all)
    {
618
      list_res_size = g_flistxattr (fd, NULL, 0);
619 620 621 622 623 624 625 626 627 628

      if (list_res_size == -1 ||
	  list_res_size == 0)
	return;

      list_size = list_res_size;
      list = g_malloc (list_size);

    retry:
      
629
      list_res_size = g_flistxattr (fd, list, list_size);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
      
      if (list_res_size == -1 && errno == ERANGE)
	{
	  list_size = list_size * 2;
	  list = g_realloc (list, list_size);
	  goto retry;
	}

      if (list_res_size == -1)
	return;

      attr = list;
      while (list_res_size > 0)
	{
	  if ((user && g_str_has_prefix (attr, "user.")) ||
	      (!user && !g_str_has_prefix (attr, "user.")))
	    {
	      char *escaped_attr, *gio_attr;
	      gboolean free_escaped_attr;
	      
	      if (user)
		{
		  escaped_attr = hex_escape_string (attr + 5, &free_escaped_attr);
653
		  gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
654 655 656 657
		}
	      else
		{
		  escaped_attr = hex_escape_string (attr, &free_escaped_attr);
658
		  gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
659 660 661 662 663 664
		}
	      
	      if (free_escaped_attr)
		g_free (escaped_attr);
	      
	      get_one_xattr_from_fd (fd, info, gio_attr, attr);
665
	      g_free (gio_attr);
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
	    }
	  
	  len = strlen (attr) + 1;
	  attr += len;
	  list_res_size -= len;
	}

      g_free (list);
    }
  else
    {
      while ((attr = g_file_attribute_matcher_enumerate_next (matcher)) != NULL)
	{
	  char *unescaped_attribute, *a;
	  gboolean free_unescaped_attribute;

	  attr2 = strchr (attr, ':');
	  if (attr2)
	    {
	      attr2++; /* Skip ':' */
	      unescaped_attribute = hex_unescape_string (attr2, NULL, &free_unescaped_attribute);
	      if (user)
		a = g_strconcat ("user.", unescaped_attribute, NULL);
	      else
		a = unescaped_attribute;
	      
	      get_one_xattr_from_fd (fd, info, attr, a);

	      if (user)
		g_free (a);
	      
	      if (free_unescaped_attribute)
		g_free (unescaped_attribute);
	    }
	}
    }
#endif /* defined HAVE_XATTR */
}

#ifdef HAVE_XATTR
static gboolean
707 708 709 710
set_xattr (char                       *filename,
	   const char                 *escaped_attribute,
	   const GFileAttributeValue  *attr_value,
	   GError                    **error)
711 712 713 714 715 716 717 718 719
{
  char *attribute, *value;
  gboolean free_attribute, free_value;
  int val_len, res, errsv;
  gboolean is_user;
  char *a;

  if (attr_value == NULL)
    {
720 721
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                           _("Attribute value must be non-NULL"));
722 723 724 725 726
      return FALSE;
    }

  if (attr_value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
    {
727 728
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                           _("Invalid attribute type (string expected)"));
729 730 731 732 733
      return FALSE;
    }

  if (!name_is_valid (escaped_attribute))
    {
734 735
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                           _("Invalid extended attribute name"));
736 737 738
      return FALSE;
    }

739
  if (g_str_has_prefix (escaped_attribute, "xattr::"))
740
    {
741
      escaped_attribute += strlen ("xattr::");
742 743 744 745
      is_user = TRUE;
    }
  else
    {
746
      g_warn_if_fail (g_str_has_prefix (escaped_attribute, "xattr-sys::"));
747
      escaped_attribute += strlen ("xattr-sys::");
748 749 750 751 752 753 754 755 756 757 758
      is_user = FALSE;
    }
  
  attribute = hex_unescape_string (escaped_attribute, NULL, &free_attribute);
  value = hex_unescape_string (attr_value->u.string, &val_len, &free_value);

  if (is_user)
    a = g_strconcat ("user.", attribute, NULL);
  else
    a = attribute;
  
759
  res = g_setxattr (filename, a, value, val_len);
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
  errsv = errno;
  
  if (is_user)
    g_free (a);
  
  if (free_attribute)
    g_free (attribute);
  
  if (free_value)
    g_free (value);

  if (res == -1)
    {
      g_set_error (error, G_IO_ERROR,
		   g_io_error_from_errno (errsv),
		   _("Error setting extended attribute '%s': %s"),
776
		   escaped_attribute, g_strerror (errsv));
777 778 779 780 781 782 783 784 785 786
      return FALSE;
    }
  
  return TRUE;
}

#endif


void
787 788 789
_g_local_file_info_get_parent_info (const char            *dir,
				    GFileAttributeMatcher *attribute_matcher,
				    GLocalParentFileInfo  *parent_info)
790
{
791
  GStatBuf statbuf;
792
  int res;
793 794 795

  parent_info->extra_data = NULL;
  parent_info->free_extra_data = NULL;
796 797
  parent_info->writable = FALSE;
  parent_info->is_sticky = FALSE;
798
  parent_info->has_trash_dir = FALSE;
799 800
  parent_info->device = 0;

801 802 803 804
  if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME) ||
      _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE) ||
      _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH) ||
      _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_UNIX_IS_MOUNTPOINT))
805
    {
806 807 808 809 810
      /* FIXME: Windows: The underlying _waccess() call in the C
       * library is mostly pointless as it only looks at the READONLY
       * FAT-style attribute of the file, it doesn't check the ACL at
       * all.
       */
811 812 813 814 815 816 817 818 819 820 821
      parent_info->writable = (g_access (dir, W_OK) == 0);
      
      res = g_stat (dir, &statbuf);

      /*
       * The sticky bit (S_ISVTX) on a directory means that a file in that directory can be
       * renamed or deleted only by the owner of the file, by the owner of the directory, and
       * by a privileged process.
       */
      if (res == 0)
	{
822
#ifdef S_ISVTX
823
	  parent_info->is_sticky = (statbuf.st_mode & S_ISVTX) != 0;
824 825 826
#else
	  parent_info->is_sticky = FALSE;
#endif
827 828
	  parent_info->owner = statbuf.st_uid;
	  parent_info->device = statbuf.st_dev;
829
          /* No need to find trash dir if it's not writable anyway */
830
          if (parent_info->writable &&
831
              _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
832
            parent_info->has_trash_dir = _g_local_file_has_trash_dir (dir, statbuf.st_dev);
833 834 835 836
	}
    }
}

837 838 839 840 841 842 843 844
void
_g_local_file_info_free_parent_info (GLocalParentFileInfo *parent_info)
{
  if (parent_info->extra_data &&
      parent_info->free_extra_data)
    parent_info->free_extra_data (parent_info->extra_data);
}

845 846
static void
get_access_rights (GFileAttributeMatcher *attribute_matcher,
847 848
		   GFileInfo             *info,
		   const gchar           *path,
849
		   GLocalFileStat        *statbuf,
850
		   GLocalParentFileInfo  *parent_info)
851
{
852
  /* FIXME: Windows: The underlyin _waccess() is mostly pointless */
853 854
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ))
855 856
    _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ,
				             g_access (path, R_OK) == 0);
857
  
858 859
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE))
860 861
    _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE,
				             g_access (path, W_OK) == 0);
862
  
863 864
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE))
865 866
    _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE,
				             g_access (path, X_OK) == 0);
867 868 869 870 871 872 873 874 875 876 877


  if (parent_info)
    {
      gboolean writable;

      writable = FALSE;
      if (parent_info->writable)
	{
	  if (parent_info->is_sticky)
	    {
878
#ifndef G_OS_WIN32
879 880 881 882 883
	      uid_t uid = geteuid ();

	      if (uid == statbuf->st_uid ||
		  uid == parent_info->owner ||
		  uid == 0)
884
#endif
885 886 887 888 889 890
		writable = TRUE;
	    }
	  else
	    writable = TRUE;
	}

891
      if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME))
892 893
	_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME,
					         writable);
894
      
895
      if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE))
896 897
	_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE,
					         writable);
898

899
      if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
900 901
        _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH,
                                                 writable && parent_info->has_trash_dir);
902 903 904 905
    }
}

static void
906
set_info_from_stat (GFileInfo             *info, 
907
                    GLocalFileStat        *statbuf,
908 909 910 911 912 913 914 915 916 917
		    GFileAttributeMatcher *attribute_matcher)
{
  GFileType file_type;

  file_type = G_FILE_TYPE_UNKNOWN;

  if (S_ISREG (statbuf->st_mode))
    file_type = G_FILE_TYPE_REGULAR;
  else if (S_ISDIR (statbuf->st_mode))
    file_type = G_FILE_TYPE_DIRECTORY;
918
#ifndef G_OS_WIN32
919 920 921 922 923 924 925 926
  else if (S_ISCHR (statbuf->st_mode) ||
	   S_ISBLK (statbuf->st_mode) ||
	   S_ISFIFO (statbuf->st_mode)
#ifdef S_ISSOCK
	   || S_ISSOCK (statbuf->st_mode)
#endif
	   )
    file_type = G_FILE_TYPE_SPECIAL;
927
#endif
928 929 930 931 932 933 934 935
#ifdef S_ISLNK
  else if (S_ISLNK (statbuf->st_mode))
    file_type = G_FILE_TYPE_SYMBOLIC_LINK;
#endif

  g_file_info_set_file_type (info, file_type);
  g_file_info_set_size (info, statbuf->st_size);

936
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_DEVICE, statbuf->st_dev);
937 938
#ifndef G_OS_WIN32
  /* Pointless setting these on Windows even if they exist in the struct */
939 940 941 942 943
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_INODE, statbuf->st_ino);
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_NLINK, statbuf->st_nlink);
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_UID, statbuf->st_uid);
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_GID, statbuf->st_gid);
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_RDEV, statbuf->st_rdev);
944 945
#endif
  /* FIXME: st_mode is mostly pointless on Windows, too. Set the attribute or not? */
946
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_MODE, statbuf->st_mode);
947
#if defined (HAVE_STRUCT_STAT_ST_BLKSIZE)
948
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCK_SIZE, statbuf->st_blksize);
949
#endif
950
#if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
951 952 953
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCKS, statbuf->st_blocks);
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_ALLOCATED_SIZE,
                                          statbuf->st_blocks * G_GUINT64_CONSTANT (512));
954 955
#endif
  
956
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED, statbuf->st_mtime);
957
#if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
958
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtimensec / 1000);
959
#elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
960
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtim.tv_nsec / 1000);
961 962
#endif
  
963
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS, statbuf->st_atime);
964
#if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
965
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atimensec / 1000);
966
#elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
967
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atim.tv_nsec / 1000);
968 969
#endif
  
970
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED, statbuf->st_ctime);
971
#if defined (HAVE_STRUCT_STAT_ST_CTIMENSEC)
972
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctimensec / 1000);
973
#elif defined (HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC)
974
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctim.tv_nsec / 1000);
975 976
#endif

977 978 979 980 981 982 983 984 985 986 987 988
#if defined (HAVE_STRUCT_STAT_ST_BIRTHTIME) && defined (HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC)
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CREATED, statbuf->st_birthtime);
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CREATED_USEC, statbuf->st_birthtimensec / 1000);
#elif defined (HAVE_STRUCT_STAT_ST_BIRTHTIM) && defined (HAVE_STRUCT_STAT_ST_BIRTHTIM_TV_NSEC)
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CREATED, statbuf->st_birthtim.tv_sec);
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CREATED_USEC, statbuf->st_birthtim.tv_nsec / 1000);
#elif defined (HAVE_STRUCT_STAT_ST_BIRTHTIME)
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CREATED, statbuf->st_birthtime);
#elif defined (HAVE_STRUCT_STAT_ST_BIRTHTIM)
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CREATED, statbuf->st_birthtim);
#endif

989 990
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ETAG_VALUE))
991 992
    {
      char *etag = _g_local_file_info_create_etag (statbuf);
993
      _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ETAG_VALUE, etag);
994 995 996
      g_free (etag);
    }

997 998
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ID_FILE))
999 1000
    {
      char *id = _g_local_file_info_create_file_id (statbuf);
1001
      _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILE, id);
1002 1003 1004
      g_free (id);
    }

1005 1006
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM))
1007 1008
    {
      char *id = _g_local_file_info_create_fs_id (statbuf);
1009
      _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM, id);
1010 1011 1012 1013
      g_free (id);
    }
}

1014 1015
#ifndef G_OS_WIN32

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
static char *
make_valid_utf8 (const char *name)
{
  GString *string;
  const gchar *remainder, *invalid;
  gint remaining_bytes, valid_bytes;
  
  string = NULL;
  remainder = name;
  remaining_bytes = strlen (name);
  
  while (remaining_bytes != 0) 
    {
      if (g_utf8_validate (remainder, remaining_bytes, &invalid)) 
	break;
      valid_bytes = invalid - remainder;
    
      if (string == NULL) 
	string = g_string_sized_new (remaining_bytes);

      g_string_append_len (string, remainder, valid_bytes);
      /* append U+FFFD REPLACEMENT CHARACTER */
      g_string_append (string, "\357\277\275");
      
      remaining_bytes -= valid_bytes + 1;
      remainder = invalid + 1;
    }
  
  if (string == NULL)
    return g_strdup (name);
  
  g_string_append (string, remainder);

1049
  g_warn_if_fail (g_utf8_validate (string->str, -1, NULL));
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  
  return g_string_free (string, FALSE);
}

static char *
convert_pwd_string_to_utf8 (char *pwd_str)
{
  char *utf8_string;
  
  if (!g_utf8_validate (pwd_str, -1, NULL))
    {
      utf8_string = g_locale_to_utf8 (pwd_str, -1, NULL, NULL, NULL);
      if (utf8_string == NULL)
	utf8_string = make_valid_utf8 (pwd_str);
    }
  else 
    utf8_string = g_strdup (pwd_str);
  
  return utf8_string;
}
1070

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
static void
uid_data_free (UidData *data)
{
  g_free (data->user_name);
  g_free (data->real_name);
  g_free (data);
}

/* called with lock held */
static UidData *
lookup_uid_data (uid_t uid)
{
  UidData *data;
  char buffer[4096];
  struct passwd pwbuf;
  struct passwd *pwbufp;
  char *gecos, *comma;
  
  if (uid_cache == NULL)
    uid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)uid_data_free);

  data = g_hash_table_lookup (uid_cache, GINT_TO_POINTER (uid));

  if (data)
    return data;

  data = g_new0 (UidData, 1);

1099
#if defined(HAVE_GETPWUID_R)
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
  getpwuid_r (uid, &pwbuf, buffer, sizeof(buffer), &pwbufp);
#else
  pwbufp = getpwuid (uid);
#endif

  if (pwbufp != NULL)
    {
      if (pwbufp->pw_name != NULL && pwbufp->pw_name[0] != 0)
	data->user_name = convert_pwd_string_to_utf8 (pwbufp->pw_name);

1110
#ifndef __BIONIC__
1111 1112 1113 1114 1115 1116 1117 1118 1119
      gecos = pwbufp->pw_gecos;

      if (gecos)
	{
	  comma = strchr (gecos, ',');
	  if (comma)
	    *comma = 0;
	  data->real_name = convert_pwd_string_to_utf8 (gecos);
	}
1120
#endif
1121 1122 1123 1124 1125 1126 1127 1128
    }

  /* Default fallbacks */
  if (data->real_name == NULL)
    {
      if (data->user_name != NULL)
	data->real_name = g_strdup (data->user_name);
      else
Matthias Clasen's avatar
Matthias Clasen committed
1129
	data->real_name = g_strdup_printf ("user #%d", (int)uid);
1130 1131 1132
    }
  
  if (data->user_name == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
1133
    data->user_name = g_strdup_printf ("%d", (int)uid);
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  
  g_hash_table_replace (uid_cache, GINT_TO_POINTER (uid), data);
  
  return data;
}

static char *
get_username_from_uid (uid_t uid)
{
  char *res;
  UidData *data;
  
  G_LOCK (uid_cache);
  data = lookup_uid_data (uid);
  res = g_strdup (data->user_name);  
  G_UNLOCK (uid_cache);

  return res;
}

static char *
get_realname_from_uid (uid_t uid)
{
  char *res;
  UidData *data;
  
  G_LOCK (uid_cache);
  data = lookup_uid_data (uid);
  res = g_strdup (data->real_name);  
  G_UNLOCK (uid_cache);
  
  return res;
}

/* called with lock held */
static char *
lookup_gid_name (gid_t gid)
{
  char *name;
  char buffer[4096];
  struct group gbuf;
  struct group *gbufp;
  
  if (gid_cache == NULL)
    gid_cache = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify)g_free);

  name = g_hash_table_lookup (gid_cache, GINT_TO_POINTER (gid));

  if (name)
    return name;

1185
#if defined (HAVE_GETGRGID_R)
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
  getgrgid_r (gid, &gbuf, buffer, sizeof(buffer), &gbufp);
#else
  gbufp = getgrgid (gid);
#endif

  if (gbufp != NULL &&
      gbufp->gr_name != NULL &&
      gbufp->gr_name[0] != 0)
    name = convert_pwd_string_to_utf8 (gbufp->gr_name);
  else
    name = g_strdup_printf("%d", (int)gid);
  
  g_hash_table_replace (gid_cache, GINT_TO_POINTER (gid), name);
  
  return name;
}

static char *
get_groupname_from_gid (gid_t gid)
{
  char *res;
  char *name;
  
  G_LOCK (gid_cache);
  name = lookup_gid_name (gid);
  res = g_strdup (name);  
  G_UNLOCK (gid_cache);
  return res;
}
1215

1216
#endif /* !G_OS_WIN32 */
1217 1218

static char *
1219 1220
get_content_type (const char          *basename,
		  const char          *path,
1221
		  GLocalFileStat      *statbuf,
1222 1223 1224 1225
		  gboolean             is_symlink,
		  gboolean             symlink_broken,
		  GFileQueryInfoFlags  flags,
		  gboolean             fast)
1226 1227 1228
{
  if (is_symlink &&
      (symlink_broken || (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)))
Patrick Griffis's avatar
Patrick Griffis committed
1229
    return g_content_type_from_mime_type ("inode/symlink");
1230
  else if (statbuf != NULL && S_ISDIR(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1231
    return g_content_type_from_mime_type ("inode/directory");
1232
#ifndef G_OS_WIN32
1233
  else if (statbuf != NULL && S_ISCHR(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1234
    return g_content_type_from_mime_type ("inode/chardevice");
1235
  else if (statbuf != NULL && S_ISBLK(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1236
    return g_content_type_from_mime_type ("inode/blockdevice");
1237
  else if (statbuf != NULL && S_ISFIFO(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1238
    return g_content_type_from_mime_type ("inode/fifo");
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
  else if (statbuf != NULL && S_ISREG(statbuf->st_mode) && statbuf->st_size == 0)
    {
      /* Don't sniff zero-length files in order to avoid reading files
       * that appear normal but are not (eg: files in /proc and /sys)
       *
       * Note that we need to return text/plain here so that
       * newly-created text files are opened by the text editor.
       * See https://bugzilla.gnome.org/show_bug.cgi?id=755795
       */
      return g_content_type_from_mime_type ("text/plain");
    }
1250
#endif
1251
#ifdef S_ISSOCK
1252
  else if (statbuf != NULL && S_ISSOCK(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1253
    return g_content_type_from_mime_type ("inode/socket");
1254 1255 1256 1257 1258
#endif
  else
    {
      char *content_type;
      gboolean result_uncertain;
1259

1260 1261 1262
      content_type = g_content_type_guess (basename, NULL, 0, &result_uncertain);
      
#ifndef G_OS_WIN32
1263
      if (!fast && result_uncertain && path != NULL)
1264 1265 1266 1267 1268 1269 1270 1271
	{
	  guchar sniff_buffer[4096];
	  gsize sniff_length;
	  int fd;

	  sniff_length = _g_unix_content_type_get_sniff_len ();
	  if (sniff_length > 4096)
	    sniff_length = 4096;
1272 1273

#ifdef O_NOATIME	  
1274
          fd = g_open (path, O_RDONLY | O_NOATIME, 0);
1275 1276
          if (fd < 0 && errno == EPERM)
#endif
1277
	    fd = g_open (path, O_RDONLY, 0);
1278

1279 1280 1281 1282 1283
	  if (fd != -1)
	    {
	      ssize_t res;
	      
	      res = read (fd, sniff_buffer, sniff_length);
Colin Walters's avatar
Colin Walters committed
1284
	      (void) g_close (fd, NULL);
1285
	      if (res >= 0)
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
		{
		  g_free (content_type);
		  content_type = g_content_type_guess (basename, sniff_buffer, res, NULL);
		}
	    }
	}
#endif
      
      return content_type;
    }
  
}

1299
/* @stat_buf is the pre-calculated result of stat(path), or %NULL if that failed. */
1300
static void
1301 1302
get_thumbnail_attributes (const char     *path,
                          GFileInfo      *info,
1303
                          const GLocalFileStat *stat_buf)
1304
{
1305
  GChecksum *checksum;
1306 1307 1308 1309 1310 1311
  char *uri;
  char *filename;
  char *basename;

  uri = g_filename_to_uri (path, NULL, NULL);

1312
  checksum = g_checksum_new (G_CHECKSUM_MD5);
1313
  g_checksum_update (checksum, (const guchar *) uri, strlen (uri));
1314

1315 1316 1317
  basename = g_strconcat (g_checksum_get_string (checksum), ".png", NULL);
  g_checksum_free (checksum);

1318
  filename = g_build_filename (g_get_user_cache_dir (),
1319
                               "thumbnails", "large", basename,
1320
                               NULL);
1321 1322

  if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1323 1324 1325 1326 1327
    {
      _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
      _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_IS_VALID,
                                                thumbnail_verify (filename, uri, stat_buf));
    }
1328 1329 1330
  else
    {
      g_free (filename);
1331
      filename = g_build_filename (g_get_user_cache_dir (),
1332
                                   "thumbnails", "normal", basename,
1333
                                   NULL);
1334 1335

      if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1336 1337 1338 1339 1340
        {
          _g_file_info_set_attribute_byte_string_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_PATH, filename);
          _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_IS_VALID,
                                                    thumbnail_verify (filename, uri, stat_buf));
        }
1341 1342
      else
        {
1343
          g_free (filename);
1344 1345 1346 1347 1348 1349 1350
          filename = g_build_filename (g_get_user_cache_dir (),
                                       "thumbnails", "fail",
                                       "gnome-thumbnail-factory",
                                       basename,
                                       NULL);

          if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1351 1352 1353 1354 1355
            {
              _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAILING_FAILED, TRUE);
              _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_THUMBNAIL_IS_VALID,
                                                        thumbnail_verify (filename, uri, stat_buf));
            }
1356
        }
1357 1358 1359
    }
  g_free (basename);
  g_free (filename);
1360
  g_free (uri);
1361 1362
}

1363
#ifdef G_OS_WIN32
1364
static void
Matthias Clasen's avatar
Matthias Clasen committed
1365 1366 1367 1368
win32_get_file_user_info (const gchar  *filename,
			  gchar       **group_name, 
			  gchar       **user_name, 
			  gchar       **real_name)
1369 1370
{
  PSECURITY_DESCRIPTOR psd = NULL;
1371
  DWORD sd_size = 0; /* first call calculates the size required */
1372 1373 1374 1375 1376 1377 1378 1379 1380
  
  wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
  if ((GetFileSecurityW (wfilename, 
                        GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
			NULL,
			sd_size,
			&sd_size) || (ERROR_INSUFFICIENT_BUFFER == GetLastError())) &&
     (psd = g_try_malloc (sd_size)) != NULL &&
     GetFileSecurityW (wfilename, 
1381 1382 1383 1384
                       GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
		       psd,
		       sd_size,
		       &sd_size))
1385
    {
1386
      PSID psid = 0;
1387 1388
      BOOL defaulted;
      SID_NAME_USE name_use = 0; /* don't care? */
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
      wchar_t *name = NULL;
      wchar_t *domain = NULL;
      DWORD name_len = 0;
      DWORD domain_len = 0;
      /* get the user name */
      do {
        if (!user_name)
	  break;
	if (!GetSecurityDescriptorOwner (psd, &psid, &defaulted))
	  break;
	if (!LookupAccountSidW (NULL, /* local machine */
                                psid, 
			        name, &name_len,
			        domain, &domain_len, /* no domain info yet */
			        &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
	  break;
Matthias Clasen's avatar
Matthias Clasen committed
1405 1406
	name = g_try_malloc (name_len * sizeof (wchar_t));
	domain = g_try_malloc (domain_len * sizeof (wchar_t));
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	if (name && domain &&
            LookupAccountSidW (NULL, /* local machine */
                               psid, 
			       name, &name_len,
			       domain, &domain_len, /* no domain info yet */
			       &name_use))
	  {
	    *user_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
	  }
	g_free (name);
	g_free (domain);
      } while (FALSE);

      /* get the group name */
      do {
        if (!group_name)
	  break;
	if (!GetSecurityDescriptorGroup (psd, &psid, &defaulted))
	  break;
	if (!LookupAccountSidW (NULL, /* local machine */
                                psid, 
			        name, &name_len,
			        domain, &domain_len, /* no domain info yet */
			        &name_use)  && (ERROR_INSUFFICIENT_BUFFER != GetLastError()))
	  break;
Matthias Clasen's avatar
Matthias Clasen committed
1432 1433
	name = g_try_malloc (name_len * sizeof (wchar_t));
	domain = g_try_malloc (domain_len * sizeof (wchar_t));
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
	if (name && domain &&
            LookupAccountSidW (NULL, /* local machine */
                               psid, 
			       name, &name_len,
			       domain, &domain_len, /* no domain info yet */
			       &name_use))
	  {
	    *group_name = g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
	  }
	g_free (name);
	g_free (domain);
      } while (FALSE);

      /* TODO: get real name */

      g_free (psd);
1450 1451 1452
    }
  g_free (wfilename);
}
1453
#endif /* G_OS_WIN32 */
1454

1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
#ifndef G_OS_WIN32
/* support for '.hidden' files */
G_LOCK_DEFINE_STATIC (hidden_cache);
static GHashTable *hidden_cache;

static gboolean
remove_from_hidden_cache (gpointer user_data)
{
  G_LOCK (hidden_cache);
  g_hash_table_remove (hidden_cache, user_data);
  G_UNLOCK (hidden_cache);

  return FALSE;
}

static GHashTable *
read_hidden_file (const gchar *dirname)
{
1473
  gchar *contents = NULL;
1474 1475 1476
  gchar *filename;

  filename = g_build_path ("/", dirname, ".hidden", NULL);
1477
  (void) g_file_get_contents (filename, &contents, NULL, NULL);
1478 1479
  g_free (filename);

1480
  if (contents != NULL)
1481 1482
    {
      GHashTable *table;
1483 1484
      gchar **lines;
      gint i;
1485 1486 1487

      table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);

1488 1489
      lines = g_strsplit (contents, "\n", 0);
      g_free (contents);
1490

1491 1492 1493
      for (i = 0; lines[i]; i++)
        /* hash table takes the individual strings... */
        g_hash_table_add (table, lines[i]);
1494

1495 1496
      /* ... so we only free the container. */
      g_free (lines);
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547

      return table;
    }
  else
    return NULL;
}

static void
maybe_unref_hash_table (gpointer data)
{
  if (data != NULL)
    g_hash_table_unref (data);
}

static gboolean
file_is_hidden (const gchar *path,
                const gchar *basename)
{
  gboolean result;
  gchar *dirname;
  gpointer table;

  dirname = g_path_get_dirname (path);

  G_LOCK (hidden_cache);

  if G_UNLIKELY (hidden_cache == NULL)
    hidden_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
                                          g_free, maybe_unref_hash_table);

  if (!g_hash_table_lookup_extended (hidden_cache, dirname,
                                     NULL, &table))
    {
      gchar *mydirname;
      GSource *remove_from_cache_source;

      g_hash_table_insert (hidden_cache,
                           mydirname = g_strdup (dirname),
                           table = read_hidden_file (dirname));

      remove_from_cache_source = g_timeout_source_new_seconds (5);
      g_source_set_priority (remove_from_cache_source, G_PRIORITY_DEFAULT);
      g_source_set_callback (remove_from_cache_source, 
                             remove_from_hidden_cache, 
                             mydirname, 
                             NULL);
      g_source_attach (remove_from_cache_source, 
                       GLIB_PRIVATE_CALL (g_get_worker_context) ());
      g_source_unref (remove_from_cache_source);
    }

1548
  result = table != NULL && g_hash_table_contains (table, basename);
1549 1550 1551 1552 1553 1554 1555 1556 1557

  G_UNLOCK (hidden_cache);

  g_free (dirname);

  return result;
}
#endif /* !G_OS_WIN32 */

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
void
_g_local_file_info_get_nostat (GFileInfo              *info,
                               const char             *basename,
			       const char             *path,
                               GFileAttributeMatcher  *attribute_matcher)
{
  g_file_info_set_name (info, basename);

  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_STANDARD_DISPLAY_NAME))
    {
      char *display_name = g_filename_display_basename (path);
     
      /* look for U+FFFD REPLACEMENT CHARACTER */ 
      if (strstr (display_name, "\357\277\275") != NULL)
	{
	  char *p = display_name;
	  display_name = g_strconcat (display_name, _(" (invalid encoding)"), NULL);
	  g_free (p);
	}
      g_file_info_set_display_name (info, display_name);
      g_free (display_name);
    }
  
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_STANDARD_EDIT_NAME))
    {
      char *edit_name = g_filename_display_basename (path);
      g_file_info_set_edit_name (info, edit_name);
      g_free (edit_name);
    }

  
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME))
    {
      char *copy_name = g_filename_to_utf8 (basename, -1, NULL, NULL, NULL);
      if (copy_name)
	_g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_COPY_NAME, copy_name);
      g_free (copy_name);
    }
}

1601 1602
static const char *
get_icon_name (const char *path,
1603
               const char *content_type,
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
               gboolean    use_symbolic,
               gboolean   *with_fallbacks_out)
{
  const char *name = NULL;
  gboolean with_fallbacks = TRUE;

  if (strcmp (path, g_get_home_dir ()) == 0)
    {
      name = use_symbolic ? "user-home-symbolic" : "user-home";
      with_fallbacks = FALSE;
    }
  else if (strcmp (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
    {
      name = use_symbolic ? "user-desktop-symbolic" : "user-desktop";
      with_fallbacks = FALSE;
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOCUMENTS)) == 0)
    {
      name = use_symbolic ? "folder-documents-symbolic" : "folder-documents";
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DOWNLOAD)) == 0)
    {
      name = use_symbolic ? "folder-download-symbolic" : "folder-download";
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_MUSIC)) == 0)
    {
      name = use_symbolic ? "folder-music-symbolic" : "folder-music";
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PICTURES)) == 0)
    {
      name = use_symbolic ? "folder-pictures-symbolic" : "folder-pictures";
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_PUBLIC_SHARE)) == 0)
    {
      name = use_symbolic ? "folder-publicshare-symbolic" : "folder-publicshare";
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_TEMPLATES)) == 0)
    {
      name = use_symbolic ? "folder-templates-symbolic" : "folder-templates";
    }
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_VIDEOS)) == 0)
    {
      name = use_symbolic ? "folder-videos-symbolic" : "folder-videos";
    }
1648 1649 1650 1651
  else if (g_strcmp0 (content_type, "inode/directory") == 0)
    {
      name = use_symbolic ? "folder-symbolic" : "folder";
    }
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
  else
    {
      name = NULL;
    }

  if (with_fallbacks_out != NULL)
    *with_fallbacks_out = with_fallbacks;

  return name;
}

1663 1664 1665 1666 1667 1668 1669 1670 1671
static GIcon *
get_icon (const char *path,
          const char *content_type,
          gboolean    use_symbolic)
{
  GIcon *icon = NULL;
  const char *icon_name;
  gboolean with_fallbacks;

1672
  icon_name = get_icon_name (path, content_type, use_symbolic, &with_fallbacks);
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
  if (icon_name != NULL)
    {
      if (with_fallbacks)
        icon = g_themed_icon_new_with_default_fallbacks (icon_name);
      else
        icon = g_themed_icon_new (icon_name);
    }
  else
    {
      if (use_symbolic)
        icon = g_content_type_get_symbolic_icon (content_type);
      else
        icon = g_content_type_get_icon (content_type);
    }

  return icon;
}

1691
GFileInfo *
1692 1693 1694 1695 1696 1697
_g_local_file_info_get (const char             *basename,
			const char             *path,
			GFileAttributeMatcher  *attribute_matcher,
			GFileQueryInfoFlags     flags,
			GLocalParentFileInfo   *parent_info,
			GError                **error)
1698 1699
{
  GFileInfo *info;
1700 1701
  GLocalFileStat statbuf;
#ifdef S_ISLNK
1702
  struct stat statbuf2;
1703
#endif
1704
  int res;
1705
  gboolean stat_ok;
1706
  gboolean is_symlink, symlink_broken;
1707 1708 1709
#ifdef G_OS_WIN32
  DWORD dos_attributes;
#endif
1710 1711 1712
  char *symlink_target;
  GVfs *vfs;
  GVfsClass *class;
1713
  guint64 device;
1714 1715 1716 1717 1718 1719

  info = g_file_info_new ();

  /* Make sure we don't set any unwanted attributes */
  g_file_info_set_attribute_mask (info, attribute_matcher);
  
1720
  _g_local_file_info_get_nostat (info, basename, path, attribute_matcher);
1721 1722

  if (attribute_matcher == NULL)
1723 1724 1725 1726
    {
      g_file_info_unset_attribute_mask (info);
      return info;
    }
1727

1728
#ifndef G_OS_WIN32
1729
  res = g_lstat (path, &statbuf);
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
#else
  {
    wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, error);
    int len;

    if (wpath == NULL)
      {
        g_object_unref (info);
        return NULL;
      }

    len = wcslen (wpath);
    while (len > 0 && G_IS_DIR_SEPARATOR (wpath[len-1]))
      len--;
    if (len > 0 &&
        (!g_path_is_absolute (path) || len > g_path_skip_root (path) - path))
      wpath[len] = '\0';

    res = _wstati64 (wpath, &statbuf);
    dos_attributes = GetFileAttributesW (wpath);

    g_free (wpath);
  }
#endif

1755 1756
  if (res == -1)
    {
1757
      int errsv = errno;
1758 1759 1760 1761 1762 1763 1764 1765

      /* Don't bail out if we get Permission denied (SELinux?) */
      if (errsv != EACCES)
        {
          char *display_name = g_filename_display_name (path);
          g_object_unref (info);
          g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
1766
		       _("Error when getting information for file '%s': %s"),
1767 1768 1769 1770
		       display_name, g_strerror (errsv));
          g_free (display_name);
          return NULL;
        }
1771
    }
1772

1773 1774 1775 1776 1777 1778 1779
  /* Even if stat() fails, try to get as much as other attributes possible */
  stat_ok = res != -1;

  if (stat_ok)
    device = statbuf.st_dev;
  else
    device = 0;
1780

1781
#ifdef S_ISLNK
1782
  is_symlink = stat_ok && S_ISLNK (statbuf.st_mode);
1783 1784 1785 1786
#else
  is_symlink = FALSE;
#endif
  symlink_broken = FALSE;
1787
#ifdef S_ISLNK