glocalfile.c 57.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* 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
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Author: Alexander Larsson <alexl@redhat.com>
 */

23
#include "config.h"
24 25 26 27 28 29

#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
30
#ifdef HAVE_UNISTD_H
31
#include <unistd.h>
32
#endif
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

#if HAVE_SYS_STATFS_H
#include <sys/statfs.h>
#endif
#if HAVE_SYS_STATVFS_H
#include <sys/statvfs.h>
#endif
#if HAVE_SYS_VFS_H
#include <sys/vfs.h>
#elif HAVE_SYS_MOUNT_H
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <sys/mount.h>
#endif

49 50 51 52
#ifndef O_BINARY
#define O_BINARY 0
#endif

53 54 55
#if defined(HAVE_STATFS) && defined(HAVE_STATVFS)
/* Some systems have both statfs and statvfs, pick the
   most "native" for these */
56 57
# if !defined(HAVE_STRUCT_STATFS_F_BAVAIL)
   /* on solaris and irix, statfs doesn't even have the
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
      f_bavail field */
#  define USE_STATVFS
# else
  /* at least on linux, statfs is the actual syscall */
#  define USE_STATFS
# endif

#elif defined(HAVE_STATFS)

# define USE_STATFS

#elif defined(HAVE_STATVFS)

# define USE_STATVFS

#endif

75
#include "gfileattribute.h"
76 77 78 79 80
#include "glocalfile.h"
#include "glocalfileinfo.h"
#include "glocalfileenumerator.h"
#include "glocalfileinputstream.h"
#include "glocalfileoutputstream.h"
81
#include "glocalfileiostream.h"
82 83
#include "glocaldirectorymonitor.h"
#include "glocalfilemonitor.h"
84
#include "gmountprivate.h"
85 86
#include "gunixmounts.h"
#include "gioerror.h"
87 88 89
#include <glib/gstdio.h>
#include "glibintl.h"

90
#ifdef G_OS_WIN32
91
#define _WIN32_WINNT 0x0500
92 93 94 95
#include <windows.h>
#include <io.h>
#include <direct.h>

96 97 98 99
#ifndef FILE_READ_ONLY_VOLUME
#define FILE_READ_ONLY_VOLUME           0x00080000
#endif

100 101 102 103 104 105 106 107
#ifndef S_ISDIR
#define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
#endif
#ifndef S_ISLNK
#define S_ISLNK(m) (0)
#endif
#endif

108 109
#include "gioalias.h"

Matthias Clasen's avatar
Matthias Clasen committed
110
static void g_local_file_file_iface_init (GFileIface *iface);
111 112 113 114 115 116 117 118 119 120 121

static GFileAttributeInfoList *local_writable_attributes = NULL;
static GFileAttributeInfoList *local_writable_namespaces = NULL;

struct _GLocalFile
{
  GObject parent_instance;

  char *filename;
};

122
#define g_local_file_get_type _g_local_file_get_type
123 124 125 126
G_DEFINE_TYPE_WITH_CODE (GLocalFile, g_local_file, G_TYPE_OBJECT,
			 G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
						g_local_file_file_iface_init))

Matthias Clasen's avatar
Matthias Clasen committed
127
static char *find_mountpoint_for (const char *file, dev_t dev);
128 129 130 131 132 133 134 135 136

static void
g_local_file_finalize (GObject *object)
{
  GLocalFile *local;

  local = G_LOCAL_FILE (object);

  g_free (local->filename);
137 138

  G_OBJECT_CLASS (g_local_file_parent_class)->finalize (object);
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
}

static void
g_local_file_class_init (GLocalFileClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GFileAttributeInfoList *list;

  gobject_class->finalize = g_local_file_finalize;

  /* Set up attribute lists */

  /* Writable attributes: */

  list = g_file_attribute_info_list_new ();

  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_UNIX_MODE,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
158
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
159
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
160 161 162 163 164
  
#ifdef HAVE_CHOWN
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_UNIX_UID,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
165
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
166 167 168
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_UNIX_GID,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
169
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
170 171 172 173
#endif
  
#ifdef HAVE_SYMLINK
  g_file_attribute_info_list_add (list,
174
				  G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
175 176 177 178 179 180 181 182
				  G_FILE_ATTRIBUTE_TYPE_BYTE_STRING,
				  0);
#endif
  
#ifdef HAVE_UTIMES
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_MODIFIED,
				  G_FILE_ATTRIBUTE_TYPE_UINT64,
183
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
184
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
185 186 187
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
188
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
189
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
190 191 192
  /* When copying, the target file is accessed. Replicating
   * the source access time does not make sense in this case.
   */
193 194 195
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_ACCESS,
				  G_FILE_ATTRIBUTE_TYPE_UINT64,
196
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
197 198 199
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
200
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
201 202 203 204 205 206 207 208 209 210 211 212
#endif

  local_writable_attributes = list;

  /* Writable namespaces: */
  
  list = g_file_attribute_info_list_new ();

#ifdef HAVE_XATTR
  g_file_attribute_info_list_add (list,
				  "xattr",
				  G_FILE_ATTRIBUTE_TYPE_STRING,
213 214
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
215
  g_file_attribute_info_list_add (list,
216
				  "xattr-sys",
217
				  G_FILE_ATTRIBUTE_TYPE_STRING,
218
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
#endif

  local_writable_namespaces = list;
}

static void
g_local_file_init (GLocalFile *local)
{
}


static char *
canonicalize_filename (const char *filename)
{
  char *canon, *start, *p, *q;
  char *cwd;
235
  int i;
236 237 238 239 240 241 242 243 244 245 246 247
  
  if (!g_path_is_absolute (filename))
    {
      cwd = g_get_current_dir ();
      canon = g_build_filename (cwd, filename, NULL);
      g_free (cwd);
    }
  else
    canon = g_strdup (filename);

  start = (char *)g_path_skip_root (canon);

248 249 250 251 252 253 254 255 256
  if (start == NULL)
    {
      /* This shouldn't really happen, as g_get_current_dir() should
	 return an absolute pathname, but bug 573843 shows this is
	 not always happening */
      g_free (canon);
      return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
    }
  
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  /* POSIX allows double slashes at the start to
   * mean something special (as does windows too).
   * So, "//" != "/", but more than two slashes
   * is treated as "/".
   */
  i = 0;
  for (p = start - 1;
       (p >= canon) &&
	 G_IS_DIR_SEPARATOR (*p);
       p--)
    i++;
  if (i > 2)
    {
      i -= 1;
      start -= i;
      memmove (start, start+i, strlen (start+i)+1);
    }
  
275 276 277 278 279 280 281 282 283 284 285 286 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
  p = start;
  while (*p != 0)
    {
      if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
	{
	  memmove (p, p+1, strlen (p+1)+1);
	}
      else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
	{
	  q = p + 2;
	  /* Skip previous separator */
	  p = p - 2;
	  if (p < start)
	    p = start;
	  while (p > start && !G_IS_DIR_SEPARATOR (*p))
	    p--;
	  if (G_IS_DIR_SEPARATOR (*p))
	    *p++ = G_DIR_SEPARATOR;
	  memmove (p, q, strlen (q)+1);
	}
      else
	{
	  /* Skip until next separator */
	  while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
	    p++;
	  
	  if (*p != 0)
	    {
	      /* Canonicalize one separator */
	      *p++ = G_DIR_SEPARATOR;
	    }
	}

      /* Remove additional separators */
      q = p;
      while (*q && G_IS_DIR_SEPARATOR (*q))
	q++;

      if (p != q)
	memmove (p, q, strlen (q)+1);
    }

  /* Remove trailing slashes */
  if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
    *(p-1) = 0;
  
  return canon;
}

/**
325
 * _g_local_file_new:
326 327 328 329 330
 * @filename: filename of the file to create.
 * 
 * Returns: new local #GFile.
 **/
GFile *
331
_g_local_file_new (const char *filename)
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
{
  GLocalFile *local;

  local = g_object_new (G_TYPE_LOCAL_FILE, NULL);
  local->filename = canonicalize_filename (filename);
  
  return G_FILE (local);
}

static gboolean
g_local_file_is_native (GFile *file)
{
  return TRUE;
}

static gboolean
348
g_local_file_has_uri_scheme (GFile      *file,
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 389 390 391 392 393
			     const char *uri_scheme)
{
  return g_ascii_strcasecmp (uri_scheme, "file") == 0;
}

static char *
g_local_file_get_uri_scheme (GFile *file)
{
  return g_strdup ("file");
}

static char *
g_local_file_get_basename (GFile *file)
{
  return g_path_get_basename (G_LOCAL_FILE (file)->filename);
}

static char *
g_local_file_get_path (GFile *file)
{
  return g_strdup (G_LOCAL_FILE (file)->filename);
}

static char *
g_local_file_get_uri (GFile *file)
{
  return g_filename_to_uri (G_LOCAL_FILE (file)->filename, NULL, NULL);
}

static gboolean
get_filename_charset (const gchar **filename_charset)
{
  const gchar **charsets;
  gboolean is_utf8;
  
  is_utf8 = g_get_filename_charsets (&charsets);

  if (filename_charset)
    *filename_charset = charsets[0];
  
  return is_utf8;
}

static gboolean
name_is_valid_for_display (const char *string,
394
			   gboolean    is_valid_utf8)
395 396
{
  char c;
397

398 399 400 401 402 403
  if (!is_valid_utf8 &&
      !g_utf8_validate (string, -1, NULL))
    return FALSE;

  while ((c = *string++) != 0)
    {
Matthias Clasen's avatar
Matthias Clasen committed
404
      if (g_ascii_iscntrl (c))
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	return FALSE;
    }

  return TRUE;
}

static char *
g_local_file_get_parse_name (GFile *file)
{
  const char *filename;
  char *parse_name;
  const gchar *charset;
  char *utf8_filename;
  char *roundtripped_filename;
  gboolean free_utf8_filename;
  gboolean is_valid_utf8;
421 422
  char *escaped_path;
  
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
  filename = G_LOCAL_FILE (file)->filename;
  if (get_filename_charset (&charset))
    {
      utf8_filename = (char *)filename;
      free_utf8_filename = FALSE;
      is_valid_utf8 = FALSE; /* Can't guarantee this */
    }
  else
    {
      utf8_filename = g_convert (filename, -1, 
				 "UTF-8", charset, NULL, NULL, NULL);
      free_utf8_filename = TRUE;
      is_valid_utf8 = TRUE;

      if (utf8_filename != NULL)
	{
	  /* Make sure we can roundtrip: */
	  roundtripped_filename = g_convert (utf8_filename, -1,
					     charset, "UTF-8", NULL, NULL, NULL);
	  
	  if (roundtripped_filename == NULL ||
	      strcmp (utf8_filename, roundtripped_filename) != 0)
	    {
	      g_free (utf8_filename);
	      utf8_filename = NULL;
	    }
449 450

	  g_free (roundtripped_filename);
451 452 453 454 455 456 457 458 459 460 461 462 463
	}
    }

  if (utf8_filename != NULL &&
      name_is_valid_for_display (utf8_filename, is_valid_utf8))
    {
      if (free_utf8_filename)
	parse_name = utf8_filename;
      else
	parse_name = g_strdup (utf8_filename);
    }
  else
    {
464 465 466 467 468 469 470 471 472 473
      escaped_path = g_uri_escape_string (filename,
					  G_URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/",
					  TRUE);
      parse_name = g_strconcat ("file://",
				(*escaped_path != '/') ? "/" : "",
				escaped_path,
				NULL);
      
      g_free (escaped_path);

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
      if (free_utf8_filename)
	g_free (utf8_filename);
    }
  
  return parse_name;
}

static GFile *
g_local_file_get_parent (GFile *file)
{
  GLocalFile *local = G_LOCAL_FILE (file);
  const char *non_root;
  char *dirname;
  GFile *parent;

  /* Check for root */
  non_root = g_path_skip_root (local->filename);
  if (*non_root == 0)
    return NULL;

  dirname = g_path_get_dirname (local->filename);
495
  parent = _g_local_file_new (dirname);
496 497 498 499 500 501 502 503 504
  g_free (dirname);
  return parent;
}

static GFile *
g_local_file_dup (GFile *file)
{
  GLocalFile *local = G_LOCAL_FILE (file);

505
  return _g_local_file_new (local->filename);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
}

static guint
g_local_file_hash (GFile *file)
{
  GLocalFile *local = G_LOCAL_FILE (file);
  
  return g_str_hash (local->filename);
}

static gboolean
g_local_file_equal (GFile *file1,
		    GFile *file2)
{
  GLocalFile *local1 = G_LOCAL_FILE (file1);
  GLocalFile *local2 = G_LOCAL_FILE (file2);

  return g_str_equal (local1->filename, local2->filename);
}

static const char *
527 528
match_prefix (const char *path, 
              const char *prefix)
529 530 531 532 533 534
{
  int prefix_len;

  prefix_len = strlen (prefix);
  if (strncmp (path, prefix, prefix_len) != 0)
    return NULL;
535 536 537 538 539 540 541
  
  /* Handle the case where prefix is the root, so that
   * the IS_DIR_SEPRARATOR check below works */
  if (prefix_len > 0 &&
      G_IS_DIR_SEPARATOR (prefix[prefix_len-1]))
    prefix_len--;
  
542 543 544 545
  return path + prefix_len;
}

static gboolean
546 547
g_local_file_prefix_matches (GFile *parent,
			     GFile *descendant)
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
{
  GLocalFile *parent_local = G_LOCAL_FILE (parent);
  GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
  const char *remainder;

  remainder = match_prefix (descendant_local->filename, parent_local->filename);
  if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
    return TRUE;
  return FALSE;
}

static char *
g_local_file_get_relative_path (GFile *parent,
				GFile *descendant)
{
  GLocalFile *parent_local = G_LOCAL_FILE (parent);
  GLocalFile *descendant_local = G_LOCAL_FILE (descendant);
  const char *remainder;

  remainder = match_prefix (descendant_local->filename, parent_local->filename);
  
  if (remainder != NULL && G_IS_DIR_SEPARATOR (*remainder))
    return g_strdup (remainder + 1);
  return NULL;
}

static GFile *
575
g_local_file_resolve_relative_path (GFile      *file,
576 577 578 579 580 581 582
				    const char *relative_path)
{
  GLocalFile *local = G_LOCAL_FILE (file);
  char *filename;
  GFile *child;

  if (g_path_is_absolute (relative_path))
583
    return _g_local_file_new (relative_path);
584 585
  
  filename = g_build_filename (local->filename, relative_path, NULL);
586
  child = _g_local_file_new (filename);
587 588 589 590 591 592
  g_free (filename);
  
  return child;
}

static GFileEnumerator *
593 594 595 596 597
g_local_file_enumerate_children (GFile                *file,
				 const char           *attributes,
				 GFileQueryInfoFlags   flags,
				 GCancellable         *cancellable,
				 GError              **error)
598 599
{
  GLocalFile *local = G_LOCAL_FILE (file);
600
  return _g_local_file_enumerator_new (local,
601 602
				       attributes, flags,
				       cancellable, error);
603 604 605 606 607 608 609
}

static GFile *
g_local_file_get_child_for_display_name (GFile        *file,
					 const char   *display_name,
					 GError      **error)
{
610
  GFile *new_file;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
  char *basename;

  basename = g_filename_from_utf8 (display_name, -1, NULL, NULL, NULL);
  if (basename == NULL)
    {
      g_set_error (error, G_IO_ERROR,
		   G_IO_ERROR_INVALID_FILENAME,
		   _("Invalid filename %s"), display_name);
      return NULL;
    }

  new_file = g_file_get_child (file, basename);
  g_free (basename);
  
  return new_file;
}

#ifdef USE_STATFS
static const char *
get_fs_type (long f_type)
{
  /* filesystem ids taken from linux manpage */
633 634 635 636
  switch (f_type) 
    {
    case 0xadf5:
      return "adfs";
637 638 639 640
    case 0x5346414f:
      return "afs";
    case 0x0187:
      return "autofs";
641 642 643 644 645 646
    case 0xADFF:
      return "affs";
    case 0x42465331:
      return "befs";
    case 0x1BADFACE:
      return "bfs";
647 648
    case 0x9123683E:
      return "btrfs";
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    case 0xFF534D42:
      return "cifs";
    case 0x73757245:
      return "coda";
    case 0x012FF7B7:
      return "coh";
    case 0x28cd3d45:
      return "cramfs";
    case 0x1373:
      return "devfs";
    case 0x00414A53:
      return "efs";
    case 0x137D:
      return "ext";
    case 0xEF51:
      return "ext2";
    case 0xEF53:
666
      return "ext3/ext4";
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
    case 0x4244:
      return "hfs";
    case 0xF995E849:
      return "hpfs";
    case 0x958458f6:
      return "hugetlbfs";
    case 0x9660:
      return "isofs";
    case 0x72b6:
      return "jffs2";
    case 0x3153464a:
      return "jfs";
    case 0x137F:
      return "minix";
    case 0x138F:
      return "minix2";
    case 0x2468:
      return "minix2";
    case 0x2478:
      return "minix22";
    case 0x4d44:
      return "msdos";
    case 0x564c:
      return "ncp";
    case 0x6969:
      return "nfs";
    case 0x5346544e:
      return "ntfs";
    case 0x9fa1:
      return "openprom";
    case 0x9fa0:
      return "proc";
    case 0x002f:
      return "qnx4";
    case 0x52654973:
      return "reiserfs";
    case 0x7275:
      return "romfs";
    case 0x517B:
      return "smb";
707 708
    case 0x73717368:
      return "squashfs";
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
    case 0x012FF7B6:
      return "sysv2";
    case 0x012FF7B5:
      return "sysv4";
    case 0x01021994:
      return "tmpfs";
    case 0x15013346:
      return "udf";
    case 0x00011954:
      return "ufs";
    case 0x9fa2:
      return "usbdevice";
    case 0xa501FCF5:
      return "vxfs";
    case 0x012FF7B4:
      return "xenix";
    case 0x58465342:
      return "xfs";
    case 0x012FD16D:
      return "xiafs";
    default:
      return NULL;
    }
732 733 734
}
#endif

735 736
#ifndef G_OS_WIN32

737 738
G_LOCK_DEFINE_STATIC(mount_info_hash);
static GHashTable *mount_info_hash = NULL;
739
static guint64 mount_info_hash_cache_time = 0;
740 741 742 743 744 745 746

typedef enum {
  MOUNT_INFO_READONLY = 1<<0
} MountInfo;

static gboolean
device_equal (gconstpointer v1,
747
              gconstpointer v2)
748
{
Matthias Clasen's avatar
Matthias Clasen committed
749
  return *(dev_t *)v1 == *(dev_t *)v2;
750 751 752
}

static guint
753
device_hash (gconstpointer v)
754 755 756 757 758
{
  return (guint) *(dev_t *)v;
}

static void
759 760
get_mount_info (GFileInfo             *fs_info,
		const char            *path,
761 762 763 764 765 766 767 768
		GFileAttributeMatcher *matcher)
{
  struct stat buf;
  gboolean got_info;
  gpointer info_as_ptr;
  guint mount_info;
  char *mountpoint;
  dev_t *dev;
769
  GUnixMountEntry *mount;
770 771
  guint64 cache_time;

772
  if (g_lstat (path, &buf) != 0)
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    return;

  G_LOCK (mount_info_hash);

  if (mount_info_hash == NULL)
    mount_info_hash = g_hash_table_new_full (device_hash, device_equal,
					     g_free, NULL);


  if (g_unix_mounts_changed_since (mount_info_hash_cache_time))
    g_hash_table_remove_all (mount_info_hash);
  
  got_info = g_hash_table_lookup_extended (mount_info_hash,
					   &buf.st_dev,
					   NULL,
					   &info_as_ptr);
  
  G_UNLOCK (mount_info_hash);
  
  mount_info = GPOINTER_TO_UINT (info_as_ptr);
  
  if (!got_info)
    {
      mount_info = 0;

      mountpoint = find_mountpoint_for (path, buf.st_dev);
      if (mountpoint == NULL)
800
	mountpoint = g_strdup ("/");
801

802
      mount = g_unix_mount_at (mountpoint, &cache_time);
803 804 805 806 807 808 809 810
      if (mount)
	{
	  if (g_unix_mount_is_readonly (mount))
	    mount_info |= MOUNT_INFO_READONLY;
	  
	  g_unix_mount_free (mount);
	}

811 812
      g_free (mountpoint);

813 814 815 816 817 818 819 820 821 822
      dev = g_new0 (dev_t, 1);
      *dev = buf.st_dev;
      
      G_LOCK (mount_info_hash);
      mount_info_hash_cache_time = cache_time;
      g_hash_table_insert (mount_info_hash, dev, GUINT_TO_POINTER (mount_info));
      G_UNLOCK (mount_info_hash);
    }

  if (mount_info & MOUNT_INFO_READONLY)
823
    g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
824 825
}

826 827
#endif

828 829 830 831 832 833 834 835 836
#ifdef G_OS_WIN32

static gboolean
is_xp_or_later (void)
{
  static int result = -1;

  if (result == -1)
    {
837
#ifndef _MSC_VER    
838 839 840 841 842 843 844 845 846 847 848 849 850 851
      OSVERSIONINFOEX ver_info = {0};
      DWORDLONG cond_mask = 0;
      int op = VER_GREATER_EQUAL;

      ver_info.dwOSVersionInfoSize = sizeof ver_info;
      ver_info.dwMajorVersion = 5;
      ver_info.dwMinorVersion = 1;

      VER_SET_CONDITION (cond_mask, VER_MAJORVERSION, op);
      VER_SET_CONDITION (cond_mask, VER_MINORVERSION, op);

      result = VerifyVersionInfo (&ver_info,
				  VER_MAJORVERSION | VER_MINORVERSION, 
				  cond_mask) != 0;
852 853 854
#else
      result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;  
#endif
855 856 857 858 859 860 861 862 863 864 865 866
    }

  return result;
}

static wchar_t *
get_volume_for_path (const char *path)
{
  long len;
  wchar_t *wpath;
  wchar_t *result;

867 868
  wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
  result = g_new (wchar_t, MAX_PATH);
869

870
  if (!GetVolumePathNameW (wpath, result, MAX_PATH))
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    {
      char *msg = g_win32_error_message (GetLastError ());
      g_critical ("GetVolumePathName failed: %s", msg);
      g_free (msg);
      g_free (result);
      g_free (wpath);
      return NULL;
    }

  len = wcslen (result);
  if (len > 0 && result[len-1] != L'\\')
    {
      result = g_renew (wchar_t, result, len + 2);
      result[len] = L'\\';
      result[len + 1] = 0;
    }

  g_free (wpath);
  return result;
}

static char *
find_mountpoint_for (const char *file, dev_t dev)
{
  wchar_t *wpath;
  char *utf8_path;

  wpath = get_volume_for_path (file);
  if (!wpath)
    return NULL;

  utf8_path = g_utf16_to_utf8 (wpath, -1, NULL, NULL, NULL);

  g_free (wpath);
  return utf8_path;
}

static void
get_filesystem_readonly (GFileInfo  *info,
			 const char *path)
{
  wchar_t *rootdir;

  rootdir = get_volume_for_path (path);

  if (rootdir)
    {
      if (is_xp_or_later ())
        {
          DWORD flags;
          if (GetVolumeInformationW (rootdir, NULL, 0, NULL, NULL, &flags, NULL, 0))
	    g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
					       (flags & FILE_READ_ONLY_VOLUME) != 0);
        }
      else
        {
          if (GetDriveTypeW (rootdir) == DRIVE_CDROM)
	    g_file_info_set_attribute_boolean (info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
        }
    }

  g_free (rootdir);
}

#endif /* G_OS_WIN32 */

937
static GFileInfo *
938 939 940 941
g_local_file_query_filesystem_info (GFile         *file,
				    const char    *attributes,
				    GCancellable  *cancellable,
				    GError       **error)
942 943 944
{
  GLocalFile *local = G_LOCAL_FILE (file);
  GFileInfo *info;
945
  int statfs_result = 0;
946
  gboolean no_size;
947
#ifndef G_OS_WIN32
948
  guint64 block_size;
949
  const char *fstype;
950 951 952 953
#ifdef USE_STATFS
  struct statfs statfs_buffer;
#elif defined(USE_STATVFS)
  struct statvfs statfs_buffer;
954
#endif
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
#endif
  GFileAttributeMatcher *attribute_matcher;
	
  no_size = FALSE;
  
#ifdef USE_STATFS
  
#if STATFS_ARGS == 2
  statfs_result = statfs (local->filename, &statfs_buffer);
#elif STATFS_ARGS == 4
  statfs_result = statfs (local->filename, &statfs_buffer,
			  sizeof (statfs_buffer), 0);
#endif
  block_size = statfs_buffer.f_bsize;
  
970 971 972 973
  /* Many backends can't report free size (for instance the gvfs fuse
     backend for backend not supporting this), and set f_bfree to 0,
     but it can be 0 for real too. We treat the availible == 0 and
     free == 0 case as "both of these are invalid".
974
   */
975 976
#ifndef G_OS_WIN32
  if (statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0)
977 978 979 980 981 982 983 984 985 986
    no_size = TRUE;
#endif
  
#elif defined(USE_STATVFS)
  statfs_result = statvfs (local->filename, &statfs_buffer);
  block_size = statfs_buffer.f_frsize; 
#endif

  if (statfs_result == -1)
    {
987 988
      int errsv = errno;

989
      g_set_error (error, G_IO_ERROR,
990
		   g_io_error_from_errno (errsv),
991
		   _("Error getting filesystem info: %s"),
992
		   g_strerror (errsv));
993 994 995 996 997 998 999
      return NULL;
    }

  info = g_file_info_new ();

  attribute_matcher = g_file_attribute_matcher_new (attributes);
  
1000 1001
  if (!no_size &&
      g_file_attribute_matcher_matches (attribute_matcher,
1002
					G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
1003 1004 1005 1006 1007 1008 1009 1010
    {
#ifdef G_OS_WIN32
      gchar *localdir = g_path_get_dirname (local->filename);
      wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
      ULARGE_INTEGER li;
      
      g_free (localdir);
      if (GetDiskFreeSpaceExW (wdirname, &li, NULL, NULL))
1011
        g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1012 1013
      g_free (wdirname);
#else
1014
      g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1015 1016
#endif
    }
1017 1018
  if (!no_size &&
      g_file_attribute_matcher_matches (attribute_matcher,
1019
					G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1020 1021 1022 1023 1024 1025 1026 1027
    {
#ifdef G_OS_WIN32
      gchar *localdir = g_path_get_dirname (local->filename);
      wchar_t *wdirname = g_utf8_to_utf16 (localdir, -1, NULL, NULL, NULL);
      ULARGE_INTEGER li;
      
      g_free (localdir);
      if (GetDiskFreeSpaceExW (wdirname, NULL, &li, NULL))
1028
        g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE,  (guint64)li.QuadPart);
1029 1030
      g_free (wdirname);
#else
1031
      g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1032 1033
#endif
    }
1034
#ifdef USE_STATFS
1035
#if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1036 1037
  fstype = g_strdup(statfs_buffer.f_fstypename);
#else
1038
  fstype = get_fs_type (statfs_buffer.f_type);
1039
#endif
1040 1041 1042 1043 1044 1045

#elif defined(USE_STATVFS) && defined(HAVE_STRUCT_STATVFS_F_BASETYPE)
  fstype = g_strdup(statfs_buffer.f_basetype); 
#endif

#ifndef G_OS_WIN32
1046 1047
  if (fstype &&
      g_file_attribute_matcher_matches (attribute_matcher,
1048 1049
					G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
    g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1050 1051 1052
#endif  

  if (g_file_attribute_matcher_matches (attribute_matcher,
1053
					G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
1054
    {
1055
#ifdef G_OS_WIN32
1056
      get_filesystem_readonly (info, local->filename);
1057
#else
1058
      get_mount_info (info, local->filename, attribute_matcher);
1059
#endif
1060 1061 1062 1063 1064 1065 1066
    }
  
  g_file_attribute_matcher_unref (attribute_matcher);
  
  return info;
}

1067 1068 1069 1070
static GMount *
g_local_file_find_enclosing_mount (GFile         *file,
                                   GCancellable  *cancellable,
                                   GError       **error)
1071 1072 1073 1074
{
  GLocalFile *local = G_LOCAL_FILE (file);
  struct stat buf;
  char *mountpoint;
1075
  GMount *mount;
1076

1077
  if (g_lstat (local->filename, &buf) != 0)
1078
    {
1079
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1080 1081 1082 1083
		      /* Translators: This is an error message when trying to
		       * find the enclosing (user visible) mount of a file, but
		       * none exists. */
		      _("Containing mount does not exist"));
1084 1085 1086 1087 1088 1089
      return NULL;
    }

  mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
  if (mountpoint == NULL)
    {
1090
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1091 1092 1093 1094
		      /* Translators: This is an error message when trying to
		       * find the enclosing (user visible) mount of a file, but
		       * none exists. */
		      _("Containing mount does not exist"));
1095 1096 1097
      return NULL;
    }

1098
  mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1099
  g_free (mountpoint);
1100 1101
  if (mount)
    return mount;
1102

1103
  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1104 1105 1106 1107
		  /* Translators: This is an error message when trying to find
		   * the enclosing (user visible) mount of a file, but none
		   * exists. */
		  _("Containing mount does not exist"));
1108 1109 1110 1111
  return NULL;
}

static GFile *
1112 1113 1114 1115
g_local_file_set_display_name (GFile         *file,
			       const char    *display_name,
			       GCancellable  *cancellable,
			       GError       **error)
1116 1117 1118 1119 1120 1121 1122 1123 1124
{
  GLocalFile *local, *new_local;
  GFile *new_file, *parent;
  struct stat statbuf;
  int errsv;

  parent = g_file_get_parent (file);
  if (parent == NULL)
    {
1125 1126 1127
      g_set_error_literal (error, G_IO_ERROR,
                           G_IO_ERROR_FAILED,
                           _("Can't rename root directory"));
1128 1129 1130
      return NULL;
    }
  
Matthias Clasen's avatar
Matthias Clasen committed
1131
  new_file = g_file_get_child_for_display_name (parent, display_name, error);
1132 1133 1134 1135 1136 1137 1138
  g_object_unref (parent);
  
  if (new_file == NULL)
    return NULL;
  local = G_LOCAL_FILE (file);
  new_local = G_LOCAL_FILE (new_file);

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
  if (g_lstat (new_local->filename, &statbuf) == -1) 
    {
      errsv = errno;

      if (errsv != ENOENT)
        {
	  g_set_error (error, G_IO_ERROR,
		       g_io_error_from_errno (errsv),
		       _("Error renaming file: %s"),
		       g_strerror (errsv));
          return NULL;
        }
    }
  else
1153
    {
1154 1155 1156
      g_set_error_literal (error, G_IO_ERROR,
                           G_IO_ERROR_EXISTS,
                           _("Can't rename file, filename already exist"));
1157 1158 1159
      return NULL;
    }

1160
  if (g_rename (local->filename, new_local->filename) == -1)
1161 1162 1163 1164 1165 1166
    {
      errsv = errno;

      if (errsv == EINVAL)
	/* We can't get a rename file into itself error herer,
	   so this must be an invalid filename, on e.g. FAT */
1167 1168 1169
	g_set_error_literal (error, G_IO_ERROR,
                             G_IO_ERROR_INVALID_FILENAME,
                             _("Invalid filename"));
1170 1171 1172 1173 1174 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 1214
      else
	g_set_error (error, G_IO_ERROR,
		     g_io_error_from_errno (errsv),
		     _("Error renaming file: %s"),
		     g_strerror (errsv));
      g_object_unref (new_file);
      return NULL;
    }
  
  return new_file;
}

static GFileInfo *
g_local_file_query_info (GFile                *file,
			 const char           *attributes,
			 GFileQueryInfoFlags   flags,
			 GCancellable         *cancellable,
			 GError              **error)
{
  GLocalFile *local = G_LOCAL_FILE (file);
  GFileInfo *info;
  GFileAttributeMatcher *matcher;
  char *basename, *dirname;
  GLocalParentFileInfo parent_info;

  matcher = g_file_attribute_matcher_new (attributes);
  
  basename = g_path_get_basename (local->filename);
  
  dirname = g_path_get_dirname (local->filename);
  _g_local_file_info_get_parent_info (dirname, matcher, &parent_info);
  g_free (dirname);
  
  info = _g_local_file_info_get (basename, local->filename,
				 matcher, flags, &parent_info,
				 error);
  
  g_free (basename);

  g_file_attribute_matcher_unref (matcher);

  return info;
}

static GFileAttributeInfoList *
1215 1216 1217
g_local_file_query_settable_attributes (GFile         *file,
					GCancellable  *cancellable,
					GError       **error)
1218 1219 1220 1221 1222
{
  return g_file_attribute_info_list_ref (local_writable_attributes);
}

static GFileAttributeInfoList *
1223 1224 1225
g_local_file_query_writable_namespaces (GFile         *file,
					GCancellable  *cancellable,
					GError       **error)
1226 1227 1228 1229 1230
{
  return g_file_attribute_info_list_ref (local_writable_namespaces);
}

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1231 1232 1233 1234 1235 1236 1237
g_local_file_set_attribute (GFile                *file,
			    const char           *attribute,
			    GFileAttributeType    type,
			    gpointer              value_p,
			    GFileQueryInfoFlags   flags,
			    GCancellable         *cancellable,
			    GError              **error)
1238 1239 1240 1241 1242
{
  GLocalFile *local = G_LOCAL_FILE (file);

  return _g_local_file_info_set_attribute (local->filename,
					   attribute,
1243 1244
					   type,
					   value_p,
1245 1246 1247 1248 1249 1250
					   flags,
					   cancellable,
					   error);
}

static gboolean
1251 1252 1253 1254 1255
g_local_file_set_attributes_from_info (GFile                *file,
				       GFileInfo            *info,
				       GFileQueryInfoFlags   flags,
				       GCancellable         *cancellable,
				       GError              **error)
1256 1257 1258
{
  GLocalFile *local = G_LOCAL_FILE (file);
  int res, chained_res;
Matthias Clasen's avatar
Matthias Clasen committed
1259
  GFileIface *default_iface;
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276

  res = _g_local_file_info_set_attributes (local->filename,
					   info, flags, 
					   cancellable,
					   error);

  if (!res)
    error = NULL; /* Don't write over error if further errors */

  default_iface = g_type_default_interface_peek (G_TYPE_FILE);

  chained_res = (default_iface->set_attributes_from_info) (file, info, flags, cancellable, error);
  
  return res && chained_res;
}

static GFileInputStream *
1277 1278 1279
g_local_file_read (GFile         *file,
		   GCancellable  *cancellable,
		   GError       **error)
1280 1281 1282 1283 1284
{
  GLocalFile *local = G_LOCAL_FILE (file);
  int fd;
  struct stat buf;
  
1285
  fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1286 1287
  if (fd == -1)
    {
1288 1289
      int errsv = errno;

1290
      g_set_error (error, G_IO_ERROR,
1291
		   g_io_error_from_errno (errsv),
1292
		   _("Error opening file: %s"),
1293
		   g_strerror (errsv));
1294 1295 1296 1297 1298 1299
      return NULL;
    }

  if (fstat(fd, &buf) == 0 && S_ISDIR (buf.st_mode))
    {
      close (fd);
1300 1301 1302
      g_set_error_literal (error, G_IO_ERROR,
                           G_IO_ERROR_IS_DIRECTORY,
                           _("Can't open directory"));
1303 1304 1305
      return NULL;
    }
  
1306
  return _g_local_file_input_stream_new (fd);
1307 1308 1309
}

static GFileOutputStream *
1310 1311 1312 1313
g_local_file_append_to (GFile             *file,
			GFileCreateFlags   flags,
			GCancellable      *cancellable,
			GError           **error)
1314
{
1315 1316
  return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
					     flags, cancellable, error);
1317 1318 1319
}

static GFileOutputStream *
1320 1321 1322 1323
g_local_file_create (GFile             *file,
		     GFileCreateFlags   flags,
		     GCancellable      *cancellable,
		     GError           **error)
1324
{
1325
  return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
1326
					     FALSE,
1327
					     flags, cancellable, error);
1328 1329 1330
}

static GFileOutputStream *
1331 1332 1333 1334 1335 1336
g_local_file_replace (GFile             *file,
		      const char        *etag,
		      gboolean           make_backup,
		      GFileCreateFlags   flags,
		      GCancellable      *cancellable,
		      GError           **error)
1337
{
1338
  return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
1339
					      FALSE,
1340 1341
					      etag, make_backup, flags,
					      cancellable, error);
1342 1343
}

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
static GFileIOStream *
g_local_file_open_readwrite (GFile                      *file,
			     GCancellable               *cancellable,
			     GError                    **error)
{
  GFileOutputStream *output;
  GFileIOStream *res;

  output = _g_local_file_output_stream_open (G_LOCAL_FILE (file)->filename,
					     TRUE,
					     cancellable, error);
  if (output == NULL)
    return NULL;

  res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
  g_object_unref (output);
  return res;
}

static GFileIOStream *
g_local_file_create_readwrite (GFile                      *file,
			       GFileCreateFlags            flags,
			       GCancellable               *cancellable,
			       GError                    **error)
{
  GFileOutputStream *output;
  GFileIOStream *res;

  output = _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
					       TRUE, flags,
					       cancellable, error);
  if (output == NULL)
    return NULL;

  res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
  g_object_unref (output);
  return res;
}

static GFileIOStream *
g_local_file_replace_readwrite (GFile                      *file,
				const char                 *etag,
				gboolean                    make_backup,
				GFileCreateFlags            flags,
				GCancellable               *cancellable,
				GError                    **error)
{
  GFileOutputStream *output;
  GFileIOStream *res;

  output = _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
						TRUE,
						etag, make_backup, flags,
						cancellable, error);
  if (output == NULL)
    return NULL;

  res = _g_local_file_io_stream_new (G_LOCAL_FILE_OUTPUT_STREAM (output));
  g_object_unref (output);
  return res;
}
1405 1406

static gboolean
1407 1408 1409
g_local_file_delete (GFile         *file,
		     GCancellable  *cancellable,
		     GError       **error)
1410 1411 1412 1413 1414
{
  GLocalFile *local = G_LOCAL_FILE (file);
  
  if (g_remove (local->filename) == -1)
    {
1415 1416
      int errsv = errno;

1417
      /* Posix allows EEXIST too, but the more sane error
1418
	 is G_IO_ERROR_NOT_FOUND, and it's what nautilus
1419 1420 1421 1422
	 expects */
      if (errsv == EEXIST)
	errsv = ENOTEMPTY;

1423
      g_set_error (error, G_IO_ERROR,
1424
		   g_io_error_from_errno (errsv),
1425
		   _("Error removing file: %s"),
1426
		   g_strerror (errsv));
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
      return FALSE;
    }
  
  return TRUE;
}

static char *
strip_trailing_slashes (const char *path)
{
  char *path_copy;
  int len;

  path_copy = g_strdup (path);
  len = strlen (path_copy);
  while (len > 1 && path_copy[len-1] == '/')
    path_copy[--len] = 0;

  return path_copy;
 }

static char *
expand_symlink (const char *link)
{
  char *resolved, *canonical, *parent, *link2;
  char symlink_value[4096];
1452 1453
#ifdef G_OS_WIN32
#else
1454
  ssize_t res;
1455
#endif
1456
  
1457 1458
#ifdef G_OS_WIN32
#else
1459
  res = readlink (link, symlink_value, sizeof (symlink_value) - 1);
1460
  
1461 1462 1463
  if (res == -1)
    return g_strdup (link);
  symlink_value[res] = 0;
1464
#endif
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
  
  if (g_path_is_absolute (symlink_value))
    return canonicalize_filename (symlink_value);
  else
    {
      link2 = strip_trailing_slashes (link);
      parent = g_path_get_dirname (link2);
      g_free (link2);
      
      resolved = g_build_filename (parent, symlink_value, NULL);
      g_free (parent);
      
      canonical = canonicalize_filename (resolved);
      
      g_free (resolved);

      return canonical;
    }
}

static char *
1486 1487
get_parent (const char *path, 
            dev_t      *parent_dev)
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
{
  char *parent, *tmp;
  struct stat parent_stat;
  int num_recursions;
  char *path_copy;

  path_copy = strip_trailing_slashes (path);
  
  parent = g_path_get_dirname (path_copy);
  if (strcmp (parent, ".") == 0 ||
      strcmp (parent, path_copy) == 0)
    {
Alexander Larsson's avatar
Alexander Larsson committed
1500
      g_free (parent);
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 1548 1549 1550 1551 1552 1553 1554 1555 1556
      g_free (path_copy);
      return NULL;
    }
  g_free (path_copy);

  num_recursions = 0;
  do {
    if (g_lstat (parent, &parent_stat) != 0)
      {
	g_free (parent);
	return NULL;
      }
    
    if (S_ISLNK (parent_stat.st_mode))
      {
	tmp = parent;
	parent = expand_symlink (parent);
	g_free (tmp);
      }
    
    num_recursions++;
    if (num_recursions > 12)
      {
	g_free (parent);
	return NULL;
      }
  } while (S_ISLNK (parent_stat.st_mode));

  *parent_dev = parent_stat.st_dev;
  
  return parent;
}

static char *
expand_all_symlinks (const char *path)
{
  char *parent, *parent_expanded;
  char *basename, *res;
  dev_t parent_dev;

  parent = get_parent (path, &parent_dev);
  if (parent)
    {
      parent_expanded = expand_all_symlinks (parent);
      g_free (parent);
      basename = g_path_get_basename (path);
      res = g_build_filename (parent_expanded, basename, NULL);
      g_free (basename);
      g_free (parent_expanded);
    }
  else
    res = g_strdup (path);
  
  return res;
}

1557 1558
#ifndef G_OS_WIN32

1559
static char *
1560 1561
find_mountpoint_for (const char *file, 
                     dev_t       dev)
1562 1563 1564 1565 1566 1567 1568
{
  char *dir, *parent;
  dev_t dir_dev, parent_dev;

  dir = g_strdup (file);
  dir_dev = dev;

1569 1570 1571 1572 1573
  while (1) 
    {
      parent = get_parent (dir, &parent_dev);
      if (parent == NULL)
        return dir;
1574
    
1575 1576 1577 1578 1579
      if (parent_dev != dir_dev)
        {
          g_free (parent);
          return dir;
        }
1580
    
1581 1582 1583
      g_free (dir);
      dir = parent;
    }
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
}

static char *
find_topdir_for (const char *file)
{
  char *dir;
  dev_t dir_dev;

  dir = get_parent (file, &dir_dev);
  if (dir == NULL)
    return NULL;

  return find_mountpoint_for (dir, dir_dev);
}

static char *
1600 1601
get_unique_filename (const char *basename, 
                     int         id)
1602 1603 1604 1605 1606 1607 1608 1609
{
  const char *dot;
      
  if (id == 1)
    return g_strdup (basename);

  dot = strchr (basename, '.');
  if (dot)
Dan Winship's avatar
Dan Winship committed
1610
    return g_strdup_printf ("%.*s.%d%s", (int)(dot - basename), basename, id, dot);
1611 1612 1613 1614 1615
  else
    return g_strdup_printf ("%s.%d", basename, id);
}

static gboolean
1616 1617
path_has_prefix (const char *path, 
                 const char *prefix)
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
{
  int prefix_len;

  if (prefix == NULL)
    return TRUE;

  prefix_len = strlen (prefix);
  
  if (strncmp (path, prefix, prefix_len) == 0 &&
      (prefix_len == 0 || /* empty prefix always matches */
       prefix[prefix_len - 1] == '/' || /* last char in prefix was a /, so it must be in path too */
       path[prefix_len] == 0 ||
       path[prefix_len] == '/'))
    return TRUE;
  
  return FALSE;
}

static char *
1637 1638
try_make_relative (const char *path, 
                   const char *base)
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 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
{
  char *path2, *base2;
  char *relative;

  path2 = expand_all_symlinks (path);
  base2 = expand_all_symlinks (base);

  relative = NULL;
  if (path_has_prefix (path2, base2))
    {
      relative = path2 + strlen (base2);
      while (*relative == '/')
	relative ++;
      relative = g_strdup (relative);
    }
  g_free (path2);
  g_free (base2);

  if (relative)
    return relative;
  
  /* Failed, use abs path */
  return g_strdup (path);
}

static char *
escape_trash_name (char *name)
{
  GString *str;
  const gchar hex[16] = "0123456789ABCDEF";
  
  str = g_string_new ("");

  while (*name != 0)
    {
      char c;

      c = *name++;

      if (g_ascii_isprint (c))
	g_string_append_c (str, c);
      else
	{
          g_string_append_c (str, '%');
          g_string_append_c (str, hex[((guchar)c) >> 4]);
          g_string_append_c (str, hex[((guchar)c) & 0xf]);
	}
    }

  return g_string_free (str, FALSE);
}

1691 1692 1693
gboolean
_g_local_file_has_trash_dir (const char *dirname, dev_t dir_dev)
{
1694 1695
  static gsize home_dev_set = 0;
  static dev_t home_dev;
1696 1697 1698 1699 1700 1701 1702
  char *topdir, *globaldir, *trashdir, *tmpname;
  uid_t uid;
  char uid_str[32];
  struct stat global_stat, trash_stat;
  gboolean res;
  int statres;
      
1703
  if (g_once_init_enter (&home_dev_set))
1704 1705 1706 1707
    {
      struct stat home_stat;
      
      g_stat (g_get_home_dir (), &home_stat);
1708 1709
      home_dev = home_stat.st_dev;
      g_once_init_leave (&home_dev_set, 1);
1710 1711 1712
    }

  /* Assume we can trash to the home */
1713
  if (dir_dev == home_dev)
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 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 1755 1756 1757 1758 1759 1760 1761 1762 1763
    return TRUE;

  topdir = find_mountpoint_for (dirname, dir_dev);
  if (topdir == NULL)
    return FALSE;

  globaldir = g_build_filename (topdir, ".Trash", NULL); 
  statres = g_lstat (globaldir, &global_stat);
 if (g_lstat (globaldir, &global_stat) == 0 &&
      S_ISDIR (global_stat.st_mode) &&
      (global_stat.st_mode & S_ISVTX) != 0)
    {
      /* got a toplevel sysadmin created dir, assume we
       * can trash to it (we should be able to create a dir)
       * This fails for the FAT case where the ownership of
       * that dir would be wrong though..
       */
      g_free (globaldir);
      g_free (topdir);
      return TRUE;
    }
  g_free (globaldir);

  /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
  uid = geteuid ();
  g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long) uid);
  
  tmpname = g_strdup_printf (".Trash-%s", uid_str);
  trashdir = g_build_filename (topdir, tmpname, NULL);
  g_free (tmpname);

  if (g_lstat (trashdir, &trash_stat) == 0)
    {
      g_free (topdir);
      g_free (trashdir);
      return
	S_ISDIR (trash_stat.st_mode) &&
	trash_stat.st_uid == uid;
    }
  g_free (trashdir);

  /* User specific trash didn't exist, can we create it? */
  res = g_access (topdir, W_OK) == 0;
  
  g_free (topdir);
  
  return res;
}


1764
static gboolean
1765 1766 1767
g_local_file_trash (GFile         *file,
		    GCancellable  *cancellable,
		    GError       **error)
1768 1769
{
  GLocalFile *local = G_LOCAL_FILE (file);
1770
  struct stat file_stat, home_stat;
1771
  const char *homedir;
1772
  char *trashdir, *topdir, *infodir, *filesdir;
1773 1774 1775 1776 1777 1778 1779
  char *basename, *trashname, *trashfile, *infoname, *infofile;
  char *original_name, *original_name_escaped;
  int i;
  char *data;
  gboolean is_homedir_trash;
  char delete_time[32];
  int fd;
1780 1781
  struct stat trash_stat, global_stat;
  char *dirname, *globaldir;
1782 1783 1784
  
  if (g_lstat (local->filename, &file_stat) != 0)
    {
1785 1786
      int errsv = errno;

1787
      g_set_error (error, G_IO_ERROR,
1788
		   g_io_error_from_errno (errsv),
1789
		   _("Error trashing file: %s"),
1790
		   g_strerror (errsv));
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
      return FALSE;
    }
    
  homedir = g_get_home_dir ();
  g_stat (homedir, &home_stat);

  is_homedir_trash = FALSE;
  trashdir = NULL;
  if (file_stat.st_dev == home_stat.st_dev)
    {
      is_homedir_trash = TRUE;
      errno = 0;
      trashdir = g_build_filename (g_get_user_data_dir (), "Trash", NULL);
      if (g_mkdir_with_parents (trashdir, 0700) < 0)
	{
          char *display_name;
1807
          int errsv = errno;
1808 1809 1810

          display_name = g_filename_display_name (trashdir);
          g_set_error (error, G_IO_ERROR,
1811
                       g_io_error_from_errno (errsv),
1812
                       _("Unable to create trash dir %s: %s"),
1813
                       display_name, g_strerror (errsv));
1814 1815 1816 1817 1818 1819 1820 1821
          g_free (display_name);
          g_free (trashdir);
          return FALSE;
	}
      topdir = g_strdup (g_get_user_data_dir ());
    }
  else
    {
1822 1823 1824
      uid_t uid;
      char uid_str[32];

1825 1826 1827 1828 1829 1830
      uid = geteuid ();
      g_snprintf (uid_str, sizeof (uid_str), "%lu", (unsigned long)uid);
      
      topdir = find_topdir_for (local->filename);
      if (topdir == NULL)
	{
1831 1832 1833
	  g_set_error_literal (error, G_IO_ERROR,
                               G_IO_ERROR_NOT_SUPPORTED,
                               _("Unable to find toplevel directory for trash"));
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
	  return FALSE;
	}
      
      /* Try looking for global trash dir $topdir/.Trash/$uid */
      globaldir = g_build_filename (topdir, ".Trash", NULL);
      if (g_lstat (globaldir, &global_stat) == 0 &&
	  S_ISDIR (global_stat.st_mode) &&
	  (global_stat.st_mode & S_ISVTX) != 0)
	{
	  trashdir = g_build_filename (globaldir, uid_str, NULL);

	  if (g_lstat (trashdir, &trash_stat) == 0)
	    {
	      if (!S_ISDIR (trash_stat.st_mode) ||
		  trash_stat.st_uid != uid)
		{
		  /* Not a directory or not owned by user, ignore */
		  g_free (trashdir);
		  trashdir = NULL;
		}
	    }
	  else if (g_mkdir (trashdir, 0700) == -1)
	    {
	      g_free (trashdir);
	      trashdir = NULL;
	    }
	}
      g_free (globaldir);

      if (trashdir == NULL)
	{
1865 1866
	  gboolean tried_create;
	  
1867 1868 1869 1870
	  /* No global trash dir, or it failed the tests, fall back to $topdir/.Trash-$uid */
	  dirname = g_strdup_printf (".Trash-%s", uid_str);
	  trashdir = g_build_filename (topdir, dirname, NULL);
	  g_free (dirname);
1871 1872 1873 1874

	  tried_create = FALSE;

	retry:
1875 1876 1877 1878 1879
	  if (g_lstat (trashdir, &trash_stat) == 0)
	    {
	      if (!S_ISDIR (trash_stat.st_mode) ||
		  trash_stat.st_uid != uid)
		{
1880 1881 1882 1883
		  /* Remove the failed directory */
		  if (tried_create)
		    g_remove (trashdir);
		  
1884 1885 1886 1887 1888
		  /* Not a directory or not owned by user, ignore */
		  g_free (trashdir);
		  trashdir = NULL;
		}
	    }
1889
	  else
1890
	    {
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
	      if (!tried_create &&
		  g_mkdir (trashdir, 0700) != -1)
		{
		  /* Ensure that the created dir has the right uid etc.
		     This might fail on e.g. a FAT dir */
		  tried_create = TRUE;
		  goto retry;
		}
	      else
		{
		  g_free (trashdir);
		  trashdir = NULL;
		}
1904 1905 1906 1907 1908 1909
	    }
	}

      if (trashdir == NULL)
	{
	  g_free (topdir);
1910 1911 1912
	  g_set_error_literal (error, G_IO_ERROR,
                               G_IO_ERROR_NOT_SUPPORTED,
                               _("Unable to find or create trash directory"));
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
	  return FALSE;
	}
    }

  /* Trashdir points to the trash dir with the "info" and "files" subdirectories */

  infodir = g_build_filename (trashdir, "info", NULL);
  filesdir = g_build_filename (trashdir, "files", NULL);
  g_free (trashdir);

  /* Make sure we have the subdirectories */
  if ((g_mkdir (infodir, 0700) == -1 && errno != EEXIST) ||
      (g_mkdir (filesdir, 0700) == -1 && errno != EEXIST))
    {
      g_free (topdir);
      g_free (infodir);
      g_free (filesdir);
1930 1931 1932
      g_set_error_literal (error, G_IO_ERROR,
                           G_IO_ERROR_NOT_SUPPORTED,
                           _("Unable to find or create trash directory"));
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
      return FALSE;
    }  

  basename = g_path_get_basename (local->filename);
  i = 1;
  trashname = NULL;
  infofile = NULL;
  do {
    g_free (trashname);
    g_free (infofile);
    
    trashname = get_unique_filename (basename, i++);
    infoname = g_strconcat (trashname, ".trashinfo", NULL);
    infofile = g_build_filename (infodir, infoname, NULL);
    g_free (infoname);

    fd = open (infofile, O_CREAT | O_EXCL, 0666);
  } while (fd == -1 && errno == EEXIST);

  g_free (basename);
  g_free (infodir);

  if (fd == -1)
    {
1957 1958
      int errsv = errno;

1959 1960 1961 1962 1963 1964
      g_free (filesdir);
      g_free (topdir);
      g_free (trashname);
      g_free (infofile);
      
      g_set_error (error, G_IO_ERROR,
1965
		   g_io_error_from_errno (errsv),
Matthias Clasen's avatar
Matthias Clasen committed
1966
		   _("Unable to create trashing info file: %s"),
1967
		   g_strerror (errsv));
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
      return FALSE;
    }

  close (fd);

  /* TODO: Maybe we should verify that you can delete the file from the trash
     before moving it? OTOH, that is hard, as it needs a recursive scan */

  trashfile = g_build_filename (filesdir, trashname, NULL);

  g_free (filesdir);

  if (g_rename (local->filename, trashfile) == -1)
    {
1982