glocalfile.c 55.5 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 81 82
#include "glocalfile.h"
#include "glocalfileinfo.h"
#include "glocalfileenumerator.h"
#include "glocalfileinputstream.h"
#include "glocalfileoutputstream.h"
#include "glocaldirectorymonitor.h"
#include "glocalfilemonitor.h"
83
#include "gmountprivate.h"
84 85
#include "gunixmounts.h"
#include "gioerror.h"
86 87 88
#include <glib/gstdio.h>
#include "glibintl.h"

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

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

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

107 108
#include "gioalias.h"

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

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

struct _GLocalFile
{
  GObject parent_instance;

  char *filename;
};

Alexander Larsson's avatar
Alexander Larsson committed
121
#define g_local_file_get_type _g_local_file_get_type
122 123 124 125
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
126
static char *find_mountpoint_for (const char *file, dev_t dev);
127 128 129 130 131 132 133 134 135

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

  local = G_LOCAL_FILE (object);

  g_free (local->filename);
136 137

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

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,
157
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
158
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
159 160 161 162 163
  
#ifdef HAVE_CHOWN
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_UNIX_UID,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
164
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
165 166 167
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_UNIX_GID,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
168
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
169 170 171 172
#endif
  
#ifdef HAVE_SYMLINK
  g_file_attribute_info_list_add (list,
173
				  G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
174 175 176 177 178 179 180 181
				  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,
182
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
183
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
184 185 186
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
187
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
188
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
189 190 191
  /* When copying, the target file is accessed. Replicating
   * the source access time does not make sense in this case.
   */
192 193 194
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_ACCESS,
				  G_FILE_ATTRIBUTE_TYPE_UINT64,
195
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
196 197 198
  g_file_attribute_info_list_add (list,
				  G_FILE_ATTRIBUTE_TIME_ACCESS_USEC,
				  G_FILE_ATTRIBUTE_TYPE_UINT32,
199
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
200 201 202 203 204 205 206 207 208 209 210 211
#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,
212 213
				  G_FILE_ATTRIBUTE_INFO_COPY_WITH_FILE |
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
214
  g_file_attribute_info_list_add (list,
215
				  "xattr-sys",
216
				  G_FILE_ATTRIBUTE_TYPE_STRING,
217
				  G_FILE_ATTRIBUTE_INFO_COPY_WHEN_MOVED);
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
#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;
234
  int i;
235 236 237 238 239 240 241 242 243 244 245 246
  
  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);

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
  /* 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);
    }
  
265 266 267 268 269 270 271 272 273 274 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
  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;
}

/**
Alexander Larsson's avatar
Alexander Larsson committed
315
 * _g_local_file_new:
316 317 318 319 320
 * @filename: filename of the file to create.
 * 
 * Returns: new local #GFile.
 **/
GFile *
Alexander Larsson's avatar
Alexander Larsson committed
321
_g_local_file_new (const char *filename)
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
{
  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
Matthias Clasen's avatar
Matthias Clasen committed
338
g_local_file_has_uri_scheme (GFile      *file,
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
			     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,
Matthias Clasen's avatar
Matthias Clasen committed
384
			   gboolean    is_valid_utf8)
385 386
{
  char c;
387

388 389 390 391 392 393
  if (!is_valid_utf8 &&
      !g_utf8_validate (string, -1, NULL))
    return FALSE;

  while ((c = *string++) != 0)
    {
Matthias Clasen's avatar
Matthias Clasen committed
394
      if (g_ascii_iscntrl (c))
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
	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;
411 412
  char *escaped_path;
  
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  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;
	    }
439 440

	  g_free (roundtripped_filename);
441 442 443 444 445 446 447 448 449 450 451 452 453
	}
    }

  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
    {
454 455 456 457 458 459 460 461 462 463
      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);

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
      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);
Alexander Larsson's avatar
Alexander Larsson committed
485
  parent = _g_local_file_new (dirname);
486 487 488 489 490 491 492 493 494
  g_free (dirname);
  return parent;
}

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

Alexander Larsson's avatar
Alexander Larsson committed
495
  return _g_local_file_new (local->filename);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
}

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 *
Matthias Clasen's avatar
Matthias Clasen committed
517 518
match_prefix (const char *path, 
              const char *prefix)
519 520 521 522 523 524
{
  int prefix_len;

  prefix_len = strlen (prefix);
  if (strncmp (path, prefix, prefix_len) != 0)
    return NULL;
525 526 527 528 529 530 531
  
  /* 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--;
  
532 533 534 535
  return path + prefix_len;
}

static gboolean
536 537
g_local_file_prefix_matches (GFile *parent,
			     GFile *descendant)
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
{
  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 *
Matthias Clasen's avatar
Matthias Clasen committed
565
g_local_file_resolve_relative_path (GFile      *file,
566 567 568 569 570 571 572
				    const char *relative_path)
{
  GLocalFile *local = G_LOCAL_FILE (file);
  char *filename;
  GFile *child;

  if (g_path_is_absolute (relative_path))
Alexander Larsson's avatar
Alexander Larsson committed
573
    return _g_local_file_new (relative_path);
574 575
  
  filename = g_build_filename (local->filename, relative_path, NULL);
Alexander Larsson's avatar
Alexander Larsson committed
576
  child = _g_local_file_new (filename);
577 578 579 580 581 582
  g_free (filename);
  
  return child;
}

static GFileEnumerator *
Matthias Clasen's avatar
Matthias Clasen committed
583 584 585 586 587
g_local_file_enumerate_children (GFile                *file,
				 const char           *attributes,
				 GFileQueryInfoFlags   flags,
				 GCancellable         *cancellable,
				 GError              **error)
588 589
{
  GLocalFile *local = G_LOCAL_FILE (file);
590
  return _g_local_file_enumerator_new (local,
Alexander Larsson's avatar
Alexander Larsson committed
591 592
				       attributes, flags,
				       cancellable, error);
593 594 595 596 597 598 599
}

static GFile *
g_local_file_get_child_for_display_name (GFile        *file,
					 const char   *display_name,
					 GError      **error)
{
600
  GFile *new_file;
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
  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)
{
622
  g_print ("get fstype for %ld\n", f_type);
623 624

  /* filesystem ids taken from linux manpage */
Matthias Clasen's avatar
Matthias Clasen committed
625 626 627 628
  switch (f_type) 
    {
    case 0xadf5:
      return "adfs";
629 630 631 632
    case 0x5346414f:
      return "afs";
    case 0x0187:
      return "autofs";
Matthias Clasen's avatar
Matthias Clasen committed
633 634 635 636 637 638
    case 0xADFF:
      return "affs";
    case 0x42465331:
      return "befs";
    case 0x1BADFACE:
      return "bfs";
639 640
    case 0x9123683E:
      return "btrfs";
Matthias Clasen's avatar
Matthias Clasen committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
    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:
      return "ext3";
    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";
699 700
    case 0x73717368:
      return "squashfs";
Matthias Clasen's avatar
Matthias Clasen committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    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;
    }
724 725 726
}
#endif

727 728
#ifndef G_OS_WIN32

729 730
G_LOCK_DEFINE_STATIC(mount_info_hash);
static GHashTable *mount_info_hash = NULL;
731
static guint64 mount_info_hash_cache_time = 0;
732 733 734 735 736 737 738

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

static gboolean
device_equal (gconstpointer v1,
Matthias Clasen's avatar
Matthias Clasen committed
739
              gconstpointer v2)
740
{
Matthias Clasen's avatar
Matthias Clasen committed
741
  return *(dev_t *)v1 == *(dev_t *)v2;
742 743 744
}

static guint
Matthias Clasen's avatar
Matthias Clasen committed
745
device_hash (gconstpointer v)
746 747 748 749 750
{
  return (guint) *(dev_t *)v;
}

static void
Matthias Clasen's avatar
Matthias Clasen committed
751 752
get_mount_info (GFileInfo             *fs_info,
		const char            *path,
753 754 755 756 757 758 759 760
		GFileAttributeMatcher *matcher)
{
  struct stat buf;
  gboolean got_info;
  gpointer info_as_ptr;
  guint mount_info;
  char *mountpoint;
  dev_t *dev;
761
  GUnixMountEntry *mount;
762 763
  guint64 cache_time;

764
  if (g_lstat (path, &buf) != 0)
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
    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)
792
	mountpoint = g_strdup ("/");
793

794
      mount = g_unix_mount_at (mountpoint, &cache_time);
795 796 797 798 799 800 801 802
      if (mount)
	{
	  if (g_unix_mount_is_readonly (mount))
	    mount_info |= MOUNT_INFO_READONLY;
	  
	  g_unix_mount_free (mount);
	}

803 804
      g_free (mountpoint);

805 806 807 808 809 810 811 812 813 814
      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)
815
    g_file_info_set_attribute_boolean (fs_info, G_FILE_ATTRIBUTE_FILESYSTEM_READONLY, TRUE);
816 817
}

818 819
#endif

820 821 822 823 824 825 826 827 828
#ifdef G_OS_WIN32

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

  if (result == -1)
    {
829
#ifndef _MSC_VER    
830 831 832 833 834 835 836 837 838 839 840 841 842 843
      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;
844 845 846
#else
      result = ((DWORD)(LOBYTE (LOWORD (GetVersion ())))) >= 5;  
#endif
847 848 849 850 851 852 853 854 855 856 857 858
    }

  return result;
}

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

859 860
  wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
  result = g_new (wchar_t, MAX_PATH);
861

862
  if (!GetVolumePathNameW (wpath, result, MAX_PATH))
863 864 865 866 867 868 869 870 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
    {
      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 */

929
static GFileInfo *
Matthias Clasen's avatar
Matthias Clasen committed
930 931 932 933
g_local_file_query_filesystem_info (GFile         *file,
				    const char    *attributes,
				    GCancellable  *cancellable,
				    GError       **error)
934 935 936
{
  GLocalFile *local = G_LOCAL_FILE (file);
  GFileInfo *info;
937
  int statfs_result = 0;
938
  gboolean no_size;
939
#ifndef G_OS_WIN32
940
  guint64 block_size;
941
  const char *fstype;
942 943 944 945
#ifdef USE_STATFS
  struct statfs statfs_buffer;
#elif defined(USE_STATVFS)
  struct statvfs statfs_buffer;
946
#endif
947 948 949
#endif
  GFileAttributeMatcher *attribute_matcher;
	
950
  g_print ("g_local_file_query_filesystem_info\n");
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
  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;
  
#if defined(__linux__)
  /* ncpfs does not know the amount of available and free space *
   * assuming ncpfs is linux specific, if you are on a non-linux platform
   * where ncpfs is available, please file a bug about it on bugzilla.gnome.org
   */
  if (statfs_buffer.f_bavail == 0 && statfs_buffer.f_bfree == 0 &&
      /* linux/ncp_fs.h: NCP_SUPER_MAGIC == 0x564c */
      statfs_buffer.f_type == 0x564c)
    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)
    {
981 982
      int errsv = errno;

983
      g_set_error (error, G_IO_ERROR,
984
		   g_io_error_from_errno (errsv),
985
		   _("Error getting filesystem info: %s"),
986
		   g_strerror (errsv));
987 988 989 990 991 992 993
      return NULL;
    }

  info = g_file_info_new ();

  attribute_matcher = g_file_attribute_matcher_new (attributes);
  
994 995
  if (!no_size &&
      g_file_attribute_matcher_matches (attribute_matcher,
996
					G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
997 998 999 1000 1001 1002 1003 1004
    {
#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))
1005
        g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, (guint64)li.QuadPart);
1006 1007
      g_free (wdirname);
#else
1008
      g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_FREE, block_size * statfs_buffer.f_bavail);
1009 1010
#endif
    }
1011 1012
  if (!no_size &&
      g_file_attribute_matcher_matches (attribute_matcher,
1013
					G_FILE_ATTRIBUTE_FILESYSTEM_SIZE))
1014 1015 1016 1017 1018 1019 1020 1021
    {
#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))
1022
        g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE,  (guint64)li.QuadPart);
1023 1024
      g_free (wdirname);
#else
1025
      g_file_info_set_attribute_uint64 (info, G_FILE_ATTRIBUTE_FILESYSTEM_SIZE, block_size * statfs_buffer.f_blocks);
1026 1027
#endif
    }
1028
#ifdef USE_STATFS
1029
#if defined(HAVE_STRUCT_STATFS_F_FSTYPENAME)
1030
  fstype = g_strdup(statfs_buffer.f_fstypename);
1031
  g_print ("using f_fstypename %s\n", fstype);
1032
#else
1033
  fstype = get_fs_type (statfs_buffer.f_type);
1034
  g_print ("using f_type %s\n", fstype);
1035
#endif
1036 1037 1038 1039 1040 1041

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

#ifndef G_OS_WIN32
1042 1043
  if (fstype &&
      g_file_attribute_matcher_matches (attribute_matcher,
1044 1045
					G_FILE_ATTRIBUTE_FILESYSTEM_TYPE))
    g_file_info_set_attribute_string (info, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE, fstype);
1046 1047 1048
#endif  

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

1063 1064 1065 1066
static GMount *
g_local_file_find_enclosing_mount (GFile         *file,
                                   GCancellable  *cancellable,
                                   GError       **error)
1067 1068 1069 1070
{
  GLocalFile *local = G_LOCAL_FILE (file);
  struct stat buf;
  char *mountpoint;
1071
  GMount *mount;
1072

1073
  if (g_lstat (local->filename, &buf) != 0)
1074
    {
1075
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1076 1077 1078 1079
		      /* 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"));
1080 1081 1082 1083 1084 1085
      return NULL;
    }

  mountpoint = find_mountpoint_for (local->filename, buf.st_dev);
  if (mountpoint == NULL)
    {
1086
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1087 1088 1089 1090
		      /* 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"));
1091 1092 1093
      return NULL;
    }

1094
  mount = _g_mount_get_for_mount_path (mountpoint, cancellable);
1095
  g_free (mountpoint);
1096 1097
  if (mount)
    return mount;
1098

1099
  g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
1100 1101 1102 1103
		  /* 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"));
1104 1105 1106 1107
  return NULL;
}

static GFile *
Matthias Clasen's avatar
Matthias Clasen committed
1108 1109 1110 1111
g_local_file_set_display_name (GFile         *file,
			       const char    *display_name,
			       GCancellable  *cancellable,
			       GError       **error)
1112 1113 1114 1115 1116 1117 1118 1119 1120
{
  GLocalFile *local, *new_local;
  GFile *new_file, *parent;
  struct stat statbuf;
  int errsv;

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

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
  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
1149
    {
1150 1151 1152
      g_set_error_literal (error, G_IO_ERROR,
                           G_IO_ERROR_EXISTS,
                           _("Can't rename file, filename already exist"));
1153 1154 1155
      return NULL;
    }

1156
  if (g_rename (local->filename, new_local->filename) == -1)
1157 1158 1159 1160 1161 1162
    {
      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 */
1163 1164 1165
	g_set_error_literal (error, G_IO_ERROR,
                             G_IO_ERROR_INVALID_FILENAME,
                             _("Invalid filename"));
1166 1167 1168 1169 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
      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 *
Matthias Clasen's avatar
Matthias Clasen committed
1211 1212 1213
g_local_file_query_settable_attributes (GFile         *file,
					GCancellable  *cancellable,
					GError       **error)
1214 1215 1216 1217 1218
{
  return g_file_attribute_info_list_ref (local_writable_attributes);
}

static GFileAttributeInfoList *
Matthias Clasen's avatar
Matthias Clasen committed
1219 1220 1221
g_local_file_query_writable_namespaces (GFile         *file,
					GCancellable  *cancellable,
					GError       **error)
1222 1223 1224 1225 1226
{
  return g_file_attribute_info_list_ref (local_writable_namespaces);
}

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

  return _g_local_file_info_set_attribute (local->filename,
					   attribute,
1239 1240
					   type,
					   value_p,
1241 1242 1243 1244 1245 1246
					   flags,
					   cancellable,
					   error);
}

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

  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 *
Matthias Clasen's avatar
Matthias Clasen committed
1273 1274 1275
g_local_file_read (GFile         *file,
		   GCancellable  *cancellable,
		   GError       **error)
1276 1277 1278 1279 1280
{
  GLocalFile *local = G_LOCAL_FILE (file);
  int fd;
  struct stat buf;
  
1281
  fd = g_open (local->filename, O_RDONLY|O_BINARY, 0);
1282 1283
  if (fd == -1)
    {
1284 1285
      int errsv = errno;

1286
      g_set_error (error, G_IO_ERROR,
1287
		   g_io_error_from_errno (errsv),
1288
		   _("Error opening file: %s"),
1289
		   g_strerror (errsv));
1290 1291 1292 1293 1294 1295
      return NULL;
    }

  if (fstat(fd, &buf) == 0 && S_ISDIR (buf.st_mode))
    {
      close (fd);
1296 1297 1298
      g_set_error_literal (error, G_IO_ERROR,
                           G_IO_ERROR_IS_DIRECTORY,
                           _("Can't open directory"));
1299 1300 1301
      return NULL;
    }
  
Alexander Larsson's avatar
Alexander Larsson committed
1302
  return _g_local_file_input_stream_new (fd);
1303 1304 1305
}

static GFileOutputStream *
Matthias Clasen's avatar
Matthias Clasen committed
1306 1307 1308 1309
g_local_file_append_to (GFile             *file,
			GFileCreateFlags   flags,
			GCancellable      *cancellable,
			GError           **error)
1310
{
Alexander Larsson's avatar
Alexander Larsson committed
1311 1312
  return _g_local_file_output_stream_append (G_LOCAL_FILE (file)->filename,
					     flags, cancellable, error);
1313 1314 1315
}

static GFileOutputStream *
Matthias Clasen's avatar
Matthias Clasen committed
1316 1317 1318 1319
g_local_file_create (GFile             *file,
		     GFileCreateFlags   flags,
		     GCancellable      *cancellable,
		     GError           **error)
1320
{
Alexander Larsson's avatar
Alexander Larsson committed
1321 1322
  return _g_local_file_output_stream_create (G_LOCAL_FILE (file)->filename,
					     flags, cancellable, error);
1323 1324 1325
}

static GFileOutputStream *
Matthias Clasen's avatar
Matthias Clasen committed
1326 1327 1328 1329 1330 1331
g_local_file_replace (GFile             *file,
		      const char        *etag,
		      gboolean           make_backup,
		      GFileCreateFlags   flags,
		      GCancellable      *cancellable,
		      GError           **error)
1332
{
Alexander Larsson's avatar
Alexander Larsson committed
1333 1334 1335
  return _g_local_file_output_stream_replace (G_LOCAL_FILE (file)->filename,
					      etag, make_backup, flags,
					      cancellable, error);
1336 1337 1338 1339
}


static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1340 1341 1342
g_local_file_delete (GFile         *file,
		     GCancellable  *cancellable,
		     GError       **error)
1343 1344