FileSystemUtils.cpp (2552B)
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */ 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 file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #include "mozilla/dom/FileSystemUtils.h" 8 9 #include "nsCharSeparatedTokenizer.h" 10 #include "nsIEventTarget.h" 11 #include "nsThreadUtils.h" 12 13 namespace mozilla::dom { 14 15 /* static */ 16 bool FileSystemUtils::IsDescendantPath(const nsAString& aPath, 17 const nsAString& aDescendantPath) { 18 // Check the sub-directory path to see if it has the parent path as prefix. 19 if (!aDescendantPath.Equals(aPath) && 20 !StringBeginsWith(aDescendantPath, aPath)) { 21 return false; 22 } 23 24 return true; 25 } 26 27 /* static */ 28 bool FileSystemUtils::IsValidRelativeDOMPath(const nsAString& aPath, 29 nsTArray<nsString>& aParts) { 30 // We don't allow empty relative path to access the root. 31 if (aPath.IsEmpty()) { 32 return false; 33 } 34 35 // Leading and trailing "/" are not allowed. 36 if (aPath.First() == FILESYSTEM_DOM_PATH_SEPARATOR_CHAR || 37 aPath.Last() == FILESYSTEM_DOM_PATH_SEPARATOR_CHAR) { 38 return false; 39 } 40 41 constexpr auto kCurrentDir = u"."_ns; 42 constexpr auto kParentDir = u".."_ns; 43 44 // Split path and check each path component. 45 for (const nsAString& pathComponent : 46 nsCharSeparatedTokenizerTemplate<NS_TokenizerIgnoreNothing>{ 47 aPath, FILESYSTEM_DOM_PATH_SEPARATOR_CHAR} 48 .ToRange()) { 49 // The path containing empty components, such as "foo//bar", is invalid. 50 // We don't allow paths, such as "../foo", "foo/./bar" and "foo/../bar", 51 // to walk up the directory. 52 if (pathComponent.IsEmpty() || pathComponent.Equals(kCurrentDir) || 53 pathComponent.Equals(kParentDir)) { 54 return false; 55 } 56 57 aParts.AppendElement(pathComponent); 58 } 59 60 return true; 61 } 62 63 /* static */ 64 nsresult FileSystemUtils::DispatchRunnable( 65 nsIGlobalObject* aGlobal, already_AddRefed<nsIRunnable>&& aRunnable) { 66 nsCOMPtr<nsIRunnable> runnable = aRunnable; 67 68 nsCOMPtr<nsIEventTarget> target; 69 if (!aGlobal) { 70 target = GetMainThreadSerialEventTarget(); 71 } else { 72 target = aGlobal->SerialEventTarget(); 73 } 74 75 MOZ_ASSERT(target); 76 77 nsresult rv = target->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL); 78 if (NS_WARN_IF(NS_FAILED(rv))) { 79 return rv; 80 } 81 82 return NS_OK; 83 } 84 85 } // namespace mozilla::dom