nsURLHelperUnix.cpp (2579B)
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim:set ts=4 sw=2 et cindent: */ 3 /* This Source Code Form is subject to the terms of the Mozilla Public 4 * License, v. 2.0. If a copy of the MPL was not distributed with this 5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 /* Unix-specific local file uri parsing */ 8 #include "nsURLHelper.h" 9 #include "nsEscape.h" 10 #include "nsIFile.h" 11 #include "nsNativeCharsetUtils.h" 12 #include "mozilla/Utf8.h" 13 14 using mozilla::IsUtf8; 15 16 nsresult net_GetURLSpecFromActualFile(nsIFile* aFile, nsACString& result) { 17 nsresult rv; 18 nsAutoCString nativePath, ePath; 19 nsAutoString path; 20 21 rv = aFile->GetNativePath(nativePath); 22 if (NS_FAILED(rv)) return rv; 23 24 // Convert to unicode and back to check correct conversion to native charset 25 NS_CopyNativeToUnicode(nativePath, path); 26 NS_CopyUnicodeToNative(path, ePath); 27 28 // Use UTF8 version if conversion was successful 29 if (nativePath == ePath) { 30 CopyUTF16toUTF8(path, ePath); 31 } else { 32 ePath = nativePath; 33 } 34 35 nsAutoCString escPath; 36 constexpr auto prefix = "file://"_ns; 37 38 // Escape the path with the directory mask 39 if (NS_EscapeURL(ePath.get(), -1, esc_Directory + esc_Forced, escPath)) { 40 escPath.Insert(prefix, 0); 41 } else { 42 escPath.Assign(prefix + ePath); 43 } 44 45 // esc_Directory does not escape the semicolons, so if a filename 46 // contains semicolons we need to manually escape them. 47 // This replacement should be removed in bug #473280 48 escPath.ReplaceSubstring(";", "%3b"); 49 result = escPath; 50 return NS_OK; 51 } 52 53 nsresult net_GetFileFromURLSpec(const nsACString& aURL, nsIFile** result) { 54 nsresult rv; 55 56 nsAutoCString directory, fileBaseName, fileExtension, path; 57 58 rv = net_ParseFileURL(aURL, directory, fileBaseName, fileExtension); 59 if (NS_FAILED(rv)) return rv; 60 61 if (!directory.IsEmpty()) { 62 rv = NS_EscapeURL(directory, esc_Directory | esc_AlwaysCopy, path, 63 mozilla::fallible); 64 if (NS_FAILED(rv)) return rv; 65 } 66 if (!fileBaseName.IsEmpty()) { 67 rv = NS_EscapeURL(fileBaseName, esc_FileBaseName | esc_AlwaysCopy, path, 68 mozilla::fallible); 69 if (NS_FAILED(rv)) return rv; 70 } 71 if (!fileExtension.IsEmpty()) { 72 path += '.'; 73 rv = NS_EscapeURL(fileExtension, esc_FileExtension | esc_AlwaysCopy, path, 74 mozilla::fallible); 75 if (NS_FAILED(rv)) return rv; 76 } 77 78 NS_UnescapeURL(path); 79 if (path.Length() != strlen(path.get())) return NS_ERROR_FILE_INVALID_PATH; 80 81 return NS_NewNativeLocalFile(path, result); 82 }