From 589bbdea7af00507d3dce26feec1c6db1d8e9746 Mon Sep 17 00:00:00 2001
From: "Erich E. Hoover" <erich.e.hoover@gmail.com>
Date: Thu, 16 Jan 2014 20:56:49 -0700
Subject: ntdll: Add support for junction point creation.

Signed-off-by: Erich E. Hoover <erich.e.hoover@gmail.com>
---
 configure.ac            |   2 +
 dlls/ntdll/file.c       | 118 ++++++++++++++++++++++++++++++++++++++++
 dlls/ntdll/tests/file.c | 101 ++++++++++++++++++++++++++++++++++
 include/Makefile.in     |   1 +
 include/ntifs.h         |  42 ++++++++++++++
 include/wine/port.h     |   9 +++
 libs/port/Makefile.in   |   1 +
 libs/port/renameat2.c   |  55 +++++++++++++++++++
 8 files changed, 329 insertions(+)
 create mode 100644 include/ntifs.h
 create mode 100644 libs/port/renameat2.c

diff --git a/configure.ac b/configure.ac
index 0ad8417735..39a9571a95 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2206,6 +2206,8 @@ AC_CHECK_FUNCS(\
 	pwrite \
 	readdir \
 	readlink \
+	renameat \
+	renameat2 \
 	sched_yield \
 	select \
 	setproctitle \
diff --git a/dlls/ntdll/file.c b/dlls/ntdll/file.c
index 3dafdcfb44..c0992ea657 100644
--- a/dlls/ntdll/file.c
+++ b/dlls/ntdll/file.c
@@ -21,6 +21,7 @@
 
 #include <stdlib.h>
 #include <string.h>
+#include <libgen.h>
 #include <stdio.h>
 #include <errno.h>
 #include <assert.h>
@@ -108,6 +109,7 @@
 #include "winioctl.h"
 #include "ddk/ntddk.h"
 #include "ddk/ntddser.h"
+#include "ntifs.h"
 
 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
 WINE_DECLARE_DEBUG_CHANNEL(winediag);
@@ -1648,6 +1650,104 @@ NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
 }
 
 
+/*
+ * Retrieve the unix name corresponding to a file handle, remove that directory, and then symlink the
+ * requested directory to the location of the old directory.
+ */
+NTSTATUS FILE_CreateSymlink(HANDLE handle, REPARSE_DATA_BUFFER *buffer)
+{
+    BOOL src_allocated = FALSE, dest_allocated = FALSE, tempdir_created = FALSE;
+    int dest_len = buffer->MountPointReparseBuffer.SubstituteNameLength;
+    int offset = buffer->MountPointReparseBuffer.SubstituteNameOffset;
+    WCHAR *dest = &buffer->MountPointReparseBuffer.PathBuffer[offset];
+    char tmpdir[PATH_MAX], tmplink[PATH_MAX], *d;
+    ANSI_STRING unix_src, unix_dest;
+    char magic_dest[PATH_MAX];
+    int dest_fd, needs_close;
+    UNICODE_STRING nt_dest;
+    NTSTATUS status;
+    int i;
+
+    if ((status = server_get_unix_fd( handle, FILE_SPECIAL_ACCESS, &dest_fd, &needs_close, NULL, NULL )))
+        return status;
+
+    if ((status = server_get_unix_name( handle, &unix_src )))
+        goto cleanup;
+    src_allocated = TRUE;
+    nt_dest.Buffer = dest;
+    nt_dest.Length = dest_len;
+    status = wine_nt_to_unix_file_name( &nt_dest, &unix_dest, 0, FALSE );
+    if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
+        goto cleanup;
+    dest_allocated = TRUE;
+
+    TRACE("Linking %s to %s\n", unix_src.Buffer, unix_dest.Buffer);
+
+    /* Encode the reparse tag into the symlink */
+    strcpy( magic_dest, "/" );
+    for (i = 0; i < sizeof(ULONG)*8; i++)
+    {
+        if ((buffer->ReparseTag >> i) & 1)
+            strcat( magic_dest, "." );
+        strcat( magic_dest, "/" );
+    }
+    strcat( magic_dest, unix_dest.Buffer );
+
+    /* Produce the link in a temporary location in the same folder */
+    strcpy( tmpdir, unix_src.Buffer );
+    d = dirname( tmpdir);
+    if (d != tmpdir) strcpy( tmpdir, d );
+    strcat( tmpdir, "/.winelink.XXXXXX" );
+    if (mkdtemp( tmpdir ) == NULL)
+    {
+        status = FILE_GetNtStatus();
+        goto cleanup;
+    }
+    tempdir_created = TRUE;
+    strcpy( tmplink, tmpdir );
+    strcat( tmplink, "/tmplink" );
+    if (symlink( magic_dest, tmplink ))
+    {
+        status = FILE_GetNtStatus();
+        goto cleanup;
+    }
+    /* Atomically move the link into position */
+    if (!renameat2( -1, tmplink, -1, unix_src.Buffer, RENAME_EXCHANGE ))
+    {
+        /* success: link and folder have switched locations */
+        rmdir( tmplink ); /* remove the folder (at link location) */
+    }
+    else if (errno == ENOSYS)
+    {
+        FIXME( "Atomic exchange of directory with symbolic link unsupported on this system, "
+               "using unsafe exchange instead.\n" );
+        if (rmdir( unix_src.Buffer ))
+        {
+            status = FILE_GetNtStatus();
+            goto cleanup;
+        }
+        if (rename( tmplink, unix_src.Buffer ))
+        {
+            status = FILE_GetNtStatus();
+            goto cleanup; /* not moved, orignal file/folder at destination is orphaned */
+        }
+    }
+    else
+    {
+        status = FILE_GetNtStatus();
+        goto cleanup;
+    }
+    status = STATUS_SUCCESS;
+
+cleanup:
+    if (tempdir_created) rmdir( tmpdir );
+    if (dest_allocated) RtlFreeAnsiString( &unix_dest );
+    if (src_allocated) RtlFreeAnsiString( &unix_src );
+    if (needs_close) close( dest_fd );
+    return status;
+}
+
+
 /**************************************************************************
  *              NtFsControlFile                 [NTDLL.@]
  *              ZwFsControlFile                 [NTDLL.@]
@@ -1732,6 +1832,24 @@ NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc
         io->Information = 0;
         status = STATUS_SUCCESS;
         break;
+
+    case FSCTL_SET_REPARSE_POINT:
+    {
+        REPARSE_DATA_BUFFER *buffer = (REPARSE_DATA_BUFFER *)in_buffer;
+
+        switch(buffer->ReparseTag)
+        {
+        case IO_REPARSE_TAG_MOUNT_POINT:
+            status = FILE_CreateSymlink( handle, buffer );
+            break;
+        default:
+            FIXME("stub: FSCTL_SET_REPARSE_POINT(%x)\n", buffer->ReparseTag);
+            status = STATUS_NOT_IMPLEMENTED;
+            break;
+        }
+        break;
+    }
+
     default:
         return server_ioctl_file( handle, event, apc, apc_context, io, code,
                                   in_buffer, in_size, out_buffer, out_size );
diff --git a/dlls/ntdll/tests/file.c b/dlls/ntdll/tests/file.c
index 8e54dbb541..322dadefe3 100644
--- a/dlls/ntdll/tests/file.c
+++ b/dlls/ntdll/tests/file.c
@@ -38,6 +38,7 @@
 #include "winuser.h"
 #include "winioctl.h"
 #include "winnls.h"
+#include "ntifs.h"
 
 #ifndef IO_COMPLETION_ALL_ACCESS
 #define IO_COMPLETION_ALL_ACCESS 0x001F0003
@@ -4831,6 +4832,105 @@ static void test_file_readonly_access(void)
     DeleteFileW(path);
 }
 
+static INT build_reparse_buffer(const WCHAR *filename, REPARSE_DATA_BUFFER **pbuffer)
+{
+    static INT header_size = offsetof(REPARSE_DATA_BUFFER, GenericReparseBuffer);
+    INT buffer_size, struct_size, data_size, string_len, prefix_len;
+    WCHAR *subst_dest, *print_dest;
+    REPARSE_DATA_BUFFER *buffer;
+
+    struct_size = offsetof(REPARSE_DATA_BUFFER, MountPointReparseBuffer.PathBuffer[0]);
+    prefix_len = strlen("\\??\\");
+    string_len = lstrlenW(&filename[prefix_len]);
+    data_size = (prefix_len + 2 * string_len + 2) * sizeof(WCHAR);
+    buffer_size = struct_size + data_size;
+    buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, buffer_size);
+    buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
+    buffer->ReparseDataLength = struct_size - header_size + data_size;
+    buffer->MountPointReparseBuffer.SubstituteNameLength = (prefix_len + string_len) * sizeof(WCHAR);
+    buffer->MountPointReparseBuffer.PrintNameOffset = (prefix_len + string_len + 1) * sizeof(WCHAR);
+    buffer->MountPointReparseBuffer.PrintNameLength = string_len * sizeof(WCHAR);
+    subst_dest = &buffer->MountPointReparseBuffer.PathBuffer[0];
+    print_dest = &buffer->MountPointReparseBuffer.PathBuffer[prefix_len + string_len + 1];
+    lstrcpyW(subst_dest, filename);
+    lstrcpyW(print_dest, &filename[prefix_len]);
+    *pbuffer = buffer;
+    return buffer_size;
+}
+
+static void test_reparse_points(void)
+{
+    static const WCHAR reparseW[] = {'\\','r','e','p','a','r','s','e',0};
+    WCHAR path[MAX_PATH], reparse_path[MAX_PATH], target_path[MAX_PATH];
+    static const WCHAR targetW[] = {'\\','t','a','r','g','e','t',0};
+    static const WCHAR fooW[] = {'f','o','o',0};
+    static WCHAR volW[] = {'c',':','\\',0};
+    static const WCHAR dotW[] = {'.',0};
+    REPARSE_DATA_BUFFER *buffer = NULL;
+    DWORD dwret, dwLen, dwFlags;
+    UNICODE_STRING nameW;
+    INT buffer_len;
+    HANDLE handle;
+    BOOL bret;
+
+    /* Create a temporary folder for the junction point tests */
+    GetTempFileNameW(dotW, fooW, 0, path);
+    DeleteFileW(path);
+    if (!CreateDirectoryW(path, NULL))
+    {
+        win_skip("Unable to create a temporary junction point directory.\n");
+        return;
+    }
+
+    /* Check that the volume this folder is located on supports junction points */
+    pRtlDosPathNameToNtPathName_U(path, &nameW, NULL, NULL);
+    volW[0] = nameW.Buffer[4];
+    pRtlFreeUnicodeString( &nameW );
+    GetVolumeInformationW(volW, 0, 0, 0, &dwLen, &dwFlags, 0, 0);
+    if (!(dwFlags & FILE_SUPPORTS_REPARSE_POINTS))
+    {
+        skip("File system does not support reparse points.\n");
+        RemoveDirectoryW(path);
+        return;
+    }
+
+    /* Create the folder to be replaced by a junction point */
+    lstrcpyW(reparse_path, path);
+    lstrcatW(reparse_path, reparseW);
+    bret = CreateDirectoryW(reparse_path, NULL);
+    ok(bret, "Failed to create junction point directory.\n");
+
+    /* Create a destination folder for the junction point to target */
+    lstrcpyW(target_path, path);
+    lstrcatW(target_path, targetW);
+    bret = CreateDirectoryW(target_path, NULL);
+    ok(bret, "Failed to create junction point target directory.\n");
+    pRtlDosPathNameToNtPathName_U(target_path, &nameW, NULL, NULL);
+
+    /* Create the junction point */
+    handle = CreateFileW(reparse_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
+                         FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, 0);
+    if (handle == INVALID_HANDLE_VALUE)
+    {
+        win_skip("Failed to open junction point directory handle (0x%x).\n", GetLastError());
+        goto cleanup;
+    }
+    buffer_len = build_reparse_buffer(nameW.Buffer, &buffer);
+    bret = DeviceIoControl(handle, FSCTL_SET_REPARSE_POINT, (LPVOID)buffer, buffer_len, NULL, 0, &dwret, 0);
+    ok(bret, "Failed to create junction point! (0x%x)\n", GetLastError());
+    CloseHandle(handle);
+
+cleanup:
+    /* Cleanup */
+    pRtlFreeUnicodeString(&nameW);
+    HeapFree(GetProcessHeap(), 0, buffer);
+    bret = RemoveDirectoryW(reparse_path);
+    todo_wine ok(bret, "Failed to remove temporary reparse point directory!\n");
+    bret = RemoveDirectoryW(target_path);
+    ok(bret, "Failed to remove temporary target directory!\n");
+    RemoveDirectoryW(path);
+}
+
 START_TEST(file)
 {
     HMODULE hkernel32 = GetModuleHandleA("kernel32.dll");
@@ -4900,4 +5000,5 @@ START_TEST(file)
     test_query_attribute_information_file();
     test_ioctl();
     test_flush_buffers_file();
+    test_reparse_points();
 }
diff --git a/include/Makefile.in b/include/Makefile.in
index 979695f552..2a1382e811 100644
--- a/include/Makefile.in
+++ b/include/Makefile.in
@@ -482,6 +482,7 @@ SOURCES = \
 	ntddvdeo.h \
 	ntdef.h \
 	ntdsapi.h \
+	ntifs.h \
 	ntlsa.h \
 	ntquery.h \
 	ntsecapi.h \
diff --git a/include/ntifs.h b/include/ntifs.h
new file mode 100644
index 0000000000..21d42e1732
--- /dev/null
+++ b/include/ntifs.h
@@ -0,0 +1,42 @@
+/*
+ * Win32 definitions for Windows NT
+ *
+ * Copyright 2012 Erich E. Hoover
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+#ifndef __WINE_NTIFS_H
+#define __WINE_NTIFS_H
+
+typedef struct _REPARSE_DATA_BUFFER {
+    ULONG  ReparseTag;
+    USHORT ReparseDataLength;
+    USHORT Reserved;
+    union {
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT SubstituteNameLength;
+            USHORT PrintNameOffset;
+            USHORT PrintNameLength;
+            WCHAR  PathBuffer[1];
+        } MountPointReparseBuffer;
+        struct {
+            UCHAR DataBuffer[1];
+        } GenericReparseBuffer;
+    };
+} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
+
+#endif /* __WINE_NTIFS_H */
diff --git a/include/wine/port.h b/include/wine/port.h
index d23e2b033f..26c5890ddb 100644
--- a/include/wine/port.h
+++ b/include/wine/port.h
@@ -317,6 +317,15 @@ double rint(double x);
 float rintf(float x);
 #endif
 
+#ifndef RENAME_EXCHANGE
+#define RENAME_EXCHANGE (1 << 1)
+#endif /* RENAME_EXCHANGE */
+
+#ifndef HAVE_RENAMEAT2
+int renameat2( int olddirfd, const char *oldpath, int newdirfd, const char *newpath,
+               unsigned int flags );
+#endif /* HAVE_RENAMEAT2 */
+
 #ifndef HAVE_STATVFS
 int statvfs( const char *path, struct statvfs *buf );
 #endif
diff --git a/libs/port/Makefile.in b/libs/port/Makefile.in
index a2e96d1500..db27249ac1 100644
--- a/libs/port/Makefile.in
+++ b/libs/port/Makefile.in
@@ -97,6 +97,7 @@ C_SRCS = \
 	pread.c \
 	pwrite.c \
 	readlink.c \
+	renameat2.c \
 	rint.c \
 	sortkey.c \
 	spawn.c \
diff --git a/libs/port/renameat2.c b/libs/port/renameat2.c
new file mode 100644
index 0000000000..f46f407ec7
--- /dev/null
+++ b/libs/port/renameat2.c
@@ -0,0 +1,55 @@
+/*
+ * renameat2 function
+ *
+ * Copyright 2015-2019 Erich E. Hoover
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+#include "config.h"
+#include "wine/port.h"
+
+#ifdef HAVE_SYS_SYSCALL_H
+# include <sys/syscall.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+
+#ifndef HAVE_RENAMEAT
+int renameat( int olddirfd, const char *oldpath, int newdirfd, const char *newpath )
+{
+    errno = ENOSYS;
+    return -1;
+}
+#endif
+
+#ifndef HAVE_RENAMEAT2
+int renameat2( int olddirfd, const char *oldpath, int newdirfd, const char *newpath,
+               unsigned int flags )
+{
+    if (flags == 0)
+        return renameat( olddirfd, oldpath, newdirfd, newpath );
+#if defined(__NR_renameat2)
+    return syscall( __NR_renameat2, olddirfd, oldpath, newdirfd, newpath, flags );
+#elif defined(RENAME_SWAP)
+    return renameatx_np(olddirfd, oldpath, newdirfd, newpath,
+                        (flags & RENAME_EXCHANGE ? RENAME_SWAP : 0));
+#else
+    errno = ENOSYS;
+    return -1;
+#endif
+}
+#endif /* HAVE_RENAMEAT2 */
-- 
2.17.1

