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

3 4 5 6 7 8 9
/* 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
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14 15 16 17
 *
 * 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 <glib/gstdioprivate.h>
57
#include <gfileattribute-priv.h>
58
#include <gfileinfo-priv.h>
59
#include <gvfs.h>
60

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

66 67
#include "glib-private.h"

68 69
#include "thumbnail-verify.h"

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
#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

93 94 95 96
#include "glocalfileinfo.h"
#include "gioerror.h"
#include "gthemedicon.h"
#include "gcontenttypeprivate.h"
97
#include "glibintl.h"
98

99

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

106
#ifndef G_OS_WIN32
107

108 109 110 111
typedef struct {
  char *user_name;
  char *real_name;
} UidData;
112

113 114 115 116 117 118
G_LOCK_DEFINE_STATIC (uid_cache);
static GHashTable *uid_cache = NULL;

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

119 120
#endif  /* !G_OS_WIN32 */

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

  sec = statbuf->st_mtime;
127
#if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
128
  usec = statbuf->st_mtimensec / 1000;
129
#elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
130
  usec = statbuf->st_mtim.tv_nsec / 1000;
131
#else
132
  usec = 0;
133 134
#endif

135
  return g_strdup_printf ("%lu:%lu", sec, usec);
136 137 138
}

static char *
139
_g_local_file_info_create_file_id (GLocalFileStat *statbuf)
140
{
141 142 143 144 145 146
  guint64 ino;
#ifdef G_OS_WIN32
  ino = statbuf->file_index;
#else
  ino = statbuf->st_ino;
#endif
147 148
  return g_strdup_printf ("l%" G_GUINT64_FORMAT ":%" G_GUINT64_FORMAT,
			  (guint64) statbuf->st_dev, 
149
			  ino);
150 151 152
}

static char *
153
_g_local_file_info_create_fs_id (GLocalFileStat *statbuf)
154 155 156 157 158
{
  return g_strdup_printf ("l%" G_GUINT64_FORMAT,
			  (guint64) statbuf->st_dev);
}

159
#if defined (S_ISLNK) || defined (G_OS_WIN32)
160

161 162 163
static gchar *
read_link (const gchar *full_name)
{
164
#if defined (HAVE_READLINK) || defined (G_OS_WIN32)
165 166 167 168 169 170 171 172 173 174
  gchar *buffer;
  guint size;
  
  size = 256;
  buffer = g_malloc (size);
  
  while (1)
    {
      int read_size;
      
175
#ifndef G_OS_WIN32
176
      read_size = readlink (full_name, buffer, size);
177 178 179
#else
      read_size = GLIB_PRIVATE_CALL (g_win32_readlink_utf8) (full_name, buffer, size);
#endif
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
      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
}

198
#endif  /* S_ISLNK || G_OS_WIN32 */
199

200
#ifdef HAVE_SELINUX
201 202
/* Get the SELinux security context */
static void
203 204
get_selinux_context (const char            *path,
		     GFileInfo             *info,
205
		     GFileAttributeMatcher *attribute_matcher,
206
		     gboolean               follow_symlinks)
207 208 209
{
  char *context;

210
  if (!_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT))
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    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)
	{
228
	  _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_SELINUX_CONTEXT, context);
229
	  freecon (context);
230 231 232
	}
    }
}
233
#endif
234 235 236

#ifdef HAVE_XATTR

237 238 239 240 241 242 243 244 245 246 247 248 249
/* 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

250
static gssize
251 252 253 254 255 256 257 258 259 260 261 262 263
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
}

264
static gssize
265 266 267 268 269 270 271 272 273 274 275 276 277
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
}

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
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 *
296 297
hex_escape_string (const char *str, 
                   gboolean   *free_return)
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 325 326 327 328 329 330 331 332 333 334 335
{
  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];
	}
    }
336
  *p = 0;
337 338 339 340 341 342

  *free_return = TRUE;
  return escaped_str;
}

static char *
343 344 345
hex_unescape_string (const char *str, 
                     int        *out_len, 
                     gboolean   *free_return)
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 378 379 380 381 382 383 384 385 386 387 388
{
  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
389
escape_xattr (GFileInfo  *info,
390 391
	      const char *gio_attr, /* gio attribute name */
	      const char *value, /* Is zero terminated */
392
	      size_t      len /* not including zero termination */)
393 394 395 396 397 398 399 400 401 402 403 404 405 406
{
  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,
407
	       GFileInfo  *info,
408 409
	       const char *gio_attr,
	       const char *xattr,
410
	       gboolean    follow_symlinks)
411 412 413
{
  char value[64];
  char *value_p;
414
  gssize len;
415
  int errsv;
416

417
  len = g_getxattr (path, xattr, value, sizeof (value)-1, follow_symlinks);
418
  errsv = errno;
419 420 421 422

  value_p = NULL;
  if (len >= 0)
    value_p = value;
423
  else if (len == -1 && errsv == ERANGE)
424
    {
425
      len = g_getxattr (path, xattr, NULL, 0, follow_symlinks);
426 427 428 429 430 431

      if (len < 0)
	return;

      value_p = g_malloc (len+1);

432
      len = g_getxattr (path, xattr, value_p, len, follow_symlinks);
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454

      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
455 456 457
get_xattrs (const char            *path,
	    gboolean               user,
	    GFileInfo             *info,
458
	    GFileAttributeMatcher *matcher,
459
	    gboolean               follow_symlinks)
460 461 462 463
{
#ifdef HAVE_XATTR
  gboolean all;
  gsize list_size;
464
  gssize list_res_size;
465 466 467 468 469 470 471
  size_t len;
  char *list;
  const char *attr, *attr2;

  if (user)
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
  else
472
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
473 474 475

  if (all)
    {
476 477
      int errsv;

478
      list_res_size = g_listxattr (path, NULL, 0, follow_symlinks);
479 480 481 482 483 484 485 486 487 488

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

      list_size = list_res_size;
      list = g_malloc (list_size);

    retry:
      
489
      list_res_size = g_listxattr (path, list, list_size, follow_symlinks);
490
      errsv = errno;
491
      
492
      if (list_res_size == -1 && errsv == ERANGE)
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
	{
	  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);
514
		  gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
515 516 517 518
		}
	      else
		{
		  escaped_attr = hex_escape_string (attr, &free_escaped_attr);
519
		  gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
520 521 522 523 524 525
		}
	      
	      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
526 527

	      g_free (gio_attr);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
	    }
	      
	  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)
	    {
547
	      attr2 += 2; /* Skip '::' */
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
	      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
569 570
get_one_xattr_from_fd (int         fd,
		       GFileInfo  *info,
571 572 573 574 575
		       const char *gio_attr,
		       const char *xattr)
{
  char value[64];
  char *value_p;
576
  gssize len;
577
  int errsv;
578

Matthias Clasen's avatar
Matthias Clasen committed
579
  len = g_fgetxattr (fd, xattr, value, sizeof (value) - 1);
580
  errsv = errno;
581 582 583 584

  value_p = NULL;
  if (len >= 0)
    value_p = value;
585
  else if (len == -1 && errsv == ERANGE)
586
    {
587
      len = g_fgetxattr (fd, xattr, NULL, 0);
588 589 590 591

      if (len < 0)
	return;

Matthias Clasen's avatar
Matthias Clasen committed
592
      value_p = g_malloc (len + 1);
593

594
      len = g_fgetxattr (fd, xattr, value_p, len);
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615

      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
616 617 618
get_xattrs_from_fd (int                    fd,
		    gboolean               user,
		    GFileInfo             *info,
619 620 621 622 623
		    GFileAttributeMatcher *matcher)
{
#ifdef HAVE_XATTR
  gboolean all;
  gsize list_size;
624
  gssize list_res_size;
625 626 627 628 629 630 631
  size_t len;
  char *list;
  const char *attr, *attr2;

  if (user)
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr");
  else
632
    all = g_file_attribute_matcher_enumerate_namespace (matcher, "xattr-sys");
633 634 635

  if (all)
    {
636 637
      int errsv;

638
      list_res_size = g_flistxattr (fd, NULL, 0);
639 640 641 642 643 644 645 646 647 648

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

      list_size = list_res_size;
      list = g_malloc (list_size);

    retry:
      
649
      list_res_size = g_flistxattr (fd, list, list_size);
650
      errsv = errno;
651
      
652
      if (list_res_size == -1 && errsv == ERANGE)
653 654 655 656 657 658 659
	{
	  list_size = list_size * 2;
	  list = g_realloc (list, list_size);
	  goto retry;
	}

      if (list_res_size == -1)
660 661 662 663
        {
          g_free (list);
          return;
        }
664 665 666 667 668 669 670 671 672 673 674 675 676

      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);
677
		  gio_attr = g_strconcat ("xattr::", escaped_attr, NULL);
678 679 680 681
		}
	      else
		{
		  escaped_attr = hex_escape_string (attr, &free_escaped_attr);
682
		  gio_attr = g_strconcat ("xattr-sys::", escaped_attr, NULL);
683 684 685 686 687 688
		}
	      
	      if (free_escaped_attr)
		g_free (escaped_attr);
	      
	      get_one_xattr_from_fd (fd, info, gio_attr, attr);
689
	      g_free (gio_attr);
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
	    }
	  
	  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
731 732 733 734
set_xattr (char                       *filename,
	   const char                 *escaped_attribute,
	   const GFileAttributeValue  *attr_value,
	   GError                    **error)
735 736 737 738 739 740 741 742 743
{
  char *attribute, *value;
  gboolean free_attribute, free_value;
  int val_len, res, errsv;
  gboolean is_user;
  char *a;

  if (attr_value == NULL)
    {
744 745
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                           _("Attribute value must be non-NULL"));
746 747 748 749 750
      return FALSE;
    }

  if (attr_value->type != G_FILE_ATTRIBUTE_TYPE_STRING)
    {
751 752
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                           _("Invalid attribute type (string expected)"));
753 754 755 756 757
      return FALSE;
    }

  if (!name_is_valid (escaped_attribute))
    {
758 759
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
                           _("Invalid extended attribute name"));
760 761 762
      return FALSE;
    }

763
  if (g_str_has_prefix (escaped_attribute, "xattr::"))
764
    {
765
      escaped_attribute += strlen ("xattr::");
766 767 768 769
      is_user = TRUE;
    }
  else
    {
770
      g_warn_if_fail (g_str_has_prefix (escaped_attribute, "xattr-sys::"));
771
      escaped_attribute += strlen ("xattr-sys::");
772 773 774 775 776 777 778 779 780 781 782
      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;
  
783
  res = g_setxattr (filename, a, value, val_len);
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
  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),
799
		   _("Error setting extended attribute “%s”: %s"),
800
		   escaped_attribute, g_strerror (errsv));
801 802 803 804 805 806 807 808 809 810
      return FALSE;
    }
  
  return TRUE;
}

#endif


void
811 812 813
_g_local_file_info_get_parent_info (const char            *dir,
				    GFileAttributeMatcher *attribute_matcher,
				    GLocalParentFileInfo  *parent_info)
814
{
815
  GStatBuf statbuf;
816
  int res;
817 818 819

  parent_info->extra_data = NULL;
  parent_info->free_extra_data = NULL;
820 821
  parent_info->writable = FALSE;
  parent_info->is_sticky = FALSE;
822
  parent_info->has_trash_dir = FALSE;
823
  parent_info->device = 0;
824
  parent_info->inode = 0;
825

826 827 828 829
  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))
830
    {
831 832 833 834 835
      /* 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.
       */
836 837 838 839 840 841 842 843 844 845 846
      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)
	{
847
#ifdef S_ISVTX
848
	  parent_info->is_sticky = (statbuf.st_mode & S_ISVTX) != 0;
849 850 851
#else
	  parent_info->is_sticky = FALSE;
#endif
852 853
	  parent_info->owner = statbuf.st_uid;
	  parent_info->device = statbuf.st_dev;
854
	  parent_info->inode = statbuf.st_ino;
855
          /* No need to find trash dir if it's not writable anyway */
856
          if (parent_info->writable &&
857
              _g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
858
            parent_info->has_trash_dir = _g_local_file_has_trash_dir (dir, statbuf.st_dev);
859 860 861 862
	}
    }
}

863 864 865 866 867 868 869 870
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);
}

871 872
static void
get_access_rights (GFileAttributeMatcher *attribute_matcher,
873 874
		   GFileInfo             *info,
		   const gchar           *path,
875
		   GLocalFileStat        *statbuf,
876
		   GLocalParentFileInfo  *parent_info)
877
{
878
  /* FIXME: Windows: The underlyin _waccess() is mostly pointless */
879 880
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ))
881 882
    _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ,
				             g_access (path, R_OK) == 0);
883
  
884 885
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE))
886 887
    _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE,
				             g_access (path, W_OK) == 0);
888
  
889 890
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE))
891 892
    _g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE,
				             g_access (path, X_OK) == 0);
893 894 895 896 897 898 899 900 901


  if (parent_info)
    {
      gboolean writable;

      writable = FALSE;
      if (parent_info->writable)
	{
902 903 904
#ifdef G_OS_WIN32
	  writable = TRUE;
#else
905 906 907 908 909 910 911 912 913 914 915
	  if (parent_info->is_sticky)
	    {
	      uid_t uid = geteuid ();

	      if (uid == statbuf->st_uid ||
		  uid == parent_info->owner ||
		  uid == 0)
		writable = TRUE;
	    }
	  else
	    writable = TRUE;
916
#endif
917 918
	}

919
      if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME))
920 921
	_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME,
					         writable);
922
      
923
      if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE))
924 925
	_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE,
					         writable);
926

927
      /* Trashing is supported only if the parent device is the same */
928
      if (_g_file_attribute_matcher_matches_id (attribute_matcher, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH))
929 930 931 932 933
        _g_file_info_set_attribute_boolean_by_id (info,
                                                  G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH,
                                                  writable &&
                                                  parent_info->has_trash_dir &&
                                                  parent_info->device == statbuf->st_dev);
934 935 936 937
    }
}

static void
938
set_info_from_stat (GFileInfo             *info, 
939
                    GLocalFileStat        *statbuf,
940 941 942 943 944 945 946 947 948 949
		    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;
950
#ifndef G_OS_WIN32
951 952 953 954 955 956 957 958
  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;
959
#endif
960 961 962
#ifdef S_ISLNK
  else if (S_ISLNK (statbuf->st_mode))
    file_type = G_FILE_TYPE_SYMBOLIC_LINK;
963 964 965
#elif defined (G_OS_WIN32)
  if (statbuf->reparse_tag == IO_REPARSE_TAG_SYMLINK)
    file_type = G_FILE_TYPE_SYMBOLIC_LINK;
966 967 968 969 970
#endif

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

971
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_DEVICE, statbuf->st_dev);
972 973
#ifndef G_OS_WIN32
  /* Pointless setting these on Windows even if they exist in the struct */
974 975 976 977 978
  _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);
979 980
#endif
  /* FIXME: st_mode is mostly pointless on Windows, too. Set the attribute or not? */
981
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_MODE, statbuf->st_mode);
982
#if defined (HAVE_STRUCT_STAT_ST_BLKSIZE)
983
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_UNIX_BLOCK_SIZE, statbuf->st_blksize);
984
#endif
985
#if defined (HAVE_STRUCT_STAT_ST_BLOCKS)
986 987
  _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,
988 989 990 991 992
                                           statbuf->st_blocks * G_GUINT64_CONSTANT (512));
#elif defined (G_OS_WIN32)
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_ALLOCATED_SIZE,
                                           statbuf->allocated_size);

993 994
#endif
  
995
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED, statbuf->st_mtime);
996
#if defined (HAVE_STRUCT_STAT_ST_MTIMENSEC)
997
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtimensec / 1000);
998
#elif defined (HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
999
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_MODIFIED_USEC, statbuf->st_mtim.tv_nsec / 1000);
1000 1001
#endif
  
1002
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS, statbuf->st_atime);
1003
#if defined (HAVE_STRUCT_STAT_ST_ATIMENSEC)
1004
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atimensec / 1000);
1005
#elif defined (HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC)
1006
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_ACCESS_USEC, statbuf->st_atim.tv_nsec / 1000);
1007 1008
#endif
  
1009
  _g_file_info_set_attribute_uint64_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED, statbuf->st_ctime);
1010
#if defined (HAVE_STRUCT_STAT_ST_CTIMENSEC)
1011
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctimensec / 1000);
1012
#elif defined (HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC)
1013
  _g_file_info_set_attribute_uint32_by_id (info, G_FILE_ATTRIBUTE_ID_TIME_CHANGED_USEC, statbuf->st_ctim.tv_nsec / 1000);
1014 1015
#endif

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
#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

1028 1029
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ETAG_VALUE))
1030 1031
    {
      char *etag = _g_local_file_info_create_etag (statbuf);
1032
      _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ETAG_VALUE, etag);
1033 1034 1035
      g_free (etag);
    }

1036 1037
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ID_FILE))
1038 1039
    {
      char *id = _g_local_file_info_create_file_id (statbuf);
1040
      _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILE, id);
1041 1042 1043
      g_free (id);
    }

1044 1045
  if (_g_file_attribute_matcher_matches_id (attribute_matcher,
					    G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM))
1046 1047
    {
      char *id = _g_local_file_info_create_fs_id (statbuf);
1048
      _g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_ID_FILESYSTEM, id);
1049 1050 1051 1052
      g_free (id);
    }
}

1053 1054
#ifndef G_OS_WIN32

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
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);

1088
  g_warn_if_fail (g_utf8_validate (string->str, -1, NULL));
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
  
  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;
}
1109

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
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;
1126
#ifndef __BIONIC__
1127
  char *gecos, *comma;
1128 1129
#endif

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  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);

1140
#if defined(HAVE_GETPWUID_R)
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  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);

1151
#ifndef __BIONIC__
1152 1153 1154 1155 1156 1157 1158 1159 1160
      gecos = pwbufp->pw_gecos;

      if (gecos)
	{
	  comma = strchr (gecos, ',');
	  if (comma)
	    *comma = 0;
	  data->real_name = convert_pwd_string_to_utf8 (gecos);
	}
1161
#endif
1162 1163 1164 1165 1166 1167 1168 1169
    }

  /* 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
1170
	data->real_name = g_strdup_printf ("user #%d", (int)uid);
1171 1172 1173
    }
  
  if (data->user_name == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
1174
    data->user_name = g_strdup_printf ("%d", (int)uid);
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 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
  
  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;
1214
#if defined (HAVE_GETGRGID_R)
1215 1216
  char buffer[4096];
  struct group gbuf;
1217
#endif
1218
  struct group *gbufp;
1219

1220 1221 1222 1223 1224 1225 1226 1227
  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;

1228
#if defined (HAVE_GETGRGID_R)
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  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;
}
1258

1259
#endif /* !G_OS_WIN32 */
1260 1261

static char *
1262 1263
get_content_type (const char          *basename,
		  const char          *path,
1264
		  GLocalFileStat      *statbuf,
1265 1266 1267 1268
		  gboolean             is_symlink,
		  gboolean             symlink_broken,
		  GFileQueryInfoFlags  flags,
		  gboolean             fast)
1269 1270 1271
{
  if (is_symlink &&
      (symlink_broken || (flags & G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS)))
Patrick Griffis's avatar
Patrick Griffis committed
1272
    return g_content_type_from_mime_type ("inode/symlink");
1273
  else if (statbuf != NULL && S_ISDIR(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1274
    return g_content_type_from_mime_type ("inode/directory");
1275
#ifndef G_OS_WIN32
1276
  else if (statbuf != NULL && S_ISCHR(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1277
    return g_content_type_from_mime_type ("inode/chardevice");
1278
  else if (statbuf != NULL && S_ISBLK(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1279
    return g_content_type_from_mime_type ("inode/blockdevice");
1280
  else if (statbuf != NULL && S_ISFIFO(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1281
    return g_content_type_from_mime_type ("inode/fifo");
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
  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");
    }
1293
#endif
1294
#ifdef S_ISSOCK
1295
  else if (statbuf != NULL && S_ISSOCK(statbuf->st_mode))
Patrick Griffis's avatar
Patrick Griffis committed
1296
    return g_content_type_from_mime_type ("inode/socket");
1297 1298 1299 1300 1301
#endif
  else
    {
      char *content_type;
      gboolean result_uncertain;
1302

1303 1304
      content_type = g_content_type_guess (basename, NULL, 0, &result_uncertain);
      
1305
#if !defined(G_OS_WIN32) && !defined(HAVE_COCOA)
1306
      if (!fast && result_uncertain && path != NULL)
1307 1308 1309
	{
	  guchar sniff_buffer[4096];
	  gsize sniff_length;
1310
	  int fd, errsv;
1311 1312 1313 1314

	  sniff_length = _g_unix_content_type_get_sniff_len ();
	  if (sniff_length > 4096)
	    sniff_length = 4096;
1315 1316

#ifdef O_NOATIME	  
1317
          fd = g_open (path, O_RDONLY | O_NOATIME, 0);
1318 1319
          errsv = errno;
          if (fd < 0 && errsv == EPERM)
1320
#endif
1321
	    fd = g_open (path, O_RDONLY, 0);
1322

1323 1324
	  if (fd != -1)
	    {
1325
	      gssize res;
1326 1327
	      
	      res = read (fd, sniff_buffer, sniff_length);
Colin Walters's avatar
Colin Walters committed
1328
	      (void) g_close (fd, NULL);
1329
	      if (res >= 0)
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
		{
		  g_free (content_type);
		  content_type = g_content_type_guess (basename, sniff_buffer, res, NULL);
		}
	    }
	}
#endif
      
      return content_type;
    }
  
}

1343
/* @stat_buf is the pre-calculated result of stat(path), or %NULL if that failed. */
1344
static void
1345 1346
get_thumbnail_attributes (const char     *path,
                          GFileInfo      *info,
1347
                          const GLocalFileStat *stat_buf)
1348
{
1349
  GChecksum *checksum;
1350 1351 1352 1353 1354 1355
  char *uri;
  char *filename;
  char *basename;

  uri = g_filename_to_uri (path, NULL, NULL);

1356
  checksum = g_checksum_new (G_CHECKSUM_MD5);
1357
  g_checksum_update (checksum, (const guchar *) uri, strlen (uri));
1358

1359 1360 1361
  basename = g_strconcat (g_checksum_get_string (checksum), ".png", NULL);
  g_checksum_free (checksum);

1362
  filename = g_build_filename (g_get_user_cache_dir (),
1363
                               "thumbnails", "large", basename,
1364
                               NULL);
1365 1366

  if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1367 1368 1369 1370 1371
    {
      _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));
    }
1372 1373 1374
  else
    {
      g_free (filename);
1375
      filename = g_build_filename (g_get_user_cache_dir (),
1376
                                   "thumbnails", "normal", basename,
1377
                                   NULL);
1378 1379

      if (g_file_test (filename, G_FILE_TEST_IS_REGULAR))
1380 1381 1382 1383 1384
        {
          _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));
        }
1385 1386
      else
        {
1387
          g_free (filename);
1388 1389 1390 1391 1392 1393 1394
          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))
1395 1396 1397 1398 1399
            {
              _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));
            }
1400
        }
1401 1402 1403
    }
  g_free (basename);
  g_free (filename);
1404
  g_free (uri);
1405 1406
}

1407
#ifdef G_OS_WIN32
1408
static void
Matthias Clasen's avatar
Matthias Clasen committed
1409 1410 1411 1412
win32_get_file_user_info (const gchar  *filename,
			  gchar       **group_name, 
			  gchar       **user_name, 
			  gchar       **real_name)
1413 1414
{
  PSECURITY_DESCRIPTOR psd = NULL;
1415
  DWORD sd_size = 0; /* first call calculates the size required */
1416 1417 1418 1419 1420 1421 1422 1423 1424
  
  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, 
1425 1426 1427 1428
                       GROUP_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION,
		       psd,
		       sd_size,
		       &sd_size))
1429
    {
1430
      PSID psid = 0;
1431 1432
      BOOL defaulted;
      SID_NAME_USE name_use = 0; /* don't care? */
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
      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
1449 1450
	name = g_try_malloc (name_len * sizeof (wchar_t));
	domain = g_try_malloc (domain_len * sizeof (wchar_t));
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
	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
1476 1477
	name = g_try_malloc (name_len * sizeof (wchar_t));
	domain = g_try_malloc (domain_len * sizeof (wchar_t));
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
	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);
1494 1495 1496
    }
  g_free (wfilename);
}
1497
#endif /* G_OS_WIN32 */
1498

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
#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)
{
1517
  gchar *contents = NULL;
1518 1519 1520
  gchar *filename;

  filename = g_build_path ("/", dirname, ".hidden", NULL);
1521
  (void) g_file_get_contents (filename, &contents, NULL, NULL);
1522 1523
  g_free (filename);

1524
  if (contents != NULL)
1525 1526
    {
      GHashTable *table;
1527 1528
      gchar **lines;
      gint i;
1529 1530 1531

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

1532 1533
      lines = g_strsplit (contents, "\n", 0);
      g_free (contents);
1534

1535 1536 1537
      for (i = 0; lines[i]; i++)
        /* hash table takes the individual strings... */
        g_hash_table_add (table, lines[i]);
1538

1539 1540
      /* ... so we only free the container. */
      g_free (lines);
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 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

      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);
    }

1592
  result = table != NULL && g_hash_table_contains (table, basename);
1593 1594 1595 1596 1597 1598 1599 1600 1601

  G_UNLOCK (hidden_cache);

  g_free (dirname);

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

1602 1603 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
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);
    }
}

1645 1646 1647 1648 1649 1650 1651 1652
static const char *
get_icon_name (const char *path,
               gboolean    use_symbolic,
               gboolean   *with_fallbacks_out)
{
  const char *name = NULL;
  gboolean with_fallbacks = TRUE;

1653
  if (g_strcmp0 (path, g_get_home_dir ()) == 0)
1654 1655 1656 1657
    {
      name = use_symbolic ? "user-home-symbolic" : "user-home";
      with_fallbacks = FALSE;
    }
1658
  else if (g_strcmp0 (path, g_get_user_special_dir (G_USER_DIRECTORY_DESKTOP)) == 0)
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700