1 /**
   2  * volume.c - NTFS volume handling code. Part of the Linux-NTFS project.
   3  *
   4  * Copyright (c) 2000-2006 Anton Altaparmakov
   5  * Copyright (c) 2002-2006 Szabolcs Szakacsits
   6  * Copyright (c) 2004-2005 Richard Russon
   7  * Copyright (c) 2005-2007 Yura Pakhuchiy
   8  *
   9  * This program/include file is free software; you can redistribute it and/or
  10  * modify it under the terms of the GNU General Public License as published
  11  * by the Free Software Foundation; either version 2 of the License, or
  12  * (at your option) any later version.
  13  *
  14  * This program/include file is distributed in the hope that it will be
  15  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  16  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17  * GNU General Public License for more details.
  18  *
  19  * You should have received a copy of the GNU General Public License
  20  * along with this program (in the main directory of the Linux-NTFS
  21  * distribution in the file COPYING); if not, write to the Free Software
  22  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  23  */
  24 
  25 #ifdef HAVE_CONFIG_H
  26 #include "config.h"
  27 #endif
  28 
  29 #ifdef HAVE_STDLIB_H
  30 #include <stdlib.h>
  31 #endif
  32 #ifdef HAVE_STDIO_H
  33 #include <stdio.h>
  34 #endif
  35 #ifdef HAVE_STRING_H
  36 #include <string.h>
  37 #endif
  38 #ifdef HAVE_FCNTL_H
  39 #include <fcntl.h>
  40 #endif
  41 #ifdef HAVE_UNISTD_H
  42 #include <unistd.h>
  43 #endif
  44 #ifdef HAVE_ERRNO_H
  45 #include <errno.h>
  46 #endif
  47 #ifdef HAVE_SYS_STAT_H
  48 #include <sys/stat.h>
  49 #endif
  50 #ifdef HAVE_LIMITS_H
  51 #include <limits.h>
  52 #endif
  53 
  54 #include "compat.h"
  55 #include "volume.h"
  56 #include "attrib.h"
  57 #include "mft.h"
  58 #include "bootsect.h"
  59 #include "device.h"
  60 #include "debug.h"
  61 #include "inode.h"
  62 #include "runlist.h"
  63 #include "logfile.h"
  64 #include "dir.h"
  65 #include "logging.h"
  66 
  67 #ifndef PATH_MAX
  68 #define PATH_MAX 4096
  69 #endif
  70 
  71 /**
  72  * ntfs_volume_alloc - Create an NTFS volume object and initialise it
  73  *
  74  * Description...
  75  *
  76  * Returns:
  77  */
  78 ntfs_volume *ntfs_volume_alloc(void)
  79 {
  80         ntfs_volume *vol;
  81         int i;
  82 
  83         vol = calloc(1, sizeof(ntfs_volume));
  84         if (vol) {
  85                 for (i = 0; i < NTFS_INODE_CACHE_SIZE; i++)
  86                         INIT_LIST_HEAD(&vol->inode_cache[i]);
  87         }
  88         return vol;
  89 }
  90 
  91 /**
  92  * __ntfs_volume_release - Destroy an NTFS volume object
  93  * @v:
  94  *
  95  * Description...
  96  *
  97  * Returns:
  98  */
  99 static void __ntfs_volume_release(ntfs_volume *v)
 100 {
 101         struct list_head *pos, *tmp;
 102         int i;
 103 
 104         /* Sync and print error about not detached inodes. */
 105         for (i = 0; i < NTFS_INODE_CACHE_SIZE; i++)
 106                 list_for_each_safe(pos, tmp, &v->inode_cache[i]) {
 107                         ntfs_inode *ni =
 108                                         list_entry(pos, ntfs_inode, list_entry);
 109 
 110                         switch (ni->mft_no) {
 111                                 case FILE_Volume:
 112                                 case FILE_Bitmap:
 113                                 case FILE_MFT:
 114                                 case FILE_MFTMirr:
 115                                         if (ni->nr_references == 1)
 116                                                 continue;
 117                                         break;
 118                         }
 119 
 120                         ntfs_log_error("%s(): Inode %llu still have %d "
 121                                         "references.\n", "__ntfs_volume_release",
 122                                         ni->mft_no, ni->nr_references);
 123                         ntfs_inode_sync(ni);
 124                 }
 125         /*
 126          * Clear the dirty bit if it was not set before we mounted and this is
 127          * not a forensic mount.
 128          */
 129         if (!NVolReadOnly(v) && !NVolWasDirty(v) && !NVolForensicMount(v)) {
 130                 v->flags &= ~VOLUME_IS_DIRTY;
 131                 (void)ntfs_volume_write_flags(v, v->flags);
 132         }
 133         if (v->lcnbmp_ni && NInoDirty(v->lcnbmp_ni))
 134                 ntfs_inode_sync(v->lcnbmp_ni);
 135         if (v->vol_ni)
 136                 ntfs_inode_close(v->vol_ni);
 137         if (v->lcnbmp_na)
 138                 ntfs_attr_close(v->lcnbmp_na);
 139         if (v->lcnbmp_ni)
 140                 ntfs_inode_close(v->lcnbmp_ni);
 141         if (v->mft_ni && NInoDirty(v->mft_ni))
 142                 ntfs_inode_sync(v->mft_ni);
 143         if (v->mftbmp_na)
 144                 ntfs_attr_close(v->mftbmp_na);
 145         if (v->mft_na)
 146                 ntfs_attr_close(v->mft_na);
 147         if (v->mft_ni)
 148                 ntfs_inode_close(v->mft_ni);
 149         if (v->mftmirr_ni && NInoDirty(v->mftmirr_ni))
 150                 ntfs_inode_sync(v->mftmirr_ni);
 151         if (v->mftmirr_na)
 152                 ntfs_attr_close(v->mftmirr_na);
 153         if (v->mftmirr_ni)
 154                 ntfs_inode_close(v->mftmirr_ni);
 155         if (v->u.dev) {
 156                 struct ntfs_device *dev = v->u.dev;
 157 
 158                 if (NDevDirty(dev))
 159                         dev->d_ops->sync(dev);
 160                 if (dev->d_ops->close(dev))
 161                         ntfs_log_perror("Failed to close the device");
 162         }
 163         free(v->vol_name);
 164         free(v->upcase);
 165         free(v->attrdef);
 166         free(v);
 167 }
 168 
 169 /**
 170  * ntfs_mft_load - load the $MFT and setup the ntfs volume with it
 171  * @vol:        ntfs volume whose $MFT to load
 172  *
 173  * Load $MFT from @vol and setup @vol with it. After calling this function the
 174  * volume @vol is ready for use by all read access functions provided by the
 175  * ntfs library.
 176  *
 177  * Return 0 on success and -1 on error with errno set to the error code.
 178  */
 179 static int ntfs_mft_load(ntfs_volume *vol)
 180 {
 181         VCN next_vcn, last_vcn, highest_vcn;
 182         s64 l;
 183         MFT_RECORD *mb = NULL;
 184         ntfs_attr_search_ctx *ctx = NULL;
 185         ATTR_RECORD *a;
 186         STANDARD_INFORMATION *std_info;
 187         int eo;
 188 
 189         /* Manually setup an ntfs_inode. */
 190         vol->mft_ni = ntfs_inode_allocate(vol);
 191         mb = (MFT_RECORD*)ntfs_malloc(vol->mft_record_size);
 192         if (!vol->mft_ni || !mb) {
 193                 ntfs_log_perror("Error allocating memory for $MFT");
 194                 goto error_exit;
 195         }
 196         vol->mft_ni->mft_no = 0;
 197         vol->mft_ni->mrec = mb;
 198         __ntfs_inode_add_to_cache(vol->mft_ni);
 199         /* Can't use any of the higher level functions yet! */
 200         l = ntfs_mst_pread(vol->u.dev, vol->mft_lcn << vol->cluster_size_bits, 1,
 201                         vol->mft_record_size, mb);
 202         if (l != 1) {
 203                 if (l != -1)
 204                         errno = EIO;
 205                 ntfs_log_perror("Error reading $MFT");
 206                 goto error_exit;
 207         }
 208         if (ntfs_is_baad_record(mb->magic)) {
 209                 ntfs_log_error("Incomplete multi sector transfer detected in "
 210                                 "$MFT.\n");
 211                 goto io_error_exit;
 212         }
 213         if (!ntfs_is_mft_record(mb->magic)) {
 214                 ntfs_log_error("$MFT has invalid magic.\n");
 215                 goto io_error_exit;
 216         }
 217         ctx = ntfs_attr_get_search_ctx(vol->mft_ni, NULL);
 218         if (!ctx) {
 219                 ntfs_log_perror("Failed to allocate attribute search context");
 220                 goto error_exit;
 221         }
 222         if (p2n(ctx->attr) < p2n(mb) ||
 223                         (char*)ctx->attr > (char*)mb + vol->mft_record_size) {
 224                 ntfs_log_error("$MFT is corrupt.\n");
 225                 goto io_error_exit;
 226         }
 227         /* Find the $ATTRIBUTE_LIST attribute in $MFT if present. */
 228         if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, AT_UNNAMED, 0, 0, 0, NULL, 0,
 229                         ctx)) {
 230                 if (errno != ENOENT) {
 231                         ntfs_log_error("$MFT has corrupt attribute list.\n");
 232                         goto io_error_exit;
 233                 }
 234                 goto mft_has_no_attr_list;
 235         }
 236         NInoSetAttrList(vol->mft_ni);
 237         l = ntfs_get_attribute_value_length(ctx->attr);
 238         if (l <= 0 || l > 0x40000) {
 239                 ntfs_log_error("$MFT/$ATTRIBUTE_LIST has invalid length.\n");
 240                 goto io_error_exit;
 241         }
 242         vol->mft_ni->attr_list_size = l;
 243         vol->mft_ni->attr_list = ntfs_malloc(l);
 244         if (!vol->mft_ni->attr_list)
 245                 goto error_exit;
 246 
 247         l = ntfs_get_attribute_value(vol, ctx->attr, vol->mft_ni->attr_list);
 248         if (!l) {
 249                 ntfs_log_error("Failed to get value of "
 250                                 "$MFT/$ATTRIBUTE_LIST.\n");
 251                 goto io_error_exit;
 252         }
 253         if (l != vol->mft_ni->attr_list_size) {
 254                 ntfs_log_error("Got unexpected amount of data when "
 255                                 "reading $MFT/$ATTRIBUTE_LIST.\n");
 256                 goto io_error_exit;
 257         }
 258 mft_has_no_attr_list:
 259         /* Receive attributes from STANDARD_INFORMATION. */
 260         std_info = ntfs_attr_readall(vol->mft_ni, AT_STANDARD_INFORMATION,
 261                                      AT_UNNAMED, 0, NULL);
 262         vol->mft_ni->flags = std_info->file_attributes;
 263         free(std_info);
 264 
 265         /* We now have a fully setup ntfs inode for $MFT in vol->mft_ni. */
 266 
 267         /* Get an ntfs attribute for $MFT/$DATA and set it up, too. */
 268         vol->mft_na = ntfs_attr_open(vol->mft_ni, AT_DATA, AT_UNNAMED, 0);
 269         if (!vol->mft_na) {
 270                 ntfs_log_perror("Failed to open ntfs attribute");
 271                 goto error_exit;
 272         }
 273         /* Read all extents from the $DATA attribute in $MFT. */
 274         ntfs_attr_reinit_search_ctx(ctx);
 275         last_vcn = vol->mft_na->allocated_size >> vol->cluster_size_bits;
 276         highest_vcn = next_vcn = 0;
 277         a = NULL;
 278         while (!ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, next_vcn, NULL, 0,
 279                         ctx)) {
 280                 runlist_element *nrl;
 281 
 282                 a = ctx->attr;
 283                 /* $MFT must be non-resident. */
 284                 if (!a->non_resident) {
 285                         ntfs_log_error("$MFT must be non-resident but a "
 286                                         "resident extent was found. $MFT is "
 287                                         "corrupt. Run chkdsk.\n");
 288                         goto io_error_exit;
 289                 }
 290                 /* $MFT must be uncompressed and unencrypted. */
 291                 if (a->flags & ATTR_COMPRESSION_MASK ||
 292                                 a->flags & ATTR_IS_ENCRYPTED) {
 293                         ntfs_log_error("$MFT must be uncompressed and "
 294                                         "unencrypted but a compressed/encrypted"
 295                                         " extent was found. $MFT is corrupt. "
 296                                         "Run chkdsk.\n");
 297                         goto io_error_exit;
 298                 }
 299                 /*
 300                  * Decompress the mapping pairs array of this extent and merge
 301                  * the result into the existing runlist. No need for locking
 302                  * as we have exclusive access to the inode at this time and we
 303                  * are a mount in progress task, too.
 304                  */
 305                 nrl = ntfs_mapping_pairs_decompress(vol, a, vol->mft_na->rl);
 306                 if (!nrl) {
 307                         ntfs_log_perror("ntfs_mapping_pairs_decompress() "
 308                                         "failed");
 309                         goto error_exit;
 310                 }
 311                 vol->mft_na->rl = nrl;
 312 
 313                 /* Get the lowest vcn for the next extent. */
 314                 highest_vcn = sle64_to_cpu(a->u.nonres.highest_vcn);
 315                 next_vcn = highest_vcn + 1;
 316 
 317                 /* Only one extent or error, which we catch below. */
 318                 if (next_vcn <= 0)
 319                         break;
 320 
 321                 /* Avoid endless loops due to corruption. */
 322                 if (next_vcn < sle64_to_cpu(a->u.nonres.lowest_vcn)) {
 323                         ntfs_log_error("$MFT has corrupt attribute list "
 324                                         "attribute. Run chkdsk.\n");
 325                         goto io_error_exit;
 326                 }
 327         }
 328         if (!a) {
 329                 ntfs_log_error("$MFT/$DATA attribute not found. "
 330                                 "$MFT is corrupt. Run chkdsk.\n");
 331                 goto io_error_exit;
 332         }
 333         if (highest_vcn && highest_vcn != last_vcn - 1) {
 334                 ntfs_log_error("Failed to load the complete runlist for "
 335                                 "$MFT/$DATA. Bug or corrupt $MFT. "
 336                                 "Run chkdsk.\n highest_vcn = 0x%llx, "
 337                                 "last_vcn - 1 = 0x%llx\n", (long long)
 338                                 highest_vcn, (long long)last_vcn - 1);
 339                 goto io_error_exit;
 340         }
 341         /* Done with the $Mft mft record. */
 342         ntfs_attr_put_search_ctx(ctx);
 343         ctx = NULL;
 344         /*
 345          * The volume is now setup so we can use all read access functions.
 346          */
 347         vol->mftbmp_na = ntfs_attr_open(vol->mft_ni, AT_BITMAP, AT_UNNAMED, 0);
 348         if (!vol->mftbmp_na) {
 349                 ntfs_log_perror("Failed to open $MFT/$BITMAP");
 350                 goto error_exit;
 351         }
 352         return 0;
 353 io_error_exit:
 354         errno = EIO;
 355 error_exit:
 356         eo = errno;
 357         if (ctx)
 358                 ntfs_attr_put_search_ctx(ctx);
 359         if (vol->mft_na) {
 360                 ntfs_attr_close(vol->mft_na);
 361                 vol->mft_na = NULL;
 362         }
 363         if (vol->mft_ni) {
 364                 ntfs_inode_close(vol->mft_ni);
 365                 vol->mft_ni = NULL;
 366         }
 367         ntfs_log_error("%s(): Failed.\n", "ntfs_mft_load");
 368         errno = eo;
 369         return -1;
 370 }
 371 
 372 /**
 373  * ntfs_mftmirr_load - load the $MFTMirr and setup the ntfs volume with it
 374  * @vol:        ntfs volume whose $MFTMirr to load
 375  *
 376  * Load $MFTMirr from @vol and setup @vol with it. After calling this function
 377  * the volume @vol is ready for use by all write access functions provided by
 378  * the ntfs library (assuming ntfs_mft_load() has been called successfully
 379  * beforehand).
 380  *
 381  * Return 0 on success and -1 on error with errno set to the error code.
 382  */
 383 static int ntfs_mftmirr_load(ntfs_volume *vol)
 384 {
 385         int err;
 386 
 387         vol->mftmirr_ni = ntfs_inode_open(vol, FILE_MFTMirr);
 388         if (!vol->mftmirr_ni) {
 389                 ntfs_log_perror("Failed to open inode $MFTMirr");
 390                 return -1;
 391         }
 392         /* Get an ntfs attribute for $MFTMirr/$DATA, too. */
 393         vol->mftmirr_na = ntfs_attr_open(vol->mftmirr_ni, AT_DATA,
 394                         AT_UNNAMED, 0);
 395         if (!vol->mftmirr_na) {
 396                 ntfs_log_perror("Failed to open $MFTMirr/$DATA");
 397                 goto error_exit;
 398         }
 399         if (ntfs_attr_map_runlist(vol->mftmirr_na, 0) < 0) {
 400                 ntfs_log_perror("Failed to map runlist of $MFTMirr/$DATA");
 401                 goto error_exit;
 402         }
 403         /* Check $MFTMirr runlist. */
 404         if (vol->mftmirr_na->rl[0].lcn != vol->mftmirr_lcn ||
 405                         vol->mftmirr_na->rl[0].length < (vol->mftmirr_size *
 406                         vol->mft_record_size + vol->cluster_size - 1) /
 407                         vol->cluster_size) {
 408                 ntfs_log_error("$MFTMirr location mismatch or first 4 records "
 409                                 "are fragmented. Run chkdsk.\n");
 410                 errno = EIO;
 411                 goto error_exit;
 412 
 413         }
 414         return 0;
 415 error_exit:
 416         err = errno;
 417         if (vol->mftmirr_na) {
 418                 ntfs_attr_close(vol->mftmirr_na);
 419                 vol->mftmirr_na = NULL;
 420         }
 421         ntfs_inode_close(vol->mftmirr_ni);
 422         vol->mftmirr_ni = NULL;
 423         errno = err;
 424         return -1;
 425 }
 426 
 427 /**
 428  * ntfs_volume_startup - allocate and setup an ntfs volume
 429  * @dev:        device to open
 430  * @flags:      optional mount flags
 431  *
 432  * Load, verify, and parse bootsector; load and setup $MFT and $MFTMirr. After
 433  * calling this function, the volume is setup sufficiently to call all read
 434  * and write access functions provided by the library.
 435  *
 436  * Return the allocated volume structure on success and NULL on error with
 437  * errno set to the error code.
 438  */
 439 ntfs_volume *ntfs_volume_startup(struct ntfs_device *dev,
 440                 ntfs_mount_flags flags)
 441 {
 442         LCN mft_zone_size, mft_lcn;
 443         s64 br;
 444         ntfs_volume *vol;
 445         NTFS_BOOT_SECTOR *bs;
 446         int eo;
 447 #ifdef DEBUG
 448         const char *OK = "OK\n";
 449         const char *FAILED = "FAILED\n";
 450         BOOL debug = 1;
 451 #else
 452         BOOL debug = 0;
 453 #endif
 454 
 455         if (!dev || !dev->d_ops || !dev->d_name) {
 456                 errno = EINVAL;
 457                 return NULL;
 458         }
 459 
 460         if (!(bs = (NTFS_BOOT_SECTOR *)ntfs_malloc(sizeof(NTFS_BOOT_SECTOR))))
 461                 return NULL;
 462 
 463         /* Allocate the volume structure. */
 464         vol = ntfs_volume_alloc();
 465         if (!vol)
 466                 goto error_exit;
 467         /* Create the default upcase table. */
 468         vol->upcase_len = 65536;
 469         vol->upcase = (ntfschar*)ntfs_malloc(vol->upcase_len *
 470                         sizeof(ntfschar));
 471         if (!vol->upcase)
 472                 goto error_exit;
 473         ntfs_upcase_table_build(vol->upcase,
 474                         vol->upcase_len * sizeof(ntfschar));
 475         if (flags & NTFS_MNT_RDONLY)
 476                 NVolSetReadOnly(vol);
 477         if (flags & NTFS_MNT_CASE_SENSITIVE)
 478                 NVolSetCaseSensitive(vol);
 479         if (flags & NTFS_MNT_INTERIX)
 480                 NVolSetInterix(vol);
 481         ntfs_log_debug("Reading bootsector... ");
 482         if (dev->d_ops->open(dev, NVolReadOnly(vol) ? O_RDONLY :
 483                                 ((flags & NTFS_MNT_NOT_EXCLUSIVE) ? O_RDWR :
 484                                 (O_RDWR | O_EXCL)))) {
 485                 ntfs_log_debug(FAILED);
 486                 ntfs_log_perror("Error opening partition device");
 487                 goto error_exit;
 488         }
 489         /* Attach the device to the volume. */
 490         vol->u.dev = dev;
 491         /* Now read the bootsector. */
 492         br = ntfs_pread(dev, 0, sizeof(NTFS_BOOT_SECTOR), bs);
 493         if (br != sizeof(NTFS_BOOT_SECTOR)) {
 494                 ntfs_log_debug(FAILED);
 495                 if (br != -1)
 496                         errno = EINVAL;
 497                 if (!br)
 498                         ntfs_log_debug("Error: partition is smaller than "
 499                                         "bootsector size. Weird!\n");
 500                 else
 501                         ntfs_log_perror("Error reading bootsector");
 502                 goto error_exit;
 503         }
 504         ntfs_log_debug(OK);
 505         if (!ntfs_boot_sector_is_ntfs(bs, !debug)) {
 506                 ntfs_log_debug("Error: %s is not a valid NTFS partition!\n",
 507                                 dev->d_name);
 508                 errno = EINVAL;
 509                 goto error_exit;
 510         }
 511         if (ntfs_boot_sector_parse(vol, bs) < 0) {
 512                 ntfs_log_perror("Failed to parse ntfs bootsector");
 513                 goto error_exit;
 514         }
 515         free(bs);
 516         bs = NULL;
 517         /* Now set the device block size to the sector size. */
 518         if (ntfs_device_block_size_set(vol->u.dev, vol->sector_size))
 519                 ntfs_log_debug("Failed to set the device block size to the "
 520                                 "sector size.  This may affect performance "
 521                                 "but should be harmless otherwise.  Error: "
 522                                 "%s\n", strerror(errno));
 523         /*
 524          * We now initialize the cluster allocator.
 525          *
 526          * FIXME: Move this to its own function? (AIA)
 527          */
 528 
 529         // TODO: Make this tunable at mount time. (AIA)
 530         vol->mft_zone_multiplier = 1;
 531 
 532         /* Determine the size of the MFT zone. */
 533         mft_zone_size = vol->nr_clusters;
 534         switch (vol->mft_zone_multiplier) {  /* % of volume size in clusters */
 535         case 4:
 536                 mft_zone_size >>= 1;                      /* 50%   */
 537                 break;
 538         case 3:
 539                 mft_zone_size = mft_zone_size * 3 >> 3;   /* 37.5% */
 540                 break;
 541         case 2:
 542                 mft_zone_size >>= 2;                      /* 25%   */
 543                 break;
 544         /* case 1: */
 545         default:
 546                 mft_zone_size >>= 3;                      /* 12.5% */
 547                 break;
 548         }
 549 
 550         /* Setup the mft zone. */
 551         vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn;
 552         ntfs_log_debug("mft_zone_pos = 0x%llx\n", (long long)vol->mft_zone_pos);
 553 
 554         /*
 555          * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs
 556          * source) and if the actual mft_lcn is in the expected place or even
 557          * further to the front of the volume, extend the mft_zone to cover the
 558          * beginning of the volume as well. This is in order to protect the
 559          * area reserved for the mft bitmap as well within the mft_zone itself.
 560          * On non-standard volumes we don't protect it as the overhead would be
 561          * higher than the speed increase we would get by doing it.
 562          */
 563         mft_lcn = (8192 + 2 * vol->cluster_size - 1) / vol->cluster_size;
 564         if (mft_lcn * vol->cluster_size < 16 * 1024)
 565                 mft_lcn = (16 * 1024 + vol->cluster_size - 1) /
 566                                 vol->cluster_size;
 567         if (vol->mft_zone_start <= mft_lcn)
 568                 vol->mft_zone_start = 0;
 569         ntfs_log_debug("mft_zone_start = 0x%llx\n",
 570                         (long long)vol->mft_zone_start);
 571 
 572         /*
 573          * Need to cap the mft zone on non-standard volumes so that it does
 574          * not point outside the boundaries of the volume. We do this by
 575          * halving the zone size until we are inside the volume.
 576          */
 577         vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
 578         while (vol->mft_zone_end >= vol->nr_clusters) {
 579                 mft_zone_size >>= 1;
 580                 vol->mft_zone_end = vol->mft_lcn + mft_zone_size;
 581         }
 582         ntfs_log_debug("mft_zone_end = 0x%llx\n", (long long)vol->mft_zone_end);
 583 
 584         /*
 585          * Set the current position within each data zone to the start of the
 586          * respective zone.
 587          */
 588         vol->data1_zone_pos = vol->mft_zone_end;
 589         ntfs_log_debug("data1_zone_pos = 0x%llx\n", vol->data1_zone_pos);
 590         vol->data2_zone_pos = 0;
 591         ntfs_log_debug("data2_zone_pos = 0x%llx\n", vol->data2_zone_pos);
 592 
 593         /* Set the mft data allocation position to mft record 24. */
 594         vol->mft_data_pos = 24;
 595 
 596         /*
 597          * The cluster allocator is now fully operational.
 598          */
 599 
 600         /* Need to setup $MFT so we can use the library read functions. */
 601         ntfs_log_debug("Loading $MFT... ");
 602         if (ntfs_mft_load(vol) < 0) {
 603                 ntfs_log_debug(FAILED);
 604                 ntfs_log_perror("Failed to load $MFT");
 605                 goto error_exit;
 606         }
 607         ntfs_log_debug(OK);
 608 
 609         /* Need to setup $MFTMirr so we can use the write functions, too. */
 610         ntfs_log_debug("Loading $MFTMirr... ");
 611         if (ntfs_mftmirr_load(vol) < 0) {
 612                 ntfs_log_debug(FAILED);
 613                 ntfs_log_perror("Failed to load $MFTMirr");
 614                 goto error_exit;
 615         }
 616         ntfs_log_debug(OK);
 617         return vol;
 618 error_exit:
 619         eo = errno;
 620         free(bs);
 621         if (vol)
 622                 __ntfs_volume_release(vol);
 623         errno = eo;
 624         return NULL;
 625 }
 626 
 627 /**
 628  * ntfs_volume_check_logfile - check logfile on target volume
 629  * @vol:        volume on which to check logfile
 630  *
 631  * Return 0 on success and -1 on error with errno set error code.
 632  */
 633 static int ntfs_volume_check_logfile(ntfs_volume *vol)
 634 {
 635         ntfs_inode *ni;
 636         ntfs_attr *na = NULL;
 637         RESTART_PAGE_HEADER *rp = NULL;
 638         int err = 0;
 639 
 640         if ((ni = ntfs_inode_open(vol, FILE_LogFile)) == NULL) {
 641                 ntfs_log_debug("Failed to open inode FILE_LogFile.\n");
 642                 errno = EIO;
 643                 return -1;
 644         }
 645         if ((na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0)) == NULL) {
 646                 ntfs_log_debug("Failed to open $FILE_LogFile/$DATA\n");
 647                 err = EIO;
 648                 goto exit;
 649         }
 650         if (!ntfs_check_logfile(na, &rp) || !ntfs_is_logfile_clean(na, rp))
 651                 err = EOPNOTSUPP;
 652         free(rp);
 653 exit:
 654         if (na)
 655                 ntfs_attr_close(na);
 656         ntfs_inode_close(ni);
 657         if (err) {
 658                 errno = err;
 659                 return -1;
 660         }
 661         return 0;
 662 }
 663 
 664 /**
 665  * ntfs_hiberfile_open - Find and open '/hiberfil.sys'
 666  * @vol:    An ntfs volume obtained from ntfs_mount
 667  *
 668  * Return:  inode  Success, hiberfil.sys is valid
 669  *          NULL   hiberfil.sys doesn't exist or some other error occurred
 670  */
 671 static ntfs_inode *ntfs_hiberfile_open(ntfs_volume *vol)
 672 {
 673         u64 inode;
 674         ntfs_inode *ni_root;
 675         ntfs_inode *ni_hibr = NULL;
 676         ntfschar   *unicode = NULL;
 677         int unicode_len;
 678         const char *hiberfile = "hiberfil.sys";
 679 
 680         if (!vol) {
 681                 errno = EINVAL;
 682                 return NULL;
 683         }
 684 
 685         ni_root = ntfs_inode_open(vol, FILE_root);
 686         if (!ni_root) {
 687                 ntfs_log_debug("Couldn't open the root directory.\n");
 688                 return NULL;
 689         }
 690 
 691         unicode_len = ntfs_mbstoucs(hiberfile, &unicode, 0);
 692         if (unicode_len < 0) {
 693                 ntfs_log_perror("Couldn't convert 'hiberfil.sys' to Unicode");
 694                 goto out;
 695         }
 696 
 697         inode = ntfs_inode_lookup_by_name(ni_root, unicode, unicode_len);
 698         if (inode == (u64)-1) {
 699                 ntfs_log_debug("Couldn't find file '%s'.\n", hiberfile);
 700                 goto out;
 701         }
 702 
 703         inode = MREF(inode);
 704         ni_hibr = ntfs_inode_open(vol, inode);
 705         if (!ni_hibr) {
 706                 ntfs_log_debug("Couldn't open inode %lld.\n", (long long)inode);
 707                 goto out;
 708         }
 709 out:
 710         ntfs_inode_close(ni_root);
 711         free(unicode);
 712         return ni_hibr;
 713 }
 714 
 715 
 716 #define NTFS_HIBERFILE_HEADER_SIZE      4096
 717 
 718 /**
 719  * ntfs_volume_check_hiberfile - check hiberfil.sys whether Windows is
 720  *                               hibernated on the target volume
 721  * @vol:    volume on which to check hiberfil.sys
 722  *
 723  * Return:  0 if Windows isn't hibernated for sure
 724  *         -1 otherwise and errno is set to the appropriate value
 725  */
 726 static int ntfs_volume_check_hiberfile(ntfs_volume *vol)
 727 {
 728         ntfs_inode *ni;
 729         ntfs_attr *na = NULL;
 730         int bytes_read, ret = -1;
 731         char *buf = NULL;
 732 
 733         ni = ntfs_hiberfile_open(vol);
 734         if (!ni) {
 735                 if (errno == ENOENT)
 736                         return 0;
 737                 return -1;
 738         }
 739 
 740         buf = ntfs_malloc(NTFS_HIBERFILE_HEADER_SIZE);
 741         if (!buf)
 742                 goto out;
 743 
 744         na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
 745         if (!na) {
 746                 ntfs_log_perror("Failed to open hiberfil.sys data attribute");
 747                 goto out;
 748         }
 749 
 750         bytes_read = ntfs_attr_pread(na, 0, NTFS_HIBERFILE_HEADER_SIZE, buf);
 751         if (bytes_read == -1) {
 752                 ntfs_log_perror("Failed to read hiberfil.sys");
 753                 goto out;
 754         }
 755         if (bytes_read < NTFS_HIBERFILE_HEADER_SIZE) {
 756                 ntfs_log_debug("Hibernated non-system partition, refused to "
 757                                 "mount!\n");
 758                 errno = EPERM;
 759                 goto out;
 760         }
 761         if (memcmp(buf, "hibr", 4) == 0) {
 762                 ntfs_log_debug("Windows is hibernated, refused to mount!\n");
 763                 errno = EPERM;
 764                 goto out;
 765         }
 766         ret = 0;
 767 out:
 768         if (na)
 769                 ntfs_attr_close(na);
 770         free(buf);
 771         ntfs_inode_close(ni);
 772         return ret;
 773 }
 774 
 775 /**
 776  * ntfs_volume_get_nr_free_mft_records - calculate number of free MFT records
 777  * vol:         ntfs volume for which perform calculations.
 778  *
 779  * This function initializes @vol->nr_free_mft_records. @vol->mftbmp_na should
 780  * be already opened upon call to this function.
 781  *
 782  * Return 0 on success. On error return -1 with errno set appropriately and
 783  * @vol->nr_free_mft_records is not touched in this case.
 784  */
 785 static int ntfs_volume_get_nr_free_mft_records(ntfs_volume *vol)
 786 {
 787         long nr_free = vol->mft_na->data_size >> vol->mft_record_size_bits;
 788         s64 br, total = 0;
 789         u8 *buf;
 790 
 791         buf = ntfs_malloc(vol->cluster_size);
 792         if (!buf)
 793                 return -1;
 794         while (1) {
 795                 int i, j;
 796 
 797                 br = ntfs_attr_pread(vol->mftbmp_na, total,
 798                                 vol->cluster_size, buf);
 799                 if (br <= 0)
 800                         break;
 801                 total += br;
 802                 for (i = 0; i < br; i++)
 803                         for (j = 0; j < 8; j++)
 804                                 if ((buf[i] >> j) & 1)
 805                                         nr_free--;
 806         }
 807         free(buf);
 808         if (!total || br < 0) {
 809                 ntfs_log_error("pread: %s\n", strerror(errno));
 810                 return -1;
 811         }
 812         vol->nr_free_mft_records = nr_free;
 813         return 0;
 814 }
 815 
 816 /**
 817  * ntfs_volume_get_nr_free_clusters - calculate number of free clusters
 818  * vol:         ntfs volume for which perform calculations.
 819  *
 820  * This function initializes @vol->nr_free_clusters. @vol->lcnbmp_na should be
 821  * already opened upon call to this function.
 822  *
 823  * Return 0 on success. On error return -1 with errno set appropriately and
 824  * @vol->nr_free_clusters is not touched in this case.
 825  */
 826 static long ntfs_volume_get_nr_free_clusters(ntfs_volume *vol)
 827 {
 828         long nr_free = vol->nr_clusters;
 829         s64 br, total = 0;
 830         u8 *buf;
 831 
 832         buf = ntfs_malloc(vol->cluster_size);
 833         if (!buf)
 834                 return -1;
 835         while (1) {
 836                 int i, j;
 837 
 838                 br = ntfs_attr_pread(vol->lcnbmp_na, total,
 839                                 vol->cluster_size, buf);
 840                 if (br <= 0)
 841                         break;
 842                 total += br;
 843                 for (i = 0; i < br; i++)
 844                         for (j = 0; j < 8; j++)
 845                                 if ((buf[i] >> j) & 1)
 846                                         nr_free--;
 847         }
 848         free(buf);
 849         if (!total || br < 0) {
 850                 ntfs_log_error("pread: %s\n", strerror(errno));
 851                 return -1;
 852         }
 853         vol->nr_free_clusters = nr_free;
 854         return 0;
 855 }
 856 
 857 /**
 858  * ntfs_device_mount - open ntfs volume
 859  * @dev:        device to open
 860  * @flags:      optional mount flags
 861  *
 862  * This function mounts an ntfs volume. @dev should describe the device which
 863  * to mount as the ntfs volume.
 864  *
 865  * @flags is an optional second parameter. Some flags are similar to flags used
 866  * as for the mount system call (man 2 mount). Currently the following flags
 867  * are implemented:
 868  *      NTFS_MNT_RDONLY         - mount volume read-only
 869  *      NTFS_MNT_CASE_SENSITIVE - treat filenames as case sensitive even if
 870  *                                they are not in POSIX namespace
 871  *      NTFS_MNT_NOT_EXCLUSIVE  - (unix only) do not open volume exclusively
 872  *      NTFS_MNT_FORENSIC       - mount for forensic purposes, i.e. do not do
 873  *                                any writing at all during the mount, i.e. no
 874  *                                journal emptying, no dirty bit setting, etc.
 875  *      NTFS_MNT_INTERIX        - make libntfs recognize special Interix files
 876  *
 877  * The function opens the device @dev and verifies that it contains a valid
 878  * bootsector. Then, it allocates an ntfs_volume structure and initializes
 879  * some of the values inside the structure from the information stored in the
 880  * bootsector. It proceeds to load the necessary system files and completes
 881  * setting up the structure.
 882  *
 883  * Return the allocated volume structure on success and NULL on error with
 884  * errno set to the error code.
 885  */
 886 ntfs_volume *ntfs_device_mount(struct ntfs_device *dev, ntfs_mount_flags flags)
 887 {
 888         s64 l;
 889 #ifdef DEBUG
 890         const char *OK = "OK\n";
 891         const char *FAILED = "FAILED\n";
 892 #endif
 893         ntfs_volume *vol;
 894         u8 *m = NULL, *m2 = NULL;
 895         ntfs_attr_search_ctx *ctx = NULL;
 896         ntfs_inode *ni;
 897         ntfs_attr *na;
 898         ATTR_RECORD *a;
 899         VOLUME_INFORMATION *vinf;
 900         ntfschar *vname;
 901         int i, j, eo;
 902         u32 u;
 903 
 904         vol = ntfs_volume_startup(dev, flags);
 905         if (!vol) {
 906                 ntfs_log_perror("Failed to startup volume");
 907                 return NULL;
 908         }
 909         /* Record whether this is a forensic mount. */
 910         if (flags & NTFS_MNT_FORENSIC)
 911                 NVolSetForensicMount(vol);
 912         /* Load data from $MFT and $MFTMirr and compare the contents. */
 913         m  = (u8*)ntfs_malloc(vol->mftmirr_size << vol->mft_record_size_bits);
 914         m2 = (u8*)ntfs_malloc(vol->mftmirr_size << vol->mft_record_size_bits);
 915         if (!m || !m2)
 916                 goto error_exit;
 917 
 918         l = ntfs_attr_mst_pread(vol->mft_na, 0, vol->mftmirr_size,
 919                         vol->mft_record_size, m);
 920         if (l != vol->mftmirr_size) {
 921                 if (l == -1)
 922                         ntfs_log_perror("Failed to read $MFT");
 923                 else {
 924                         ntfs_log_debug("Failed to read $MFT, unexpected length "
 925                                        "(%d != %lld).\n", vol->mftmirr_size, l);
 926                         errno = EIO;
 927                 }
 928                 goto error_exit;
 929         }
 930         l = ntfs_attr_mst_pread(vol->mftmirr_na, 0, vol->mftmirr_size,
 931                         vol->mft_record_size, m2);
 932         if (l != vol->mftmirr_size) {
 933                 if (l == -1)
 934                         ntfs_log_perror("Failed to read $MFTMirr");
 935                 else {
 936                         ntfs_log_debug("Failed to read $MFTMirr, unexpected "
 937                                        "length (%d != %lld).\n",
 938                                        vol->mftmirr_size, l);
 939                         errno = EIO;
 940                 }
 941                 goto error_exit;
 942         }
 943         ntfs_log_debug("Comparing $MFTMirr to $MFT... ");
 944         for (i = 0; i < vol->mftmirr_size; ++i) {
 945                 MFT_RECORD *mrec, *mrec2;
 946                 const char *ESTR[12] = { "$MFT", "$MFTMirr", "$LogFile",
 947                         "$Volume", "$AttrDef", "root directory", "$Bitmap",
 948                         "$Boot", "$BadClus", "$Secure", "$UpCase", "$Extend" };
 949                 const char *s;
 950 
 951                 if (i < 12)
 952                         s = ESTR[i];
 953                 else if (i < 16)
 954                         s = "system file";
 955                 else
 956                         s = "mft record";
 957 
 958                 mrec = (MFT_RECORD*)(m + i * vol->mft_record_size);
 959                 if (mrec->flags & MFT_RECORD_IN_USE) {
 960                         if (ntfs_is_baad_record(mrec->magic)) {
 961                                 ntfs_log_debug("FAILED\n");
 962                                 ntfs_log_debug("$MFT error: Incomplete multi "
 963                                                 "sector transfer detected in "
 964                                                 "%s.\n", s);
 965                                 goto io_error_exit;
 966                         }
 967                         if (!ntfs_is_mft_record(mrec->magic)) {
 968                                 ntfs_log_debug("FAILED\n");
 969                                 ntfs_log_debug("$MFT error: Invalid mft "
 970                                                 "record for %s.\n", s);
 971                                 goto io_error_exit;
 972                         }
 973                 }
 974                 mrec2 = (MFT_RECORD*)(m2 + i * vol->mft_record_size);
 975                 if (mrec2->flags & MFT_RECORD_IN_USE) {
 976                         if (ntfs_is_baad_record(mrec2->magic)) {
 977                                 ntfs_log_debug("FAILED\n");
 978                                 ntfs_log_debug("$MFTMirr error: Incomplete "
 979                                                 "multi sector transfer "
 980                                                 "detected in %s.\n", s);
 981                                 goto io_error_exit;
 982                         }
 983                         if (!ntfs_is_mft_record(mrec2->magic)) {
 984                                 ntfs_log_debug("FAILED\n");
 985                                 ntfs_log_debug("$MFTMirr error: Invalid mft "
 986                                                 "record for %s.\n", s);
 987                                 goto io_error_exit;
 988                         }
 989                 }
 990                 if (memcmp(mrec, mrec2, ntfs_mft_record_get_data_size(mrec))) {
 991                         ntfs_log_debug(FAILED);
 992                         ntfs_log_debug("$MFTMirr does not match $MFT. Run "
 993                                         "chkdsk.\n");
 994                         goto io_error_exit;
 995                 }
 996         }
 997         ntfs_log_debug(OK);
 998 
 999         free(m2);
1000         free(m);
1001         m = m2 = NULL;
1002 
1003         /* Now load the bitmap from $Bitmap. */
1004         ntfs_log_debug("Loading $Bitmap... ");
1005         vol->lcnbmp_ni = ntfs_inode_open(vol, FILE_Bitmap);
1006         if (!vol->lcnbmp_ni) {
1007                 ntfs_log_debug(FAILED);
1008                 ntfs_log_perror("Failed to open inode");
1009                 goto error_exit;
1010         }
1011         /* Get an ntfs attribute for $Bitmap/$DATA. */
1012         vol->lcnbmp_na = ntfs_attr_open(vol->lcnbmp_ni, AT_DATA, AT_UNNAMED, 0);
1013         if (!vol->lcnbmp_na) {
1014                 ntfs_log_debug(FAILED);
1015                 ntfs_log_perror("Failed to open ntfs attribute");
1016                 goto error_exit;
1017         }
1018         /* Done with the $Bitmap mft record. */
1019         ntfs_log_debug(OK);
1020 
1021         /* Now load the upcase table from $UpCase. */
1022         ntfs_log_debug("Loading $UpCase... ");
1023         ni = ntfs_inode_open(vol, FILE_UpCase);
1024         if (!ni) {
1025                 ntfs_log_debug(FAILED);
1026                 ntfs_log_perror("Failed to open inode");
1027                 goto error_exit;
1028         }
1029         /* Get an ntfs attribute for $UpCase/$DATA. */
1030         na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
1031         if (!na) {
1032                 ntfs_log_debug(FAILED);
1033                 ntfs_log_perror("Failed to open ntfs attribute");
1034                 goto error_exit;
1035         }
1036         /*
1037          * Note: Normally, the upcase table has a length equal to 65536
1038          * 2-byte Unicode characters but allow for different cases, so no
1039          * checks done. Just check we don't overflow 32-bits worth of Unicode
1040          * characters.
1041          */
1042         if (na->data_size & ~0x1ffffffffULL) {
1043                 ntfs_log_debug(FAILED);
1044                 ntfs_log_debug("Error: Upcase table is too big (max 32-bit "
1045                                 "allowed).\n");
1046                 errno = EINVAL;
1047                 goto error_exit;
1048         }
1049         if (vol->upcase_len != na->data_size >> 1) {
1050                 vol->upcase_len = na->data_size >> 1;
1051                 /* Throw away default table. */
1052                 free(vol->upcase);
1053                 vol->upcase = (ntfschar*)ntfs_malloc(na->data_size);
1054                 if (!vol->upcase) {
1055                         ntfs_log_debug(FAILED);
1056                         goto error_exit;
1057                 }
1058         }
1059         /* Read in the $DATA attribute value into the buffer. */
1060         l = ntfs_attr_pread(na, 0, na->data_size, vol->upcase);
1061         if (l != na->data_size) {
1062                 ntfs_log_debug(FAILED);
1063                 ntfs_log_debug("Amount of data read does not correspond to "
1064                                 "expected length!\n");
1065                 errno = EIO;
1066                 goto error_exit;
1067         }
1068         /* Done with the $UpCase mft record. */
1069         ntfs_log_debug(OK);
1070         ntfs_attr_close(na);
1071         if (ntfs_inode_close(ni))
1072                 ntfs_log_perror("Failed to close inode, leaking memory");
1073 
1074         /*
1075          * Now load $Volume and set the version information and flags in the
1076          * vol structure accordingly.
1077          */
1078         ntfs_log_debug("Loading $Volume... ");
1079         vol->vol_ni = ntfs_inode_open(vol, FILE_Volume);
1080         if (!vol->vol_ni) {
1081                 ntfs_log_debug(FAILED);
1082                 ntfs_log_perror("Failed to open inode");
1083                 goto error_exit;
1084         }
1085         /* Get a search context for the $Volume/$VOLUME_INFORMATION lookup. */
1086         ctx = ntfs_attr_get_search_ctx(vol->vol_ni, NULL);
1087         if (!ctx) {
1088                 ntfs_log_debug(FAILED);
1089                 ntfs_log_perror("Failed to allocate attribute search context");
1090                 goto error_exit;
1091         }
1092         /* Find the $VOLUME_INFORMATION attribute. */
1093         if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL,
1094                         0, ctx)) {
1095                 ntfs_log_debug(FAILED);
1096                 ntfs_log_debug("$VOLUME_INFORMATION attribute not found in "
1097                                 "$Volume?!?\n");
1098                 goto error_exit;
1099         }
1100         a = ctx->attr;
1101         /* Has to be resident. */
1102         if (a->non_resident) {
1103                 ntfs_log_debug(FAILED);
1104                 ntfs_log_debug("Error: Attribute $VOLUME_INFORMATION must be "
1105                                 "resident (and it isn't)!\n");
1106                 errno = EIO;
1107                 goto error_exit;
1108         }
1109         /* Get a pointer to the value of the attribute. */
1110         vinf = (VOLUME_INFORMATION*)(le16_to_cpu(a->u.res.value_offset) + (char*)a);
1111         /* Sanity checks. */
1112         if ((char*)vinf + le32_to_cpu(a->u.res.value_length) > (char*)ctx->mrec +
1113                         le32_to_cpu(ctx->mrec->bytes_in_use) ||
1114                         le16_to_cpu(a->u.res.value_offset) + le32_to_cpu(
1115                         a->u.res.value_length) > le32_to_cpu(a->length)) {
1116                 ntfs_log_debug(FAILED);
1117                 ntfs_log_debug("Error: Attribute $VOLUME_INFORMATION in "
1118                                 "$Volume is corrupt!\n");
1119                 errno = EIO;
1120                 goto error_exit;
1121         }
1122         /* Setup vol from the volume information attribute value. */
1123         vol->major_ver = vinf->major_ver;
1124         vol->minor_ver = vinf->minor_ver;
1125         /*
1126          * Do not use le16_to_cpu() macro here as our VOLUME_FLAGS are defined
1127          * using cpu_to_le16() macro and hence are consistent.
1128          */
1129         vol->flags = vinf->flags;
1130         /* Record whether the volume was dirty or not. */
1131         if (vol->flags & VOLUME_IS_DIRTY)
1132                 NVolSetWasDirty(vol);
1133         /*
1134          * Reinitialize the search context for the $Volume/$VOLUME_NAME lookup.
1135          */
1136         ntfs_attr_reinit_search_ctx(ctx);
1137         if (ntfs_attr_lookup(AT_VOLUME_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0,
1138                         ctx)) {
1139                 if (errno != ENOENT) {
1140                         ntfs_log_debug(FAILED);
1141                         ntfs_log_debug("Error: Lookup of $VOLUME_NAME "
1142                                         "attribute in $Volume failed.  "
1143                                         "This probably means something is "
1144                                         "corrupt.  Run chkdsk.\n");
1145                         goto error_exit;
1146                 }
1147                 /*
1148                  * Attribute not present.  This has been seen in the field.
1149                  * Treat this the same way as if the attribute was present but
1150                  * had zero length.
1151                  */
1152                 vol->vol_name = ntfs_malloc(1);
1153                 if (!vol->vol_name) {
1154                         ntfs_log_debug(FAILED);
1155                         goto error_exit;
1156                 }
1157                 vol->vol_name[0] = '\0';
1158         } else {
1159                 a = ctx->attr;
1160                 /* Has to be resident. */
1161                 if (a->non_resident) {
1162                         ntfs_log_debug(FAILED);
1163                         ntfs_log_debug("Error: Attribute $VOLUME_NAME must be "
1164                                         "resident!\n");
1165                         errno = EIO;
1166                         goto error_exit;
1167                 }
1168                 /* Get a pointer to the value of the attribute. */
1169                 vname = (ntfschar*)(le16_to_cpu(a->u.res.value_offset) + (char*)a);
1170                 u = le32_to_cpu(a->u.res.value_length) / 2;
1171                 /*
1172                  * Convert Unicode volume name to current locale multibyte
1173                  * format.
1174                  */
1175                 vol->vol_name = NULL;
1176                 if (ntfs_ucstombs(vname, u, &vol->vol_name, 0) == -1) {
1177                         ntfs_log_perror("Error: Volume name could not be "
1178                                         "converted to current locale");
1179                         ntfs_log_debug("Forcing name into ASCII by replacing "
1180                                 "non-ASCII characters with underscores.\n");
1181                         vol->vol_name = ntfs_malloc(u + 1);
1182                         if (!vol->vol_name) {
1183                                 ntfs_log_debug(FAILED);
1184                                 goto error_exit;
1185                         }
1186                         for (j = 0; j < (s32)u; j++) {
1187                                 u16 uc = le16_to_cpu(vname[j]);
1188                                 if (uc > 0xff)
1189                                         uc = (u16)'_';
1190                                 vol->vol_name[j] = (char)uc;
1191                         }
1192                         vol->vol_name[u] = 0;
1193                 }
1194         }
1195         ntfs_log_debug(OK);
1196         ntfs_attr_put_search_ctx(ctx);
1197         ctx = NULL;
1198         /* Now load the attribute definitions from $AttrDef. */
1199         ntfs_log_debug("Loading $AttrDef... ");
1200         ni = ntfs_inode_open(vol, FILE_AttrDef);
1201         if (!ni) {
1202                 ntfs_log_debug(FAILED);
1203                 ntfs_log_perror("Failed to open inode");
1204                 goto error_exit;
1205         }
1206         /* Get an ntfs attribute for $AttrDef/$DATA. */
1207         na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0);
1208         if (!na) {
1209                 ntfs_log_debug(FAILED);
1210                 ntfs_log_perror("Failed to open ntfs attribute");
1211                 goto error_exit;
1212         }
1213         /* Check we don't overflow 32-bits. */
1214         if (na->data_size > 0xffffffffLL) {
1215                 ntfs_log_debug(FAILED);
1216                 ntfs_log_debug("Error: Attribute definition table is too big "
1217                                 "(max 32-bit allowed).\n");
1218                 errno = EINVAL;
1219                 goto error_exit;
1220         }
1221         vol->attrdef_len = na->data_size;
1222         vol->attrdef = (ATTR_DEF*)ntfs_malloc(na->data_size);
1223         if (!vol->attrdef) {
1224                 ntfs_log_debug(FAILED);
1225                 goto error_exit;
1226         }
1227         /* Read in the $DATA attribute value into the buffer. */
1228         l = ntfs_attr_pread(na, 0, na->data_size, vol->attrdef);
1229         if (l != na->data_size) {
1230                 ntfs_log_debug(FAILED);
1231                 ntfs_log_debug("Amount of data read does not correspond to "
1232                                 "expected length!\n");
1233                 errno = EIO;
1234                 goto error_exit;
1235         }
1236         /* Done with the $AttrDef mft record. */
1237         ntfs_log_debug(OK);
1238         ntfs_attr_close(na);
1239         if (ntfs_inode_close(ni))
1240                 ntfs_log_perror("Failed to close inode, leaking memory");
1241         /* Initialize number of free clusters and MFT records. */
1242         if (ntfs_volume_get_nr_free_mft_records(vol)) {
1243                 ntfs_log_perror("Failed to calculate number of free MFTs");
1244                 goto error_exit;
1245         }
1246         if (ntfs_volume_get_nr_free_clusters(vol)) {
1247                 ntfs_log_perror("Failed to calculate number of free clusters");
1248                 goto error_exit;
1249         }
1250         /*
1251          * Check for dirty logfile and hibernated Windows.
1252          * We care only about read-write mounts.
1253          *
1254          * If all is ok, reset the logfile and set the dirty bit on the volume.
1255          *
1256          * But do not do that if this is a FORENSIC mount.
1257          */
1258         if (!(flags & NTFS_MNT_RDONLY)) {
1259                 if (ntfs_volume_check_hiberfile(vol) < 0)
1260                         goto error_exit;
1261                 if (ntfs_volume_check_logfile(vol) < 0) {
1262                         if (errno != EOPNOTSUPP || !(flags & NTFS_MNT_FORCE))
1263                                 goto error_exit;
1264                         ntfs_log_warning("WARNING: $LogFile is not clean, "
1265                                         "forced to continue.\n");
1266                         NVolSetWasDirty(vol); /* Leave volume dirty since we
1267                                                  empted logfile. */
1268                 }
1269                 if (!NVolForensicMount(vol)) {
1270                         if (ntfs_logfile_reset(vol) < 0)
1271                                 goto error_exit;
1272                         if (!(vol->flags & VOLUME_IS_DIRTY)) {
1273                                 vol->flags |= VOLUME_IS_DIRTY;
1274                                 if (ntfs_volume_write_flags(vol, vol->flags) <
1275                                                 0)
1276                                         goto error_exit;
1277                         }
1278                 }
1279         }
1280         return vol;
1281 io_error_exit:
1282         errno = EIO;
1283 error_exit:
1284         eo = errno;
1285         if (ctx)
1286                 ntfs_attr_put_search_ctx(ctx);
1287         free(m);
1288         free(m2);
1289         __ntfs_volume_release(vol);
1290         errno = eo;
1291         return NULL;
1292 }
1293 
1294 /**
1295  * ntfs_mount - open ntfs volume
1296  * @name:       name of device/file to open
1297  * @flags:      optional mount flags
1298  *
1299  * This function mounts an ntfs volume. @name should contain the name of the
1300  * device/file to mount as the ntfs volume.
1301  *
1302  * @flags is an optional second parameter. See ntfs_device_mount comment for
1303  * description.
1304  *
1305  * The function opens the device or file @name and verifies that it contains a
1306  * valid bootsector. Then, it allocates an ntfs_volume structure and initializes
1307  * some of the values inside the structure from the information stored in the
1308  * bootsector. It proceeds to load the necessary system files and completes
1309  * setting up the structure.
1310  *
1311  * Return the allocated volume structure on success and NULL on error with
1312  * errno set to the error code.
1313  *
1314  * Note, that a copy is made of @name, and hence it can be discarded as
1315  * soon as the function returns.
1316  */
1317 ntfs_volume *ntfs_mount(const char *name __attribute__((unused)),
1318                 ntfs_mount_flags flags __attribute__((unused)))
1319 {
1320 #ifndef NO_NTFS_DEVICE_DEFAULT_IO_OPS
1321         struct ntfs_device *dev;
1322         ntfs_volume *vol;
1323 
1324         /* Allocate an ntfs_device structure. */
1325         dev = ntfs_device_alloc(name, 0, &ntfs_device_default_io_ops, NULL);
1326         if (!dev)
1327                 return NULL;
1328         /* Call ntfs_device_mount() to do the actual mount. */
1329         vol = ntfs_device_mount(dev, flags);
1330         if (!vol) {
1331                 int eo = errno;
1332                 ntfs_device_free(dev);
1333                 errno = eo;
1334         }
1335         return vol;
1336 #else
1337         /*
1338          * ntfs_mount() makes no sense if NO_NTFS_DEVICE_DEFAULT_IO_OPS is
1339          * defined as there are no device operations available in libntfs in
1340          * this case.
1341          */
1342         errno = EOPNOTSUPP;
1343         return NULL;
1344 #endif
1345 }
1346 
1347 /**
1348  * ntfs_device_umount - close ntfs volume
1349  * @vol: address of ntfs_volume structure of volume to close
1350  * @force: if true force close the volume even if it is busy
1351  *
1352  * Deallocate all structures (including @vol itself) associated with the ntfs
1353  * volume @vol.
1354  *
1355  * Note it is up to the caller to destroy the device associated with the volume
1356  * being unmounted after this function returns.
1357  *
1358  * Return 0 on success. On error return -1 with errno set appropriately
1359  * (most likely to one of EAGAIN, EBUSY or EINVAL). The EAGAIN error means that
1360  * an operation is in progress and if you try the close later the operation
1361  * might be completed and the close succeed.
1362  *
1363  * If @force is true (i.e. not zero) this function will close the volume even
1364  * if this means that data might be lost.
1365  *
1366  * @vol must have previously been returned by a call to ntfs_device_mount().
1367  *
1368  * @vol itself is deallocated and should no longer be dereferenced after this
1369  * function returns success. If it returns an error then nothing has been done
1370  * so it is safe to continue using @vol.
1371  */
1372 int ntfs_device_umount(ntfs_volume *vol,
1373                 const BOOL force __attribute__((unused)))
1374 {
1375         if (!vol) {
1376                 errno = EINVAL;
1377                 return -1;
1378         }
1379         __ntfs_volume_release(vol);
1380         return 0;
1381 }
1382 
1383 /**
1384  * ntfs_umount - close ntfs volume
1385  * @vol: address of ntfs_volume structure of volume to close
1386  * @force: if true force close the volume even if it is busy
1387  *
1388  * Deallocate all structures (including @vol itself) associated with the ntfs
1389  * volume @vol.
1390  *
1391  * Return 0 on success. On error return -1 with errno set appropriately
1392  * (most likely to one of EAGAIN, EBUSY or EINVAL). The EAGAIN error means that
1393  * an operation is in progress and if you try the close later the operation
1394  * might be completed and the close succeed.
1395  *
1396  * If @force is true (i.e. not zero) this function will close the volume even
1397  * if this means that data might be lost.
1398  *
1399  * @vol must have previously been returned by a call to ntfs_mount().
1400  *
1401  * @vol itself is deallocated and should no longer be dereferenced after this
1402  * function returns success. If it returns an error then nothing has been done
1403  * so it is safe to continue using @vol.
1404  */
1405 int ntfs_umount(ntfs_volume *vol,
1406                 const BOOL force __attribute__((unused)))
1407 {
1408         struct ntfs_device *dev;
1409 
1410         if (!vol) {
1411                 errno = EINVAL;
1412                 return -1;
1413         }
1414         dev = vol->u.dev;
1415         __ntfs_volume_release(vol);
1416         ntfs_device_free(dev);
1417         return 0;
1418 }
1419 
1420 #ifdef HAVE_MNTENT_H
1421 
1422 #ifndef HAVE_REALPATH
1423 /**
1424  * realpath - If there is no realpath on the system
1425  */
1426 static char *realpath(const char *path, char *resolved_path)
1427 {
1428         strncpy(resolved_path, path, PATH_MAX);
1429         resolved_path[PATH_MAX] = '\0';
1430         return resolved_path;
1431 }
1432 #endif
1433 
1434 /**
1435  * ntfs_mntent_check - desc
1436  *
1437  * If you are wanting to use this, you actually wanted to use
1438  * ntfs_check_if_mounted(), you just didn't realize. (-:
1439  *
1440  * See description of ntfs_check_if_mounted(), below.
1441  */
1442 static int ntfs_mntent_check(const char *file, unsigned long *mnt_flags)
1443 {
1444         struct mntent *mnt;
1445         char *real_file = NULL, *real_fsname = NULL;
1446         FILE *f;
1447         int err = 0;
1448 
1449         real_file = ntfs_malloc(PATH_MAX + 1);
1450         if (!real_file)
1451                 return -1;
1452         real_fsname = ntfs_malloc(PATH_MAX + 1);
1453         if (!real_fsname) {
1454                 err = errno;
1455                 goto exit;
1456         }
1457         if (!realpath(file, real_file)) {
1458                 err = errno;
1459                 goto exit;
1460         }
1461         if (!(f = setmntent(MOUNTED, "r"))) {
1462                 err = errno;
1463                 goto exit;
1464         }
1465         while ((mnt = getmntent(f))) {
1466                 if (!realpath(mnt->mnt_fsname, real_fsname))
1467                         continue;
1468                 if (!strcmp(real_file, real_fsname))
1469                         break;
1470         }
1471         endmntent(f);
1472         if (!mnt)
1473                 goto exit;
1474         *mnt_flags = NTFS_MF_MOUNTED;
1475         if (!strcmp(mnt->mnt_dir, "/"))
1476                 *mnt_flags |= NTFS_MF_ISROOT;
1477 #ifdef HAVE_HASMNTOPT
1478         if (hasmntopt(mnt, "ro") && !hasmntopt(mnt, "rw"))
1479                 *mnt_flags |= NTFS_MF_READONLY;
1480 #endif
1481 exit:
1482         free(real_file);
1483         free(real_fsname);
1484         if (err) {
1485                 errno = err;
1486                 return -1;
1487         }
1488         return 0;
1489 }
1490 #endif /* HAVE_MNTENT_H */
1491 
1492 /**
1493  * ntfs_check_if_mounted - check if an ntfs volume is currently mounted
1494  * @file:       device file to check
1495  * @mnt_flags:  pointer into which to return the ntfs mount flags (see volume.h)
1496  *
1497  * If the running system does not support the {set,get,end}mntent() calls,
1498  * just return 0 and set *@mnt_flags to zero.
1499  *
1500  * When the system does support the calls, ntfs_check_if_mounted() first tries
1501  * to find the device @file in /etc/mtab (or wherever this is kept on the
1502  * running system). If it is not found, assume the device is not mounted and
1503  * return 0 and set *@mnt_flags to zero.
1504  *
1505  * If the device @file is found, set the NTFS_MF_MOUNTED flags in *@mnt_flags.
1506  *
1507  * Further if @file is mounted as the file system root ("/"), set the flag
1508  * NTFS_MF_ISROOT in *@mnt_flags.
1509  *
1510  * Finally, check if the file system is mounted read-only, and if so set the
1511  * NTFS_MF_READONLY flag in *@mnt_flags.
1512  *
1513  * On success return 0 with *@mnt_flags set to the ntfs mount flags.
1514  *
1515  * On error return -1 with errno set to the error code.
1516  */
1517 int ntfs_check_if_mounted(const char *file __attribute__((unused)),
1518                 unsigned long *mnt_flags)
1519 {
1520         *mnt_flags = 0;
1521 #ifdef HAVE_MNTENT_H
1522         return ntfs_mntent_check(file, mnt_flags);
1523 #else
1524         return 0;
1525 #endif
1526 }
1527 
1528 /**
1529  * ntfs_version_is_supported - check if NTFS version is supported.
1530  * @vol:        ntfs volume whose version we're interested in.
1531  *
1532  * The function checks if the NTFS volume version is known or not.
1533  * Version 1.1 and 1.2 are used by Windows NT3.x and NT4.
1534  * Version 2.x is used by Windows 2000 Betas.
1535  * Version 3.0 is used by Windows 2000.
1536  * Version 3.1 is used by Windows XP, Windows Server 2003 and Vista.
1537  *
1538  * Return 0 if NTFS version is supported otherwise -1 with errno set.
1539  *
1540  * The following error codes are defined:
1541  *      EOPNOTSUPP - Unknown NTFS version
1542  *      EINVAL     - Invalid argument
1543  */
1544 int ntfs_version_is_supported(ntfs_volume *vol)
1545 {
1546         u8 major, minor;
1547 
1548         if (!vol) {
1549                 errno = EINVAL;
1550                 return -1;
1551         }
1552 
1553         major = vol->major_ver;
1554         minor = vol->minor_ver;
1555 
1556         if (NTFS_V1_1(major, minor) || NTFS_V1_2(major, minor))
1557                 return 0;
1558 
1559         if (NTFS_V2_X(major, minor))
1560                 return 0;
1561 
1562         if (NTFS_V3_0(major, minor) || NTFS_V3_1(major, minor))
1563                 return 0;
1564 
1565         errno = EOPNOTSUPP;
1566         return -1;
1567 }
1568 
1569 /**
1570  * ntfs_logfile_reset - "empty" $LogFile data attribute value
1571  * @vol:        ntfs volume whose $LogFile we intend to reset.
1572  *
1573  * Fill the value of the $LogFile data attribute, i.e. the contents of
1574  * the file, with 0xff's, thus marking the journal as empty.
1575  *
1576  * FIXME(?): We might need to zero the LSN field of every single mft
1577  * record as well. (But, first try without doing that and see what
1578  * happens, since chkdsk might pickup the pieces and do it for us...)
1579  *
1580  * On success return 0.
1581  *
1582  * On error return -1 with errno set to the error code.
1583  */
1584 int ntfs_logfile_reset(ntfs_volume *vol)
1585 {
1586         ntfs_inode *ni;
1587         ntfs_attr *na;
1588         int eo;
1589 
1590         if (!vol) {
1591                 errno = EINVAL;
1592                 return -1;
1593         }
1594 
1595         if ((ni = ntfs_inode_open(vol, FILE_LogFile)) == NULL) {
1596                 ntfs_log_perror("Failed to open inode FILE_LogFile.");
1597                 return -1;
1598         }
1599 
1600         if ((na = ntfs_attr_open(ni, AT_DATA, AT_UNNAMED, 0)) == NULL) {
1601                 eo = errno;
1602                 ntfs_log_perror("Failed to open $FILE_LogFile/$DATA");
1603                 goto error_exit;
1604         }
1605 
1606         if (ntfs_empty_logfile(na)) {
1607                 eo = errno;
1608                 ntfs_log_perror("Failed to empty $FILE_LogFile/$DATA");
1609                 ntfs_attr_close(na);
1610                 goto error_exit;
1611         }
1612         ntfs_attr_close(na);
1613         return ntfs_inode_close(ni);
1614 
1615 error_exit:
1616         ntfs_inode_close(ni);
1617         errno = eo;
1618         return -1;
1619 }
1620 
1621 /**
1622  * ntfs_volume_write_flags - set the flags of an ntfs volume
1623  * @vol:        ntfs volume where we set the volume flags
1624  * @flags:      new flags
1625  *
1626  * Set the on-disk volume flags in the mft record of $Volume and
1627  * on volume @vol to @flags.
1628  *
1629  * Return 0 if successful and -1 if not with errno set to the error code.
1630  */
1631 int ntfs_volume_write_flags(ntfs_volume *vol, const le16 flags)
1632 {
1633         ATTR_RECORD *a;
1634         VOLUME_INFORMATION *c;
1635         ntfs_attr_search_ctx *ctx;
1636         int ret = -1;   /* failure */
1637 
1638         if (!vol || !vol->vol_ni) {
1639                 errno = EINVAL;
1640                 return -1;
1641         }
1642         /* Get a pointer to the volume information attribute. */
1643         ctx = ntfs_attr_get_search_ctx(vol->vol_ni, NULL);
1644         if (!ctx) {
1645                 ntfs_log_perror("Failed to allocate attribute search context");
1646                 return -1;
1647         }
1648         if (ntfs_attr_lookup(AT_VOLUME_INFORMATION, AT_UNNAMED, 0, 0, 0, NULL,
1649                         0, ctx)) {
1650                 ntfs_log_error("Attribute $VOLUME_INFORMATION was not found "
1651                                 "in $Volume!\n");
1652                 goto err_out;
1653         }
1654         a = ctx->attr;
1655         /* Sanity check. */
1656         if (a->non_resident) {
1657                 ntfs_log_error("Attribute $VOLUME_INFORMATION must be "
1658                                 "resident (and it isn't)!\n");
1659                 errno = EIO;
1660                 goto err_out;
1661         }
1662         /* Get a pointer to the value of the attribute. */
1663         c = (VOLUME_INFORMATION*)(le16_to_cpu(a->u.res.value_offset) + (char*)a);
1664         /* Sanity checks. */
1665         if ((char*)c + le32_to_cpu(a->u.res.value_length) > (char*)ctx->mrec +
1666                         le32_to_cpu(ctx->mrec->bytes_in_use) ||
1667                         le16_to_cpu(a->u.res.value_offset) +
1668                         le32_to_cpu(a->u.res.value_length) > le32_to_cpu(a->length)) {
1669                 ntfs_log_error("Attribute $VOLUME_INFORMATION in $Volume is "
1670                                 "corrupt!\n");
1671                 errno = EIO;
1672                 goto err_out;
1673         }
1674         /* Set the volume flags. */
1675         vol->flags = c->flags = flags & VOLUME_FLAGS_MASK;
1676         /* Write them to disk. */
1677         ntfs_inode_mark_dirty(vol->vol_ni);
1678         if (ntfs_inode_sync(vol->vol_ni)) {
1679                 ntfs_log_perror("Error writing $Volume");
1680                 goto err_out;
1681         }
1682         ret = 0; /* success */
1683 err_out:
1684         ntfs_attr_put_search_ctx(ctx);
1685         if (ret)
1686                 ntfs_log_error("%s(): Failed.\n", "ntfs_volume_write_flags");
1687         return ret;
1688 }
1689