Move Windows safe file creation code into WebCore from WebPreferences
[WebKit-https.git] / WebCore / platform / win / FileSystemWin.cpp
index 25d3e4a82540ea8dc48fe204ba96d42c5ee88e92..cfba4ae96ac22fa9719b895d90eb5677f210546e 100644 (file)
@@ -163,5 +163,35 @@ String roamingUserSpecificStorageDirectory()
 {
     return cachedStorageDirectory(CSIDL_APPDATA);
 }
+
+bool safeCreateFile(const String& path, CFDataRef data)
+{
+    // Create a temporary file.
+    WCHAR tempDirPath[MAX_PATH];
+    if (!GetTempPathW(ARRAYSIZE(tempDirPath), tempDirPath))
+        return false;
+
+    WCHAR tempPath[MAX_PATH];
+    if (!GetTempFileNameW(tempDirPath, L"WEBKIT", 0, tempPath))
+        return false;
+
+    HANDLE tempFileHandle = CreateFileW(tempPath, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
+    if (tempFileHandle == INVALID_HANDLE_VALUE)
+        return false;
+
+    // Write the data to this temp file.
+    DWORD written;
+    if (!WriteFile(tempFileHandle, CFDataGetBytePtr(data), static_cast<DWORD>(CFDataGetLength(data)), &written, 0))
+        return false;
+
+    CloseHandle(tempFileHandle);
+
+    // Copy the temp file to the destination file.
+    String destination = path;
+    if (!MoveFileExW(tempPath, destination.charactersWithNullTermination(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
+        return false;
+
+    return true;
+}
 \r
 } // namespace WebCore\r