1/**
2 * dir.c - Directory handling code. Originated from the Linux-NTFS project.
3 *
4 * Copyright (c) 2002-2005 Anton Altaparmakov
5 * Copyright (c) 2004-2005 Richard Russon
6 * Copyright (c) 2004-2008 Szabolcs Szakacsits
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 NTFS-3G
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_ERRNO_H
33#include <errno.h>
34#endif
35#ifdef HAVE_STRING_H
36#include <string.h>
37#endif
38#ifdef HAVE_SYS_STAT_H
39#include <sys/stat.h>
40#endif
41
42#ifdef HAVE_SYS_SYSMACROS_H
43#include <sys/sysmacros.h>
44#endif
45
46#include "types.h"
47#include "debug.h"
48#include "attrib.h"
49#include "inode.h"
50#include "dir.h"
51#include "volume.h"
52#include "mft.h"
53#include "index.h"
54#include "ntfstime.h"
55#include "lcnalloc.h"
56#include "logging.h"
57#include "misc.h"
58#include "security.h"
59
60/*
61 * The little endian Unicode strings "$I30", "$SII", "$SDH", "$O"
62 *  and "$Q" as global constants.
63 */
64ntfschar NTFS_INDEX_I30[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('I'),
65		const_cpu_to_le16('3'), const_cpu_to_le16('0'),
66		const_cpu_to_le16('\0') };
67ntfschar NTFS_INDEX_SII[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('S'),
68		const_cpu_to_le16('I'), const_cpu_to_le16('I'),
69		const_cpu_to_le16('\0') };
70ntfschar NTFS_INDEX_SDH[5] = { const_cpu_to_le16('$'), const_cpu_to_le16('S'),
71		const_cpu_to_le16('D'), const_cpu_to_le16('H'),
72		const_cpu_to_le16('\0') };
73ntfschar NTFS_INDEX_O[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('O'),
74		const_cpu_to_le16('\0') };
75ntfschar NTFS_INDEX_Q[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('Q'),
76		const_cpu_to_le16('\0') };
77ntfschar NTFS_INDEX_R[3] = { const_cpu_to_le16('$'), const_cpu_to_le16('R'),
78		const_cpu_to_le16('\0') };
79
80/**
81 * ntfs_inode_lookup_by_name - find an inode in a directory given its name
82 * @dir_ni:	ntfs inode of the directory in which to search for the name
83 * @uname:	Unicode name for which to search in the directory
84 * @uname_len:	length of the name @uname in Unicode characters
85 *
86 * Look for an inode with name @uname in the directory with inode @dir_ni.
87 * ntfs_inode_lookup_by_name() walks the contents of the directory looking for
88 * the Unicode name. If the name is found in the directory, the corresponding
89 * inode number (>= 0) is returned as a mft reference in cpu format, i.e. it
90 * is a 64-bit number containing the sequence number.
91 *
92 * On error, return -1 with errno set to the error code. If the inode is is not
93 * found errno is ENOENT.
94 *
95 * Note, @uname_len does not include the (optional) terminating NULL character.
96 *
97 * Note, we look for a case sensitive match first but we also look for a case
98 * insensitive match at the same time. If we find a case insensitive match, we
99 * save that for the case that we don't find an exact match, where we return
100 * the mft reference of the case insensitive match.
101 *
102 * If the volume is mounted with the case sensitive flag set, then we only
103 * allow exact matches.
104 */
105u64 ntfs_inode_lookup_by_name(ntfs_inode *dir_ni, const ntfschar *uname,
106		const int uname_len)
107{
108	VCN vcn;
109	u64 mref = 0;
110	s64 br;
111	ntfs_volume *vol = dir_ni->vol;
112	ntfs_attr_search_ctx *ctx;
113	INDEX_ROOT *ir;
114	INDEX_ENTRY *ie;
115	INDEX_ALLOCATION *ia;
116	u8 *index_end;
117	ntfs_attr *ia_na;
118	int eo, rc;
119	u32 index_block_size, index_vcn_size;
120	u8 index_vcn_size_bits;
121
122	ntfs_log_trace("Entering\n");
123
124	if (!dir_ni || !dir_ni->mrec || !uname || uname_len <= 0) {
125		errno = EINVAL;
126		return -1;
127	}
128
129	ctx = ntfs_attr_get_search_ctx(dir_ni, NULL);
130	if (!ctx)
131		return -1;
132
133	/* Find the index root attribute in the mft record. */
134	if (ntfs_attr_lookup(AT_INDEX_ROOT, NTFS_INDEX_I30, 4, CASE_SENSITIVE, 0, NULL,
135			0, ctx)) {
136		ntfs_log_perror("Index root attribute missing in directory inode "
137				"%lld", (unsigned long long)dir_ni->mft_no);
138		goto put_err_out;
139	}
140	/* Get to the index root value. */
141	ir = (INDEX_ROOT*)((u8*)ctx->attr +
142			le16_to_cpu(ctx->attr->value_offset));
143	index_block_size = le32_to_cpu(ir->index_block_size);
144	if (index_block_size < NTFS_BLOCK_SIZE ||
145			index_block_size & (index_block_size - 1)) {
146		ntfs_log_error("Index block size %u is invalid.\n",
147				(unsigned)index_block_size);
148		goto put_err_out;
149	}
150	index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length);
151	/* The first index entry. */
152	ie = (INDEX_ENTRY*)((u8*)&ir->index +
153			le32_to_cpu(ir->index.entries_offset));
154	/*
155	 * Loop until we exceed valid memory (corruption case) or until we
156	 * reach the last entry.
157	 */
158	for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
159		/* Bounds checks. */
160		if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie +
161				sizeof(INDEX_ENTRY_HEADER) > index_end ||
162				(u8*)ie + le16_to_cpu(ie->key_length) >
163				index_end) {
164			ntfs_log_error("Index entry out of bounds in inode %lld"
165				       "\n", (unsigned long long)dir_ni->mft_no);
166			goto put_err_out;
167		}
168		/*
169		 * The last entry cannot contain a name. It can however contain
170		 * a pointer to a child node in the B+tree so we just break out.
171		 */
172		if (ie->ie_flags & INDEX_ENTRY_END)
173			break;
174
175		if (!le16_to_cpu(ie->length)) {
176			ntfs_log_error("Zero length index entry in inode %lld"
177				       "\n", (unsigned long long)dir_ni->mft_no);
178			goto put_err_out;
179		}
180		/*
181		 * Not a perfect match, need to do full blown collation so we
182		 * know which way in the B+tree we have to go.
183		 */
184		rc = ntfs_names_collate(uname, uname_len,
185				(ntfschar*)&ie->key.file_name.file_name,
186				ie->key.file_name.file_name_length, 1,
187				IGNORE_CASE, vol->upcase, vol->upcase_len);
188		/*
189		 * If uname collates before the name of the current entry, there
190		 * is definitely no such name in this index but we might need to
191		 * descend into the B+tree so we just break out of the loop.
192		 */
193		if (rc == -1)
194			break;
195		/* The names are not equal, continue the search. */
196		if (rc)
197			continue;
198		/*
199		 * Names match with case insensitive comparison, now try the
200		 * case sensitive comparison, which is required for proper
201		 * collation.
202		 */
203		rc = ntfs_names_collate(uname, uname_len,
204				(ntfschar*)&ie->key.file_name.file_name,
205				ie->key.file_name.file_name_length, 1,
206				CASE_SENSITIVE, vol->upcase, vol->upcase_len);
207		if (rc == -1)
208			break;
209		if (rc)
210			continue;
211		/*
212		 * Perfect match, this will never happen as the
213		 * ntfs_are_names_equal() call will have gotten a match but we
214		 * still treat it correctly.
215		 */
216		mref = le64_to_cpu(ie->indexed_file);
217		ntfs_attr_put_search_ctx(ctx);
218		return mref;
219	}
220	/*
221	 * We have finished with this index without success. Check for the
222	 * presence of a child node and if not present return error code
223	 * ENOENT, unless we have got the mft reference of a matching name
224	 * cached in mref in which case return mref.
225	 */
226	if (!(ie->ie_flags & INDEX_ENTRY_NODE)) {
227		ntfs_attr_put_search_ctx(ctx);
228		if (mref)
229			return mref;
230		ntfs_log_debug("Entry not found.\n");
231		errno = ENOENT;
232		return -1;
233	} /* Child node present, descend into it. */
234
235	/* Open the index allocation attribute. */
236	ia_na = ntfs_attr_open(dir_ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4);
237	if (!ia_na) {
238		ntfs_log_perror("Failed to open index allocation (inode %lld)",
239				(unsigned long long)dir_ni->mft_no);
240		goto put_err_out;
241	}
242
243	/* Allocate a buffer for the current index block. */
244	ia = ntfs_malloc(index_block_size);
245	if (!ia) {
246		ntfs_attr_close(ia_na);
247		goto put_err_out;
248	}
249
250	/* Determine the size of a vcn in the directory index. */
251	if (vol->cluster_size <= index_block_size) {
252		index_vcn_size = vol->cluster_size;
253		index_vcn_size_bits = vol->cluster_size_bits;
254	} else {
255		index_vcn_size = vol->sector_size;
256		index_vcn_size_bits = vol->sector_size_bits;
257	}
258
259	/* Get the starting vcn of the index_block holding the child node. */
260	vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8);
261
262descend_into_child_node:
263
264	/* Read the index block starting at vcn. */
265	br = ntfs_attr_mst_pread(ia_na, vcn << index_vcn_size_bits, 1,
266			index_block_size, ia);
267	if (br != 1) {
268		if (br != -1)
269			errno = EIO;
270		ntfs_log_perror("Failed to read vcn 0x%llx",
271			       	(unsigned long long)vcn);
272		goto close_err_out;
273	}
274
275	if (sle64_to_cpu(ia->index_block_vcn) != vcn) {
276		ntfs_log_error("Actual VCN (0x%llx) of index buffer is different "
277				"from expected VCN (0x%llx).\n",
278				(long long)sle64_to_cpu(ia->index_block_vcn),
279				(long long)vcn);
280		errno = EIO;
281		goto close_err_out;
282	}
283	if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) {
284		ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode 0x%llx "
285				"has a size (%u) differing from the directory "
286				"specified size (%u).\n", (long long)vcn,
287				(unsigned long long)dir_ni->mft_no,
288				(unsigned) le32_to_cpu(ia->index.allocated_size) + 0x18,
289				(unsigned)index_block_size);
290		errno = EIO;
291		goto close_err_out;
292	}
293	index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length);
294	if (index_end > (u8*)ia + index_block_size) {
295		ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode "
296				"0x%llx exceeds maximum size.\n",
297				(long long)vcn, (unsigned long long)dir_ni->mft_no);
298		errno = EIO;
299		goto close_err_out;
300	}
301
302	/* The first index entry. */
303	ie = (INDEX_ENTRY*)((u8*)&ia->index +
304			le32_to_cpu(ia->index.entries_offset));
305	/*
306	 * Iterate similar to above big loop but applied to index buffer, thus
307	 * loop until we exceed valid memory (corruption case) or until we
308	 * reach the last entry.
309	 */
310	for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
311		/* Bounds check. */
312		if ((u8*)ie < (u8*)ia || (u8*)ie +
313				sizeof(INDEX_ENTRY_HEADER) > index_end ||
314				(u8*)ie + le16_to_cpu(ie->key_length) >
315				index_end) {
316			ntfs_log_error("Index entry out of bounds in directory "
317				       "inode %lld.\n",
318				       (unsigned long long)dir_ni->mft_no);
319			errno = EIO;
320			goto close_err_out;
321		}
322		/*
323		 * The last entry cannot contain a name. It can however contain
324		 * a pointer to a child node in the B+tree so we just break out.
325		 */
326		if (ie->ie_flags & INDEX_ENTRY_END)
327			break;
328
329		if (!le16_to_cpu(ie->length)) {
330			errno = EIO;
331			ntfs_log_error("Zero length index entry in inode %lld"
332				       "\n", (unsigned long long)dir_ni->mft_no);
333			goto close_err_out;
334		}
335		/*
336		 * Not a perfect match, need to do full blown collation so we
337		 * know which way in the B+tree we have to go.
338		 */
339		rc = ntfs_names_collate(uname, uname_len,
340				(ntfschar*)&ie->key.file_name.file_name,
341				ie->key.file_name.file_name_length, 1,
342				IGNORE_CASE, vol->upcase, vol->upcase_len);
343		/*
344		 * If uname collates before the name of the current entry, there
345		 * is definitely no such name in this index but we might need to
346		 * descend into the B+tree so we just break out of the loop.
347		 */
348		if (rc == -1)
349			break;
350		/* The names are not equal, continue the search. */
351		if (rc)
352			continue;
353		/*
354		 * Names match with case insensitive comparison, now try the
355		 * case sensitive comparison, which is required for proper
356		 * collation.
357		 */
358		rc = ntfs_names_collate(uname, uname_len,
359				(ntfschar*)&ie->key.file_name.file_name,
360				ie->key.file_name.file_name_length, 1,
361				CASE_SENSITIVE, vol->upcase, vol->upcase_len);
362		if (rc == -1)
363			break;
364		if (rc)
365			continue;
366
367		mref = le64_to_cpu(ie->indexed_file);
368		free(ia);
369		ntfs_attr_close(ia_na);
370		ntfs_attr_put_search_ctx(ctx);
371		return mref;
372	}
373	/*
374	 * We have finished with this index buffer without success. Check for
375	 * the presence of a child node.
376	 */
377	if (ie->ie_flags & INDEX_ENTRY_NODE) {
378		if ((ia->index.ih_flags & NODE_MASK) == LEAF_NODE) {
379			ntfs_log_error("Index entry with child node found in a leaf "
380					"node in directory inode %lld.\n",
381					(unsigned long long)dir_ni->mft_no);
382			errno = EIO;
383			goto close_err_out;
384		}
385		/* Child node present, descend into it. */
386		vcn = sle64_to_cpup((u8*)ie + le16_to_cpu(ie->length) - 8);
387		if (vcn >= 0)
388			goto descend_into_child_node;
389		ntfs_log_error("Negative child node vcn in directory inode "
390			       "0x%llx.\n", (unsigned long long)dir_ni->mft_no);
391		errno = EIO;
392		goto close_err_out;
393	}
394	free(ia);
395	ntfs_attr_close(ia_na);
396	ntfs_attr_put_search_ctx(ctx);
397	/*
398	 * No child node present, return error code ENOENT, unless we have got
399	 * the mft reference of a matching name cached in mref in which case
400	 * return mref.
401	 */
402	if (mref)
403		return mref;
404	ntfs_log_debug("Entry not found.\n");
405	errno = ENOENT;
406	return -1;
407put_err_out:
408	eo = EIO;
409	ntfs_log_debug("Corrupt directory. Aborting lookup.\n");
410eo_put_err_out:
411	ntfs_attr_put_search_ctx(ctx);
412	errno = eo;
413	return -1;
414close_err_out:
415	eo = errno;
416	free(ia);
417	ntfs_attr_close(ia_na);
418	goto eo_put_err_out;
419}
420
421/**
422 * ntfs_pathname_to_inode - Find the inode which represents the given pathname
423 * @vol:       An ntfs volume obtained from ntfs_mount
424 * @parent:    A directory inode to begin the search (may be NULL)
425 * @pathname:  Pathname to be located
426 *
427 * Take an ASCII pathname and find the inode that represents it.  The function
428 * splits the path and then descends the directory tree.  If @parent is NULL,
429 * then the root directory '.' will be used as the base for the search.
430 *
431 * Return:  inode  Success, the pathname was valid
432 *	    NULL   Error, the pathname was invalid, or some other error occurred
433 */
434ntfs_inode *ntfs_pathname_to_inode(ntfs_volume *vol, ntfs_inode *parent,
435		const char *pathname)
436{
437	u64 inum;
438	int len, err = 0;
439	char *p, *q;
440	ntfs_inode *ni;
441	ntfs_inode *result = NULL;
442	ntfschar *unicode = NULL;
443	char *ascii = NULL;
444
445	if (!vol || !pathname) {
446		errno = EINVAL;
447		return NULL;
448	}
449
450	ntfs_log_trace("path: '%s'\n", pathname);
451
452	if (parent) {
453		ni = parent;
454	} else {
455		ni = ntfs_inode_open(vol, FILE_root);
456		if (!ni) {
457			ntfs_log_debug("Couldn't open the inode of the root "
458					"directory.\n");
459			err = EIO;
460			goto close;
461		}
462	}
463
464	ascii = strdup(pathname);
465	if (!ascii) {
466		ntfs_log_error("Out of memory.\n");
467		err = ENOMEM;
468		goto close;
469	}
470
471	p = ascii;
472	/* Remove leading /'s. */
473	while (p && *p && *p == PATH_SEP)
474		p++;
475	while (p && *p) {
476		/* Find the end of the first token. */
477		q = strchr(p, PATH_SEP);
478		if (q != NULL) {
479			*q = '\0';
480			q++;
481		}
482
483		len = ntfs_mbstoucs(p, &unicode);
484		if (len < 0) {
485			ntfs_log_perror("Could not convert filename to Unicode:"
486					" '%s'", p);
487			err = errno;
488			goto close;
489		} else if (len > NTFS_MAX_NAME_LEN) {
490			err = ENAMETOOLONG;
491			goto close;
492		}
493
494		inum = ntfs_inode_lookup_by_name(ni, unicode, len);
495		if (inum == (u64) -1) {
496			ntfs_log_debug("Couldn't find name '%s' in pathname "
497					"'%s'.\n", p, pathname);
498			err = ENOENT;
499			goto close;
500		}
501
502		if (ni != parent)
503			if (ntfs_inode_close(ni)) {
504				err = errno;
505				goto out;
506			}
507
508		inum = MREF(inum);
509		ni = ntfs_inode_open(vol, inum);
510		if (!ni) {
511			ntfs_log_debug("Cannot open inode %llu: %s.\n",
512					(unsigned long long)inum, p);
513			err = EIO;
514			goto close;
515		}
516
517		free(unicode);
518		unicode = NULL;
519
520		p = q;
521		while (p && *p && *p == PATH_SEP)
522			p++;
523	}
524
525	result = ni;
526	ni = NULL;
527close:
528	if (ni && (ni != parent))
529		if (ntfs_inode_close(ni) && !err)
530			err = errno;
531out:
532	free(ascii);
533	free(unicode);
534	if (err)
535		errno = err;
536	return result;
537}
538
539/*
540 * The little endian Unicode string ".." for ntfs_readdir().
541 */
542static const ntfschar dotdot[3] = { const_cpu_to_le16('.'),
543				   const_cpu_to_le16('.'),
544				   const_cpu_to_le16('\0') };
545
546/*
547 * union index_union -
548 * More helpers for ntfs_readdir().
549 */
550typedef union {
551	INDEX_ROOT *ir;
552	INDEX_ALLOCATION *ia;
553} index_union __attribute__((__transparent_union__));
554
555/**
556 * enum INDEX_TYPE -
557 * More helpers for ntfs_readdir().
558 */
559typedef enum {
560	INDEX_TYPE_ROOT,	/* index root */
561	INDEX_TYPE_ALLOCATION,	/* index allocation */
562} INDEX_TYPE;
563
564/**
565 * ntfs_filldir - ntfs specific filldir method
566 * @dir_ni:	ntfs inode of current directory
567 * @pos:	current position in directory
568 * @ivcn_bits:	log(2) of index vcn size
569 * @index_type:	specifies whether @iu is an index root or an index allocation
570 * @iu:		index root or index block to which @ie belongs
571 * @ie:		current index entry
572 * @dirent:	context for filldir callback supplied by the caller
573 * @filldir:	filldir callback supplied by the caller
574 *
575 * Pass information specifying the current directory entry @ie to the @filldir
576 * callback.
577 */
578static int ntfs_filldir(ntfs_inode *dir_ni, s64 *pos, u8 ivcn_bits,
579		const INDEX_TYPE index_type, index_union iu, INDEX_ENTRY *ie,
580		void *dirent, ntfs_filldir_t filldir)
581{
582	FILE_NAME_ATTR *fn = &ie->key.file_name;
583	unsigned dt_type;
584
585	ntfs_log_trace("Entering.\n");
586
587	/* Advance the position even if going to skip the entry. */
588	if (index_type == INDEX_TYPE_ALLOCATION)
589		*pos = (u8*)ie - (u8*)iu.ia + (sle64_to_cpu(
590				iu.ia->index_block_vcn) << ivcn_bits) +
591				dir_ni->vol->mft_record_size;
592	else /* if (index_type == INDEX_TYPE_ROOT) */
593		*pos = (u8*)ie - (u8*)iu.ir;
594	/* Skip root directory self reference entry. */
595	if (MREF_LE(ie->indexed_file) == FILE_root)
596		return 0;
597	if (ie->key.file_name.file_attributes & FILE_ATTR_I30_INDEX_PRESENT)
598		dt_type = NTFS_DT_DIR;
599	else if (fn->file_attributes & FILE_ATTR_SYSTEM)
600		dt_type = NTFS_DT_UNKNOWN;
601	else
602		dt_type = NTFS_DT_REG;
603	return filldir(dirent, fn->file_name, fn->file_name_length,
604			fn->file_name_type, *pos,
605			le64_to_cpu(ie->indexed_file), dt_type);
606}
607
608/**
609 * ntfs_mft_get_parent_ref - find mft reference of parent directory of an inode
610 * @ni:		ntfs inode whose parent directory to find
611 *
612 * Find the parent directory of the ntfs inode @ni. To do this, find the first
613 * file name attribute in the mft record of @ni and return the parent mft
614 * reference from that.
615 *
616 * Note this only makes sense for directories, since files can be hard linked
617 * from multiple directories and there is no way for us to tell which one is
618 * being looked for.
619 *
620 * Technically directories can have hard links, too, but we consider that as
621 * illegal as Linux/UNIX do not support directory hard links.
622 *
623 * Return the mft reference of the parent directory on success or -1 on error
624 * with errno set to the error code.
625 */
626static MFT_REF ntfs_mft_get_parent_ref(ntfs_inode *ni)
627{
628	MFT_REF mref;
629	ntfs_attr_search_ctx *ctx;
630	FILE_NAME_ATTR *fn;
631	int eo;
632
633	ntfs_log_trace("Entering.\n");
634
635	if (!ni) {
636		errno = EINVAL;
637		return ERR_MREF(-1);
638	}
639
640	ctx = ntfs_attr_get_search_ctx(ni, NULL);
641	if (!ctx)
642		return ERR_MREF(-1);
643	if (ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx)) {
644		ntfs_log_error("No file name found in inode %lld\n",
645			       (unsigned long long)ni->mft_no);
646		goto err_out;
647	}
648	if (ctx->attr->non_resident) {
649		ntfs_log_error("File name attribute must be resident (inode "
650			       "%lld)\n", (unsigned long long)ni->mft_no);
651		goto io_err_out;
652	}
653	fn = (FILE_NAME_ATTR*)((u8*)ctx->attr +
654			le16_to_cpu(ctx->attr->value_offset));
655	if ((u8*)fn +	le32_to_cpu(ctx->attr->value_length) >
656			(u8*)ctx->attr + le32_to_cpu(ctx->attr->length)) {
657		ntfs_log_error("Corrupt file name attribute in inode %lld.\n",
658			       (unsigned long long)ni->mft_no);
659		goto io_err_out;
660	}
661	mref = le64_to_cpu(fn->parent_directory);
662	ntfs_attr_put_search_ctx(ctx);
663	return mref;
664io_err_out:
665	errno = EIO;
666err_out:
667	eo = errno;
668	ntfs_attr_put_search_ctx(ctx);
669	errno = eo;
670	return ERR_MREF(-1);
671}
672
673/**
674 * ntfs_readdir - read the contents of an ntfs directory
675 * @dir_ni:	ntfs inode of current directory
676 * @pos:	current position in directory
677 * @dirent:	context for filldir callback supplied by the caller
678 * @filldir:	filldir callback supplied by the caller
679 *
680 * Parse the index root and the index blocks that are marked in use in the
681 * index bitmap and hand each found directory entry to the @filldir callback
682 * supplied by the caller.
683 *
684 * Return 0 on success or -1 on error with errno set to the error code.
685 *
686 * Note: Index blocks are parsed in ascending vcn order, from which follows
687 * that the directory entries are not returned sorted.
688 */
689int ntfs_readdir(ntfs_inode *dir_ni, s64 *pos,
690		void *dirent, ntfs_filldir_t filldir)
691{
692	s64 i_size, br, ia_pos, bmp_pos, ia_start;
693	ntfs_volume *vol;
694	ntfs_attr *ia_na, *bmp_na = NULL;
695	ntfs_attr_search_ctx *ctx = NULL;
696	u8 *index_end, *bmp = NULL;
697	INDEX_ROOT *ir;
698	INDEX_ENTRY *ie;
699	INDEX_ALLOCATION *ia = NULL;
700	int rc, ir_pos, bmp_buf_size, bmp_buf_pos, eo;
701	u32 index_block_size, index_vcn_size;
702	u8 index_block_size_bits, index_vcn_size_bits;
703
704	ntfs_log_trace("Entering.\n");
705
706	if (!dir_ni || !pos || !filldir) {
707		errno = EINVAL;
708		return -1;
709	}
710
711	if (!(dir_ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)) {
712		errno = ENOTDIR;
713		return -1;
714	}
715
716	vol = dir_ni->vol;
717
718	ntfs_log_trace("Entering for inode %lld, *pos 0x%llx.\n",
719			(unsigned long long)dir_ni->mft_no, (long long)*pos);
720
721	/* Open the index allocation attribute. */
722	ia_na = ntfs_attr_open(dir_ni, AT_INDEX_ALLOCATION, NTFS_INDEX_I30, 4);
723	if (!ia_na) {
724		if (errno != ENOENT) {
725			ntfs_log_perror("Failed to open index allocation attribute. "
726				"Directory inode %lld is corrupt or bug",
727				(unsigned long long)dir_ni->mft_no);
728			return -1;
729		}
730		i_size = 0;
731	} else
732		i_size = ia_na->data_size;
733
734	rc = 0;
735
736	/* Are we at end of dir yet? */
737	if (*pos >= i_size + vol->mft_record_size)
738		goto done;
739
740	/* Emulate . and .. for all directories. */
741	if (!*pos) {
742		rc = filldir(dirent, dotdot, 1, FILE_NAME_POSIX, *pos,
743				MK_MREF(dir_ni->mft_no,
744				le16_to_cpu(dir_ni->mrec->sequence_number)),
745				NTFS_DT_DIR);
746		if (rc)
747			goto err_out;
748		++*pos;
749	}
750	if (*pos == 1) {
751		MFT_REF parent_mref;
752
753		parent_mref = ntfs_mft_get_parent_ref(dir_ni);
754		if (parent_mref == ERR_MREF(-1)) {
755			ntfs_log_perror("Parent directory not found");
756			goto dir_err_out;
757		}
758
759		rc = filldir(dirent, dotdot, 2, FILE_NAME_POSIX, *pos,
760				parent_mref, NTFS_DT_DIR);
761		if (rc)
762			goto err_out;
763		++*pos;
764	}
765
766	ctx = ntfs_attr_get_search_ctx(dir_ni, NULL);
767	if (!ctx)
768		goto err_out;
769
770	/* Get the offset into the index root attribute. */
771	ir_pos = (int)*pos;
772	/* Find the index root attribute in the mft record. */
773	if (ntfs_attr_lookup(AT_INDEX_ROOT, NTFS_INDEX_I30, 4, CASE_SENSITIVE, 0, NULL,
774			0, ctx)) {
775		ntfs_log_perror("Index root attribute missing in directory inode "
776				"%lld", (unsigned long long)dir_ni->mft_no);
777		goto dir_err_out;
778	}
779	/* Get to the index root value. */
780	ir = (INDEX_ROOT*)((u8*)ctx->attr +
781			le16_to_cpu(ctx->attr->value_offset));
782
783	/* Determine the size of a vcn in the directory index. */
784	index_block_size = le32_to_cpu(ir->index_block_size);
785	if (index_block_size < NTFS_BLOCK_SIZE ||
786			index_block_size & (index_block_size - 1)) {
787		ntfs_log_error("Index block size %u is invalid.\n",
788				(unsigned)index_block_size);
789		goto dir_err_out;
790	}
791	index_block_size_bits = ffs(index_block_size) - 1;
792	if (vol->cluster_size <= index_block_size) {
793		index_vcn_size = vol->cluster_size;
794		index_vcn_size_bits = vol->cluster_size_bits;
795	} else {
796		index_vcn_size = vol->sector_size;
797		index_vcn_size_bits = vol->sector_size_bits;
798	}
799
800	/* Are we jumping straight into the index allocation attribute? */
801	if (*pos >= vol->mft_record_size) {
802		ntfs_attr_put_search_ctx(ctx);
803		ctx = NULL;
804		goto skip_index_root;
805	}
806
807	index_end = (u8*)&ir->index + le32_to_cpu(ir->index.index_length);
808	/* The first index entry. */
809	ie = (INDEX_ENTRY*)((u8*)&ir->index +
810			le32_to_cpu(ir->index.entries_offset));
811	/*
812	 * Loop until we exceed valid memory (corruption case) or until we
813	 * reach the last entry or until filldir tells us it has had enough
814	 * or signals an error (both covered by the rc test).
815	 */
816	for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
817		ntfs_log_debug("In index root, offset %d.\n", (int)((u8*)ie - (u8*)ir));
818		/* Bounds checks. */
819		if ((u8*)ie < (u8*)ctx->mrec || (u8*)ie +
820				sizeof(INDEX_ENTRY_HEADER) > index_end ||
821				(u8*)ie + le16_to_cpu(ie->key_length) >
822				index_end)
823			goto dir_err_out;
824		/* The last entry cannot contain a name. */
825		if (ie->ie_flags & INDEX_ENTRY_END)
826			break;
827
828		if (!le16_to_cpu(ie->length))
829			goto dir_err_out;
830
831		/* Skip index root entry if continuing previous readdir. */
832		if (ir_pos > (u8*)ie - (u8*)ir)
833			continue;
834		/*
835		 * Submit the directory entry to ntfs_filldir(), which will
836		 * invoke the filldir() callback as appropriate.
837		 */
838		rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits,
839				INDEX_TYPE_ROOT, ir, ie, dirent, filldir);
840		if (rc) {
841			ntfs_attr_put_search_ctx(ctx);
842			ctx = NULL;
843			goto err_out;
844		}
845	}
846	ntfs_attr_put_search_ctx(ctx);
847	ctx = NULL;
848
849	/* If there is no index allocation attribute we are finished. */
850	if (!ia_na)
851		goto EOD;
852
853	/* Advance *pos to the beginning of the index allocation. */
854	*pos = vol->mft_record_size;
855
856skip_index_root:
857
858	if (!ia_na)
859		goto done;
860
861	/* Allocate a buffer for the current index block. */
862	ia = ntfs_malloc(index_block_size);
863	if (!ia)
864		goto err_out;
865
866	bmp_na = ntfs_attr_open(dir_ni, AT_BITMAP, NTFS_INDEX_I30, 4);
867	if (!bmp_na) {
868		ntfs_log_perror("Failed to open index bitmap attribute");
869		goto dir_err_out;
870	}
871
872	/* Get the offset into the index allocation attribute. */
873	ia_pos = *pos - vol->mft_record_size;
874
875	bmp_pos = ia_pos >> index_block_size_bits;
876	if (bmp_pos >> 3 >= bmp_na->data_size) {
877		ntfs_log_error("Current index position exceeds index bitmap "
878				"size.\n");
879		goto dir_err_out;
880	}
881
882	bmp_buf_size = min(bmp_na->data_size - (bmp_pos >> 3), 4096);
883	bmp = ntfs_malloc(bmp_buf_size);
884	if (!bmp)
885		goto err_out;
886
887	br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp);
888	if (br != bmp_buf_size) {
889		if (br != -1)
890			errno = EIO;
891		ntfs_log_perror("Failed to read from index bitmap attribute");
892		goto err_out;
893	}
894
895	bmp_buf_pos = 0;
896	/* If the index block is not in use find the next one that is. */
897	while (!(bmp[bmp_buf_pos >> 3] & (1 << (bmp_buf_pos & 7)))) {
898find_next_index_buffer:
899		bmp_pos++;
900		bmp_buf_pos++;
901		/* If we have reached the end of the bitmap, we are done. */
902		if (bmp_pos >> 3 >= bmp_na->data_size)
903			goto EOD;
904		ia_pos = bmp_pos << index_block_size_bits;
905		if (bmp_buf_pos >> 3 < bmp_buf_size)
906			continue;
907		/* Read next chunk from the index bitmap. */
908		bmp_buf_pos = 0;
909		if ((bmp_pos >> 3) + bmp_buf_size > bmp_na->data_size)
910			bmp_buf_size = bmp_na->data_size - (bmp_pos >> 3);
911		br = ntfs_attr_pread(bmp_na, bmp_pos >> 3, bmp_buf_size, bmp);
912		if (br != bmp_buf_size) {
913			if (br != -1)
914				errno = EIO;
915			ntfs_log_perror("Failed to read from index bitmap attribute");
916			goto err_out;
917		}
918	}
919
920	ntfs_log_debug("Handling index block 0x%llx.\n", (long long)bmp_pos);
921
922	/* Read the index block starting at bmp_pos. */
923	br = ntfs_attr_mst_pread(ia_na, bmp_pos << index_block_size_bits, 1,
924			index_block_size, ia);
925	if (br != 1) {
926		if (br != -1)
927			errno = EIO;
928		ntfs_log_perror("Failed to read index block");
929		goto err_out;
930	}
931
932	ia_start = ia_pos & ~(s64)(index_block_size - 1);
933	if (sle64_to_cpu(ia->index_block_vcn) != ia_start >>
934			index_vcn_size_bits) {
935		ntfs_log_error("Actual VCN (0x%llx) of index buffer is different "
936				"from expected VCN (0x%llx) in inode 0x%llx.\n",
937				(long long)sle64_to_cpu(ia->index_block_vcn),
938				(long long)ia_start >> index_vcn_size_bits,
939				(unsigned long long)dir_ni->mft_no);
940		goto dir_err_out;
941	}
942	if (le32_to_cpu(ia->index.allocated_size) + 0x18 != index_block_size) {
943		ntfs_log_error("Index buffer (VCN 0x%llx) of directory inode %lld "
944				"has a size (%u) differing from the directory "
945				"specified size (%u).\n", (long long)ia_start >>
946				index_vcn_size_bits,
947				(unsigned long long)dir_ni->mft_no,
948				(unsigned) le32_to_cpu(ia->index.allocated_size)
949				+ 0x18, (unsigned)index_block_size);
950		goto dir_err_out;
951	}
952	index_end = (u8*)&ia->index + le32_to_cpu(ia->index.index_length);
953	if (index_end > (u8*)ia + index_block_size) {
954		ntfs_log_error("Size of index buffer (VCN 0x%llx) of directory inode "
955				"%lld exceeds maximum size.\n",
956				(long long)ia_start >> index_vcn_size_bits,
957				(unsigned long long)dir_ni->mft_no);
958		goto dir_err_out;
959	}
960	/* The first index entry. */
961	ie = (INDEX_ENTRY*)((u8*)&ia->index +
962			le32_to_cpu(ia->index.entries_offset));
963	/*
964	 * Loop until we exceed valid memory (corruption case) or until we
965	 * reach the last entry or until ntfs_filldir tells us it has had
966	 * enough or signals an error (both covered by the rc test).
967	 */
968	for (;; ie = (INDEX_ENTRY*)((u8*)ie + le16_to_cpu(ie->length))) {
969		ntfs_log_debug("In index allocation, offset 0x%llx.\n",
970				(long long)ia_start + ((u8*)ie - (u8*)ia));
971		/* Bounds checks. */
972		if ((u8*)ie < (u8*)ia || (u8*)ie +
973				sizeof(INDEX_ENTRY_HEADER) > index_end ||
974				(u8*)ie + le16_to_cpu(ie->key_length) >
975				index_end) {
976			ntfs_log_error("Index entry out of bounds in directory inode "
977				"%lld.\n", (unsigned long long)dir_ni->mft_no);
978			goto dir_err_out;
979		}
980		/* The last entry cannot contain a name. */
981		if (ie->ie_flags & INDEX_ENTRY_END)
982			break;
983
984		if (!le16_to_cpu(ie->length))
985			goto dir_err_out;
986
987		/* Skip index entry if continuing previous readdir. */
988		if (ia_pos - ia_start > (u8*)ie - (u8*)ia)
989			continue;
990		/*
991		 * Submit the directory entry to ntfs_filldir(), which will
992		 * invoke the filldir() callback as appropriate.
993		 */
994		rc = ntfs_filldir(dir_ni, pos, index_vcn_size_bits,
995				INDEX_TYPE_ALLOCATION, ia, ie, dirent, filldir);
996		if (rc)
997			goto err_out;
998	}
999	goto find_next_index_buffer;
1000EOD:
1001	/* We are finished, set *pos to EOD. */
1002	*pos = i_size + vol->mft_record_size;
1003done:
1004	free(ia);
1005	free(bmp);
1006	if (bmp_na)
1007		ntfs_attr_close(bmp_na);
1008	if (ia_na)
1009		ntfs_attr_close(ia_na);
1010	ntfs_log_debug("EOD, *pos 0x%llx, returning 0.\n", (long long)*pos);
1011	return 0;
1012dir_err_out:
1013	errno = EIO;
1014err_out:
1015	eo = errno;
1016	ntfs_log_trace("failed.\n");
1017	if (ctx)
1018		ntfs_attr_put_search_ctx(ctx);
1019	free(ia);
1020	free(bmp);
1021	if (bmp_na)
1022		ntfs_attr_close(bmp_na);
1023	if (ia_na)
1024		ntfs_attr_close(ia_na);
1025	errno = eo;
1026	return -1;
1027}
1028
1029
1030/**
1031 * __ntfs_create - create object on ntfs volume
1032 * @dir_ni:	ntfs inode for directory in which create new object
1033 * @name:	unicode name of new object
1034 * @name_len:	length of the name in unicode characters
1035 * @type:	type of the object to create
1036 * @dev:	major and minor device numbers (obtained from makedev())
1037 * @target:	target in unicode (only for symlinks)
1038 * @target_len:	length of target in unicode characters
1039 *
1040 * Internal, use ntfs_create{,_device,_symlink} wrappers instead.
1041 *
1042 * @type can be:
1043 *	S_IFREG		to create regular file
1044 *	S_IFDIR		to create directory
1045 *	S_IFBLK		to create block device
1046 *	S_IFCHR		to create character device
1047 *	S_IFLNK		to create symbolic link
1048 *	S_IFIFO		to create FIFO
1049 *	S_IFSOCK	to create socket
1050 * other values are invalid.
1051 *
1052 * @dev is used only if @type is S_IFBLK or S_IFCHR, in other cases its value
1053 * ignored.
1054 *
1055 * @target and @target_len are used only if @type is S_IFLNK, in other cases
1056 * their value ignored.
1057 *
1058 * Return opened ntfs inode that describes created object on success or NULL
1059 * on error with errno set to the error code.
1060 */
1061static ntfs_inode *__ntfs_create(ntfs_inode *dir_ni,
1062		ntfschar *name, u8 name_len, dev_t type, dev_t dev,
1063		ntfschar *target, int target_len)
1064{
1065	ntfs_inode *ni;
1066	int rollback_data = 0, rollback_sd = 0;
1067	FILE_NAME_ATTR *fn = NULL;
1068	STANDARD_INFORMATION *si = NULL;
1069	int err, fn_len, si_len;
1070
1071	ntfs_log_trace("Entering.\n");
1072
1073	/* Sanity checks. */
1074	if (!dir_ni || !name || !name_len) {
1075		ntfs_log_error("Invalid arguments.\n");
1076		errno = EINVAL;
1077		return NULL;
1078	}
1079
1080	if (dir_ni->flags & FILE_ATTR_REPARSE_POINT) {
1081		errno = EOPNOTSUPP;
1082		return NULL;
1083	}
1084
1085	ni = ntfs_mft_record_alloc(dir_ni->vol, NULL);
1086	if (!ni)
1087		return NULL;
1088	/*
1089	 * Create STANDARD_INFORMATION attribute. Write STANDARD_INFORMATION
1090	 * version 1.2, windows will upgrade it to version 3 if needed.
1091	 */
1092	si_len = offsetof(STANDARD_INFORMATION, v1_end);
1093	si = ntfs_calloc(si_len);
1094	if (!si) {
1095		err = errno;
1096		goto err_out;
1097	}
1098	si->creation_time = utc2ntfs(ni->creation_time);
1099	si->last_data_change_time = utc2ntfs(ni->last_data_change_time);
1100	si->last_mft_change_time = utc2ntfs(ni->last_mft_change_time);
1101	si->last_access_time = utc2ntfs(ni->last_access_time);
1102	if (!S_ISREG(type) && !S_ISDIR(type)) {
1103		si->file_attributes = FILE_ATTR_SYSTEM;
1104		ni->flags = FILE_ATTR_SYSTEM;
1105	}
1106	/* Add STANDARD_INFORMATION to inode. */
1107	if (ntfs_attr_add(ni, AT_STANDARD_INFORMATION, AT_UNNAMED, 0,
1108			(u8*)si, si_len)) {
1109		err = errno;
1110		ntfs_log_error("Failed to add STANDARD_INFORMATION "
1111				"attribute.\n");
1112		goto err_out;
1113	}
1114
1115	if (ntfs_sd_add_everyone(ni)) {
1116		err = errno;
1117		goto err_out;
1118	}
1119	rollback_sd = 1;
1120
1121	if (S_ISDIR(type)) {
1122		INDEX_ROOT *ir = NULL;
1123		INDEX_ENTRY *ie;
1124		int ir_len, index_len;
1125
1126		/* Create INDEX_ROOT attribute. */
1127		index_len = sizeof(INDEX_HEADER) + sizeof(INDEX_ENTRY_HEADER);
1128		ir_len = offsetof(INDEX_ROOT, index) + index_len;
1129		ir = ntfs_calloc(ir_len);
1130		if (!ir) {
1131			err = errno;
1132			goto err_out;
1133		}
1134		ir->type = AT_FILE_NAME;
1135		ir->collation_rule = COLLATION_FILE_NAME;
1136		ir->index_block_size = cpu_to_le32(ni->vol->indx_record_size);
1137		if (ni->vol->cluster_size <= ni->vol->indx_record_size)
1138			ir->clusters_per_index_block =
1139					ni->vol->indx_record_size >>
1140					ni->vol->cluster_size_bits;
1141		else
1142			ir->clusters_per_index_block =
1143					ni->vol->indx_record_size >>
1144					ni->vol->sector_size_bits;
1145		ir->index.entries_offset = cpu_to_le32(sizeof(INDEX_HEADER));
1146		ir->index.index_length = cpu_to_le32(index_len);
1147		ir->index.allocated_size = cpu_to_le32(index_len);
1148		ie = (INDEX_ENTRY*)((u8*)ir + sizeof(INDEX_ROOT));
1149		ie->length = cpu_to_le16(sizeof(INDEX_ENTRY_HEADER));
1150		ie->key_length = 0;
1151		ie->ie_flags = INDEX_ENTRY_END;
1152		/* Add INDEX_ROOT attribute to inode. */
1153		if (ntfs_attr_add(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4,
1154				(u8*)ir, ir_len)) {
1155			err = errno;
1156			free(ir);
1157			ntfs_log_error("Failed to add INDEX_ROOT attribute.\n");
1158			goto err_out;
1159		}
1160		free(ir);
1161	} else {
1162		INTX_FILE *data;
1163		int data_len;
1164
1165		switch (type) {
1166			case S_IFBLK:
1167			case S_IFCHR:
1168				data_len = offsetof(INTX_FILE, device_end);
1169				data = ntfs_malloc(data_len);
1170				if (!data) {
1171					err = errno;
1172					goto err_out;
1173				}
1174				data->major = cpu_to_le64(major(dev));
1175				data->minor = cpu_to_le64(minor(dev));
1176				if (type == S_IFBLK)
1177					data->magic = INTX_BLOCK_DEVICE;
1178				if (type == S_IFCHR)
1179					data->magic = INTX_CHARACTER_DEVICE;
1180				break;
1181			case S_IFLNK:
1182				data_len = sizeof(INTX_FILE_TYPES) +
1183						target_len * sizeof(ntfschar);
1184				data = ntfs_malloc(data_len);
1185				if (!data) {
1186					err = errno;
1187					goto err_out;
1188				}
1189				data->magic = INTX_SYMBOLIC_LINK;
1190				memcpy(data->target, target,
1191						target_len * sizeof(ntfschar));
1192				break;
1193			case S_IFSOCK:
1194				data = NULL;
1195				data_len = 1;
1196				break;
1197			default: /* FIFO or regular file. */
1198				data = NULL;
1199				data_len = 0;
1200				break;
1201		}
1202		/* Add DATA attribute to inode. */
1203		if (ntfs_attr_add(ni, AT_DATA, AT_UNNAMED, 0, (u8*)data,
1204				data_len)) {
1205			err = errno;
1206			ntfs_log_error("Failed to add DATA attribute.\n");
1207			free(data);
1208			goto err_out;
1209		}
1210		rollback_data = 1;
1211		free(data);
1212	}
1213	/* Create FILE_NAME attribute. */
1214	fn_len = sizeof(FILE_NAME_ATTR) + name_len * sizeof(ntfschar);
1215	fn = ntfs_calloc(fn_len);
1216	if (!fn) {
1217		err = errno;
1218		goto err_out;
1219	}
1220	fn->parent_directory = MK_LE_MREF(dir_ni->mft_no,
1221			le16_to_cpu(dir_ni->mrec->sequence_number));
1222	fn->file_name_length = name_len;
1223	fn->file_name_type = FILE_NAME_POSIX;
1224	if (S_ISDIR(type))
1225		fn->file_attributes = FILE_ATTR_I30_INDEX_PRESENT;
1226	if (!S_ISREG(type) && !S_ISDIR(type))
1227		fn->file_attributes = FILE_ATTR_SYSTEM;
1228	fn->creation_time = utc2ntfs(ni->creation_time);
1229	fn->last_data_change_time = utc2ntfs(ni->last_data_change_time);
1230	fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time);
1231	fn->last_access_time = utc2ntfs(ni->last_access_time);
1232	fn->data_size = cpu_to_sle64(ni->data_size);
1233	fn->allocated_size = cpu_to_sle64(ni->allocated_size);
1234	memcpy(fn->file_name, name, name_len * sizeof(ntfschar));
1235	/* Add FILE_NAME attribute to inode. */
1236	if (ntfs_attr_add(ni, AT_FILE_NAME, AT_UNNAMED, 0, (u8*)fn, fn_len)) {
1237		err = errno;
1238		ntfs_log_error("Failed to add FILE_NAME attribute.\n");
1239		goto err_out;
1240	}
1241	/* Add FILE_NAME attribute to index. */
1242	if (ntfs_index_add_filename(dir_ni, fn, MK_MREF(ni->mft_no,
1243			le16_to_cpu(ni->mrec->sequence_number)))) {
1244		err = errno;
1245		ntfs_log_perror("Failed to add entry to the index");
1246		goto err_out;
1247	}
1248	/* Set hard links count and directory flag. */
1249	ni->mrec->link_count = cpu_to_le16(1);
1250	if (S_ISDIR(type))
1251		ni->mrec->flags |= MFT_RECORD_IS_DIRECTORY;
1252	ntfs_inode_mark_dirty(ni);
1253	/* Done! */
1254	free(fn);
1255	free(si);
1256	ntfs_log_trace("Done.\n");
1257	return ni;
1258err_out:
1259	ntfs_log_trace("Failed.\n");
1260
1261	if (rollback_sd)
1262		ntfs_attr_remove(ni, AT_SECURITY_DESCRIPTOR, AT_UNNAMED, 0);
1263
1264	if (rollback_data)
1265		ntfs_attr_remove(ni, AT_DATA, AT_UNNAMED, 0);
1266	/*
1267	 * Free extent MFT records (should not exist any with current
1268	 * ntfs_create implementation, but for any case if something will be
1269	 * changed in the future).
1270	 */
1271	while (ni->nr_extents)
1272		if (ntfs_mft_record_free(ni->vol, *(ni->extent_nis))) {
1273			err = errno;
1274			ntfs_log_error("Failed to free extent MFT record.  "
1275					"Leaving inconsistent metadata.\n");
1276		}
1277	if (ntfs_mft_record_free(ni->vol, ni))
1278		ntfs_log_error("Failed to free MFT record.  "
1279				"Leaving inconsistent metadata. Run chkdsk.\n");
1280	free(fn);
1281	free(si);
1282	errno = err;
1283	return NULL;
1284}
1285
1286/**
1287 * Some wrappers around __ntfs_create() ...
1288 */
1289
1290ntfs_inode *ntfs_create(ntfs_inode *dir_ni, ntfschar *name, u8 name_len,
1291		dev_t type)
1292{
1293	if (type != S_IFREG && type != S_IFDIR && type != S_IFIFO &&
1294			type != S_IFSOCK) {
1295		ntfs_log_error("Invalid arguments.\n");
1296		return NULL;
1297	}
1298	return __ntfs_create(dir_ni, name, name_len, type, 0, NULL, 0);
1299}
1300
1301ntfs_inode *ntfs_create_device(ntfs_inode *dir_ni, ntfschar *name, u8 name_len,
1302		dev_t type, dev_t dev)
1303{
1304	if (type != S_IFCHR && type != S_IFBLK) {
1305		ntfs_log_error("Invalid arguments.\n");
1306		return NULL;
1307	}
1308	return __ntfs_create(dir_ni, name, name_len, type, dev, NULL, 0);
1309}
1310
1311ntfs_inode *ntfs_create_symlink(ntfs_inode *dir_ni, ntfschar *name, u8 name_len,
1312		ntfschar *target, int target_len)
1313{
1314	if (!target || !target_len) {
1315		ntfs_log_error("%s: Invalid argument (%p, %d)\n", __FUNCTION__,
1316			       target, target_len);
1317		return NULL;
1318	}
1319	return __ntfs_create(dir_ni, name, name_len, S_IFLNK, 0,
1320			target, target_len);
1321}
1322
1323int ntfs_check_empty_dir(ntfs_inode *ni)
1324{
1325	ntfs_attr *na;
1326	int ret = 0;
1327
1328	if (!(ni->mrec->flags & MFT_RECORD_IS_DIRECTORY))
1329		return 0;
1330
1331	na = ntfs_attr_open(ni, AT_INDEX_ROOT, NTFS_INDEX_I30, 4);
1332	if (!na) {
1333		errno = EIO;
1334		ntfs_log_perror("Failed to open directory");
1335		return -1;
1336	}
1337
1338	/* Non-empty directory? */
1339	if ((na->data_size != sizeof(INDEX_ROOT) + sizeof(INDEX_ENTRY_HEADER))){
1340		/* Both ENOTEMPTY and EEXIST are ok. We use the more common. */
1341		errno = ENOTEMPTY;
1342		ntfs_log_debug("Directory is not empty\n");
1343		ret = -1;
1344	}
1345
1346	ntfs_attr_close(na);
1347	return ret;
1348}
1349
1350static int ntfs_check_unlinkable_dir(ntfs_inode *ni, FILE_NAME_ATTR *fn)
1351{
1352	int link_count = le16_to_cpu(ni->mrec->link_count);
1353	int ret;
1354
1355	ret = ntfs_check_empty_dir(ni);
1356	if (!ret || errno != ENOTEMPTY)
1357		return ret;
1358	/*
1359	 * Directory is non-empty, so we can unlink only if there is more than
1360	 * one "real" hard link, i.e. links aren't different DOS and WIN32 names
1361	 */
1362	if ((link_count == 1) ||
1363	    (link_count == 2 && fn->file_name_type == FILE_NAME_DOS)) {
1364		errno = ENOTEMPTY;
1365		ntfs_log_debug("Non-empty directory without hard links\n");
1366		goto no_hardlink;
1367	}
1368
1369	ret = 0;
1370no_hardlink:
1371	return ret;
1372}
1373
1374/**
1375 * ntfs_delete - delete file or directory from ntfs volume
1376 * @ni:		ntfs inode for object to delte
1377 * @dir_ni:	ntfs inode for directory in which delete object
1378 * @name:	unicode name of the object to delete
1379 * @name_len:	length of the name in unicode characters
1380 *
1381 * @ni is always closed after the call to this function (even if it failed),
1382 * user does not need to call ntfs_inode_close himself.
1383 *
1384 * Return 0 on success or -1 on error with errno set to the error code.
1385 */
1386int ntfs_delete(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len)
1387{
1388	ntfs_attr_search_ctx *actx = NULL;
1389	FILE_NAME_ATTR *fn = NULL;
1390	BOOL looking_for_dos_name = FALSE, looking_for_win32_name = FALSE;
1391	BOOL case_sensitive_match = TRUE;
1392	int err = 0;
1393
1394	ntfs_log_trace("Entering.\n");
1395
1396	if (!ni || !dir_ni || !name || !name_len) {
1397		ntfs_log_error("Invalid arguments.\n");
1398		errno = EINVAL;
1399		goto err_out;
1400	}
1401	if (ni->nr_extents == -1)
1402		ni = ni->base_ni;
1403	if (dir_ni->nr_extents == -1)
1404		dir_ni = dir_ni->base_ni;
1405	/*
1406	 * Search for FILE_NAME attribute with such name. If it's in POSIX or
1407	 * WIN32_AND_DOS namespace, then simply remove it from index and inode.
1408	 * If filename in DOS or in WIN32 namespace, then remove DOS name first,
1409	 * only then remove WIN32 name.
1410	 */
1411	actx = ntfs_attr_get_search_ctx(ni, NULL);
1412	if (!actx)
1413		goto err_out;
1414search:
1415	while (!ntfs_attr_lookup(AT_FILE_NAME, AT_UNNAMED, 0, CASE_SENSITIVE,
1416			0, NULL, 0, actx)) {
1417		char *s;
1418		BOOL case_sensitive = IGNORE_CASE;
1419
1420		errno = 0;
1421		fn = (FILE_NAME_ATTR*)((u8*)actx->attr +
1422				le16_to_cpu(actx->attr->value_offset));
1423		s = ntfs_attr_name_get(fn->file_name, fn->file_name_length);
1424		ntfs_log_trace("name: '%s'  type: %d  dos: %d  win32: %d  "
1425			       "case: %d\n", s, fn->file_name_type,
1426			       looking_for_dos_name, looking_for_win32_name,
1427			       case_sensitive_match);
1428		ntfs_attr_name_free(&s);
1429		if (looking_for_dos_name) {
1430			if (fn->file_name_type == FILE_NAME_DOS)
1431				break;
1432			else
1433				continue;
1434		}
1435		if (looking_for_win32_name) {
1436			if  (fn->file_name_type == FILE_NAME_WIN32)
1437				break;
1438			else
1439				continue;
1440		}
1441
1442		/* Ignore hard links from other directories */
1443		if (dir_ni->mft_no != MREF_LE(fn->parent_directory)) {
1444			ntfs_log_debug("MFT record numbers don't match "
1445				       "(%llu != %llu)\n",
1446				       (long long unsigned)dir_ni->mft_no,
1447				       (long long unsigned)MREF_LE(fn->parent_directory));
1448			continue;
1449		}
1450
1451		if (fn->file_name_type == FILE_NAME_POSIX || case_sensitive_match)
1452			case_sensitive = CASE_SENSITIVE;
1453
1454		if (ntfs_names_are_equal(fn->file_name, fn->file_name_length,
1455					 name, name_len, case_sensitive,
1456					 ni->vol->upcase, ni->vol->upcase_len)){
1457
1458			if (fn->file_name_type == FILE_NAME_WIN32) {
1459				looking_for_dos_name = TRUE;
1460				ntfs_attr_reinit_search_ctx(actx);
1461				continue;
1462			}
1463			if (fn->file_name_type == FILE_NAME_DOS)
1464				looking_for_dos_name = TRUE;
1465			break;
1466		}
1467	}
1468	if (errno) {
1469		/*
1470		 * If case sensitive search failed, then try once again
1471		 * ignoring case.
1472		 */
1473		if (errno == ENOENT && case_sensitive_match) {
1474			case_sensitive_match = FALSE;
1475			ntfs_attr_reinit_search_ctx(actx);
1476			goto search;
1477		}
1478		goto err_out;
1479	}
1480
1481	if (ntfs_check_unlinkable_dir(ni, fn) < 0)
1482		goto err_out;
1483
1484	if (ntfs_index_remove(dir_ni, fn, le32_to_cpu(actx->attr->value_length)))
1485		goto err_out;
1486
1487	if (ntfs_attr_record_rm(actx))
1488		goto err_out;
1489
1490	ni->mrec->link_count = cpu_to_le16(le16_to_cpu(
1491			ni->mrec->link_count) - 1);
1492
1493	ntfs_inode_mark_dirty(ni);
1494	if (looking_for_dos_name) {
1495		looking_for_dos_name = FALSE;
1496		looking_for_win32_name = TRUE;
1497		ntfs_attr_reinit_search_ctx(actx);
1498		goto search;
1499	}
1500	/* TODO: Update object id, quota and securiry indexes if required. */
1501	/*
1502	 * If hard link count is not equal to zero then we are done. In other
1503	 * case there are no reference to this inode left, so we should free all
1504	 * non-resident attributes and mark all MFT record as not in use.
1505	 */
1506	if (ni->mrec->link_count) {
1507		ntfs_inode_update_times(ni, NTFS_UPDATE_CTIME);
1508		goto ok;
1509	}
1510	ntfs_attr_reinit_search_ctx(actx);
1511	while (!ntfs_attrs_walk(actx)) {
1512		if (actx->attr->non_resident) {
1513			runlist *rl;
1514
1515			rl = ntfs_mapping_pairs_decompress(ni->vol, actx->attr,
1516					NULL);
1517			if (!rl) {
1518				err = errno;
1519				ntfs_log_error("Failed to decompress runlist.  "
1520						"Leaving inconsistent metadata.\n");
1521				continue;
1522			}
1523			if (ntfs_cluster_free_from_rl(ni->vol, rl)) {
1524				err = errno;
1525				ntfs_log_error("Failed to free clusters.  "
1526						"Leaving inconsistent metadata.\n");
1527				continue;
1528			}
1529			free(rl);
1530		}
1531	}
1532	if (errno != ENOENT) {
1533		err = errno;
1534		ntfs_log_error("Attribute enumeration failed.  "
1535				"Probably leaving inconsistent metadata.\n");
1536	}
1537	/* All extents should be attached after attribute walk. */
1538	while (ni->nr_extents)
1539		if (ntfs_mft_record_free(ni->vol, *(ni->extent_nis))) {
1540			err = errno;
1541			ntfs_log_error("Failed to free extent MFT record.  "
1542					"Leaving inconsistent metadata.\n");
1543		}
1544	if (ntfs_mft_record_free(ni->vol, ni)) {
1545		err = errno;
1546		ntfs_log_error("Failed to free base MFT record.  "
1547				"Leaving inconsistent metadata.\n");
1548	}
1549	ni = NULL;
1550ok:
1551	ntfs_inode_update_times(dir_ni, NTFS_UPDATE_MCTIME);
1552out:
1553	if (actx)
1554		ntfs_attr_put_search_ctx(actx);
1555	if (ntfs_inode_close(dir_ni) && !err)
1556		err = errno;
1557	if (ntfs_inode_close(ni) && !err)
1558		err = errno;
1559	if (err) {
1560		errno = err;
1561		ntfs_log_debug("Could not delete file: %s\n", strerror(errno));
1562		return -1;
1563	}
1564	ntfs_log_trace("Done.\n");
1565	return 0;
1566err_out:
1567	err = errno;
1568	goto out;
1569}
1570
1571/**
1572 * ntfs_link - create hard link for file or directory
1573 * @ni:		ntfs inode for object to create hard link
1574 * @dir_ni:	ntfs inode for directory in which new link should be placed
1575 * @name:	unicode name of the new link
1576 * @name_len:	length of the name in unicode characters
1577 *
1578 * NOTE: At present we allow creating hardlinks to directories, we use them
1579 * in a temporary state during rename. But it's defenitely bad idea to have
1580 * hard links to directories as a result of operation.
1581 * FIXME: Create internal  __ntfs_link that allows hard links to a directories
1582 * and external ntfs_link that do not. Write ntfs_rename that uses __ntfs_link.
1583 *
1584 * Return 0 on success or -1 on error with errno set to the error code.
1585 */
1586int ntfs_link(ntfs_inode *ni, ntfs_inode *dir_ni, ntfschar *name, u8 name_len)
1587{
1588	FILE_NAME_ATTR *fn = NULL;
1589	int fn_len, err;
1590
1591	ntfs_log_trace("Entering.\n");
1592
1593	if (!ni || !dir_ni || !name || !name_len ||
1594			ni->mft_no == dir_ni->mft_no) {
1595		err = EINVAL;
1596		ntfs_log_perror("ntfs_link wrong arguments");
1597		goto err_out;
1598	}
1599
1600	if (ni->flags & FILE_ATTR_REPARSE_POINT) {
1601		err = EOPNOTSUPP;
1602		goto err_out;
1603	}
1604
1605	/* Create FILE_NAME attribute. */
1606	fn_len = sizeof(FILE_NAME_ATTR) + name_len * sizeof(ntfschar);
1607	fn = ntfs_calloc(fn_len);
1608	if (!fn) {
1609		err = errno;
1610		goto err_out;
1611	}
1612	fn->parent_directory = MK_LE_MREF(dir_ni->mft_no,
1613			le16_to_cpu(dir_ni->mrec->sequence_number));
1614	fn->file_name_length = name_len;
1615	fn->file_name_type = FILE_NAME_POSIX;
1616	fn->file_attributes = ni->flags;
1617	if (ni->mrec->flags & MFT_RECORD_IS_DIRECTORY)
1618		fn->file_attributes |= FILE_ATTR_I30_INDEX_PRESENT;
1619	fn->allocated_size = cpu_to_sle64(ni->allocated_size);
1620	fn->data_size = cpu_to_sle64(ni->data_size);
1621	fn->creation_time = utc2ntfs(ni->creation_time);
1622	fn->last_data_change_time = utc2ntfs(ni->last_data_change_time);
1623	fn->last_mft_change_time = utc2ntfs(ni->last_mft_change_time);
1624	fn->last_access_time = utc2ntfs(ni->last_access_time);
1625	memcpy(fn->file_name, name, name_len * sizeof(ntfschar));
1626	/* Add FILE_NAME attribute to index. */
1627	if (ntfs_index_add_filename(dir_ni, fn, MK_MREF(ni->mft_no,
1628			le16_to_cpu(ni->mrec->sequence_number)))) {
1629		err = errno;
1630		ntfs_log_perror("Failed to add filename to the index");
1631		goto err_out;
1632	}
1633	/* Add FILE_NAME attribute to inode. */
1634	if (ntfs_attr_add(ni, AT_FILE_NAME, AT_UNNAMED, 0, (u8*)fn, fn_len)) {
1635		ntfs_log_error("Failed to add FILE_NAME attribute.\n");
1636		err = errno;
1637		/* Try to remove just added attribute from index. */
1638		if (ntfs_index_remove(dir_ni, fn, fn_len))
1639			goto rollback_failed;
1640		goto err_out;
1641	}
1642	/* Increment hard links count. */
1643	ni->mrec->link_count = cpu_to_le16(le16_to_cpu(
1644			ni->mrec->link_count) + 1);
1645	/* Done! */
1646	ntfs_inode_mark_dirty(ni);
1647	free(fn);
1648	ntfs_log_trace("Done.\n");
1649	return 0;
1650rollback_failed:
1651	ntfs_log_error("Rollback failed. Leaving inconsistent metadata.\n");
1652err_out:
1653	free(fn);
1654	errno = err;
1655	return -1;
1656}
1657
1658