Bug 1932613 - temporarily disable browser_ml_end_to_end.js for permanent failures...
[gecko.git] / xpcom / io / nsLocalFileCommon.cpp
blob15be3648a78686fa23f1e515a2054622feaf914f
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
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsLocalFile.h" // includes platform-specific headers
9 #include "nsString.h"
10 #include "nsCOMPtr.h"
11 #include "nsReadableUtils.h"
12 #include "nsPrintfCString.h"
13 #include "nsCRT.h"
14 #include "nsNativeCharsetUtils.h"
15 #include "nsUTF8Utils.h"
16 #include "nsArray.h"
17 #include "nsLocalFileCommon.h"
19 #ifdef XP_WIN
20 # include <string.h>
21 #endif
23 // Extensions that should be considered 'executable', ie will not allow users
24 // to open immediately without first saving to disk, and potentially provoke
25 // other warnings. PLEASE read the longer comment in
26 // toolkit/components/reputationservice/ApplicationReputation.cpp
27 // before modifying this list!
28 // If you update this list, make sure to update the length of sExecutableExts
29 // in nsLocalFileCommmon.h.
30 /* static */
31 const char* const sExecutableExts[] = {
32 // clang-format off
33 ".accda", // MS Access database
34 ".accdb", // MS Access database
35 ".accde", // MS Access database
36 ".accdr", // MS Access database
37 ".ad",
38 ".ade", // access project extension
39 ".adp",
40 ".afploc", // Apple Filing Protocol Location
41 ".air", // Adobe AIR installer
42 ".app", // executable application
43 ".application", // from bug 348763
44 ".appref-ms", // ClickOnce link
45 ".appx",
46 ".appxbundle",
47 ".asp",
48 ".atloc", // Appletalk Location
49 ".bas",
50 ".bat",
51 ".cer", // Signed certificate file
52 ".chm",
53 ".cmd",
54 ".com",
55 ".cpl",
56 ".crt",
57 ".der",
58 ".diagcab", // Windows archive
59 ".exe",
60 ".fileloc", // Apple finder internet location data file
61 ".ftploc", // Apple FTP Location
62 ".fxp", // FoxPro compiled app
63 ".hlp",
64 ".hta",
65 ".inetloc", // Apple finder internet location data file
66 ".inf",
67 ".ins",
68 ".isp",
69 ".jar", // java application bundle
70 #ifndef MOZ_ESR
71 ".jnlp",
72 #endif
73 ".js",
74 ".jse",
75 ".library-ms", // Windows Library Files
76 ".lnk",
77 ".mad", // Access Module Shortcut
78 ".maf", // Access
79 ".mag", // Access Diagram Shortcut
80 ".mam", // Access Macro Shortcut
81 ".maq", // Access Query Shortcut
82 ".mar", // Access Report Shortcut
83 ".mas", // Access Stored Procedure
84 ".mat", // Access Table Shortcut
85 ".mau", // Media Attachment Unit
86 ".mav", // Access View Shortcut
87 ".maw", // Access Data Access Page
88 ".mda", // Access Add-in, MDA Access 2 Workgroup
89 ".mdb",
90 ".mde",
91 ".mdt", // Access Add-in Data
92 ".mdw", // Access Workgroup Information
93 ".mdz", // Access Wizard Template
94 ".msc",
95 ".msh", // Microsoft Shell
96 ".msh1", // Microsoft Shell
97 ".msh1xml", // Microsoft Shell
98 ".msh2", // Microsoft Shell
99 ".msh2xml", // Microsoft Shell
100 ".mshxml", // Microsoft Shell
101 ".msi",
102 ".msix",
103 ".msixbundle",
104 ".msp",
105 ".mst",
106 ".ops", // Office Profile Settings
107 ".pcd",
108 ".pif",
109 ".plg", // Developer Studio Build Log
110 ".prf", // windows system file
111 ".prg",
112 ".pst",
113 ".reg",
114 ".scf", // Windows explorer command
115 ".scr",
116 ".sct",
117 ".settingcontent-ms",
118 ".shb",
119 ".shs",
120 ".url",
121 ".vb",
122 ".vbe",
123 ".vbs",
124 ".vdx",
125 ".vsd",
126 ".vsdm",
127 ".vsdx",
128 ".vsmacros", // Visual Studio .NET Binary-based Macro Project
129 ".vss",
130 ".vssm",
131 ".vssx",
132 ".vst",
133 ".vstm",
134 ".vstx",
135 ".vsw",
136 ".vsx",
137 ".vtx",
138 ".webloc", // MacOS website location file
139 ".ws",
140 ".wsc",
141 ".wsf",
142 ".wsh",
143 ".xll", // MS Excel dynamic link library
144 ".xrm-ms"
145 // clang-format on
148 #if !defined(MOZ_WIDGET_COCOA) && !defined(XP_WIN)
149 NS_IMETHODIMP
150 nsLocalFile::InitWithFile(nsIFile* aFile) {
151 if (NS_WARN_IF(!aFile)) {
152 return NS_ERROR_INVALID_ARG;
155 nsAutoCString path;
156 aFile->GetNativePath(path);
157 if (path.IsEmpty()) {
158 return NS_ERROR_INVALID_ARG;
160 return InitWithNativePath(path);
162 #endif
164 #define kMaxFilenameLength 255
165 #define kMaxExtensionLength 100
166 #define kMaxSequenceNumberLength 5 // "-9999"
167 // requirement: kMaxExtensionLength <
168 // kMaxFilenameLength - kMaxSequenceNumberLength
170 NS_IMETHODIMP
171 nsLocalFile::CreateUnique(uint32_t aType, uint32_t aAttributes) {
172 nsresult rv;
173 bool longName;
175 #ifdef XP_WIN
176 nsAutoString pathName, leafName, rootName, suffix;
177 rv = GetPath(pathName);
178 #else
179 nsAutoCString pathName, leafName, rootName, suffix;
180 rv = GetNativePath(pathName);
181 #endif
182 if (NS_FAILED(rv)) {
183 return rv;
186 auto FailedBecauseExists = [&](nsresult aRv) {
187 if (aRv == NS_ERROR_FILE_ACCESS_DENIED) {
188 bool exists;
189 return NS_SUCCEEDED(Exists(&exists)) && exists;
191 return aRv == NS_ERROR_FILE_ALREADY_EXISTS;
194 longName =
195 (pathName.Length() + kMaxSequenceNumberLength > kMaxFilenameLength);
196 if (!longName) {
197 rv = Create(aType, aAttributes);
198 if (!FailedBecauseExists(rv)) {
199 return rv;
203 #ifdef XP_WIN
204 rv = GetLeafName(leafName);
205 if (NS_FAILED(rv)) {
206 return rv;
209 const int32_t lastDot = leafName.RFindChar(char16_t('.'));
210 #else
211 rv = GetNativeLeafName(leafName);
212 if (NS_FAILED(rv)) {
213 return rv;
216 const int32_t lastDot = leafName.RFindChar('.');
217 #endif
219 if (lastDot == kNotFound) {
220 rootName = leafName;
221 } else {
222 suffix = Substring(leafName, lastDot); // include '.'
223 rootName = Substring(leafName, 0, lastDot); // strip suffix and dot
226 if (longName) {
227 int32_t maxRootLength =
228 (kMaxFilenameLength - (pathName.Length() - leafName.Length()) -
229 suffix.Length() - kMaxSequenceNumberLength);
231 // We cannot create an item inside a directory whose name is too long.
232 // Also, ensure that at least one character remains after we truncate
233 // the root name, as we don't want to end up with an empty leaf name.
234 if (maxRootLength < 2) {
235 return NS_ERROR_FILE_UNRECOGNIZED_PATH;
238 #ifdef XP_WIN
239 // ensure that we don't cut the name in mid-UTF16-character
240 rootName.SetLength(NS_IS_LOW_SURROGATE(rootName[maxRootLength])
241 ? maxRootLength - 1
242 : maxRootLength);
243 SetLeafName(rootName + suffix);
244 #else
245 if (NS_IsNativeUTF8()) {
246 // ensure that we don't cut the name in mid-UTF8-character
247 // (assume the name is valid UTF8 to begin with)
248 while (UTF8traits::isInSeq(rootName[maxRootLength])) {
249 --maxRootLength;
252 // Another check to avoid ending up with an empty leaf name.
253 if (maxRootLength == 0 && suffix.IsEmpty()) {
254 return NS_ERROR_FILE_UNRECOGNIZED_PATH;
258 rootName.SetLength(maxRootLength);
259 SetNativeLeafName(rootName + suffix);
260 #endif
261 nsresult rvCreate = Create(aType, aAttributes);
262 if (!FailedBecauseExists(rvCreate)) {
263 return rvCreate;
267 for (int indx = 1; indx < 10000; ++indx) {
268 // start with "Picture-1.jpg" after "Picture.jpg" exists
269 #ifdef XP_WIN
270 SetLeafName(rootName +
271 NS_ConvertASCIItoUTF16(nsPrintfCString("-%d", indx)) + suffix);
272 #else
273 SetNativeLeafName(rootName + nsPrintfCString("-%d", indx) + suffix);
274 #endif
275 rv = Create(aType, aAttributes);
276 if (NS_SUCCEEDED(rv) || !FailedBecauseExists(rv)) {
277 return rv;
281 // The disk is full, sort of
282 return NS_ERROR_FILE_TOO_BIG;
285 #if defined(XP_WIN)
286 static const char16_t kPathSeparatorChar = '\\';
287 #elif defined(XP_UNIX)
288 static const char16_t kPathSeparatorChar = '/';
289 #else
290 # error Need to define file path separator for your platform
291 #endif
293 static void SplitPath(char16_t* aPath, nsTArray<char16_t*>& aNodeArray) {
294 if (*aPath == 0) {
295 return;
298 if (*aPath == kPathSeparatorChar) {
299 aPath++;
301 aNodeArray.AppendElement(aPath);
303 for (char16_t* cp = aPath; *cp != 0; ++cp) {
304 if (*cp == kPathSeparatorChar) {
305 *cp++ = 0;
306 if (*cp == 0) {
307 break;
309 aNodeArray.AppendElement(cp);
314 NS_IMETHODIMP
315 nsLocalFile::GetRelativeDescriptor(nsIFile* aFromFile, nsACString& aResult) {
316 if (NS_WARN_IF(!aFromFile)) {
317 return NS_ERROR_INVALID_ARG;
321 // aResult will be UTF-8 encoded
324 nsresult rv;
325 aResult.Truncate(0);
327 nsAutoString thisPath, fromPath;
328 AutoTArray<char16_t*, 32> thisNodes;
329 AutoTArray<char16_t*, 32> fromNodes;
331 rv = GetPath(thisPath);
332 if (NS_FAILED(rv)) {
333 return rv;
335 rv = aFromFile->GetPath(fromPath);
336 if (NS_FAILED(rv)) {
337 return rv;
340 // get raw pointer to mutable string buffer
341 char16_t* thisPathPtr = thisPath.BeginWriting();
342 char16_t* fromPathPtr = fromPath.BeginWriting();
344 SplitPath(thisPathPtr, thisNodes);
345 SplitPath(fromPathPtr, fromNodes);
347 size_t nodeIndex;
348 for (nodeIndex = 0;
349 nodeIndex < thisNodes.Length() && nodeIndex < fromNodes.Length();
350 ++nodeIndex) {
351 #ifdef XP_WIN
352 if (_wcsicmp(char16ptr_t(thisNodes[nodeIndex]),
353 char16ptr_t(fromNodes[nodeIndex]))) {
354 break;
356 #else
357 if (nsCRT::strcmp(thisNodes[nodeIndex], fromNodes[nodeIndex])) {
358 break;
360 #endif
363 size_t branchIndex = nodeIndex;
364 for (nodeIndex = branchIndex; nodeIndex < fromNodes.Length(); ++nodeIndex) {
365 aResult.AppendLiteral("../");
367 StringJoinAppend(aResult, "/"_ns, mozilla::Span{thisNodes}.From(branchIndex),
368 [](nsACString& dest, const auto& thisNode) {
369 // XXX(Bug 1682869) We wouldn't need to reconstruct a
370 // nsDependentString here if SplitPath already returned
371 // nsDependentString. In fact, it seems SplitPath might be
372 // replaced by ParseString?
373 AppendUTF16toUTF8(nsDependentString{thisNode}, dest);
376 return NS_OK;
379 NS_IMETHODIMP
380 nsLocalFile::SetRelativeDescriptor(nsIFile* aFromFile,
381 const nsACString& aRelativeDesc) {
382 constexpr auto kParentDirStr = "../"_ns;
384 nsCOMPtr<nsIFile> targetFile;
385 nsresult rv = aFromFile->Clone(getter_AddRefs(targetFile));
386 if (NS_FAILED(rv)) {
387 return rv;
391 // aRelativeDesc is UTF-8 encoded
394 nsCString::const_iterator strBegin, strEnd;
395 aRelativeDesc.BeginReading(strBegin);
396 aRelativeDesc.EndReading(strEnd);
398 nsCString::const_iterator nodeBegin(strBegin), nodeEnd(strEnd);
399 nsCString::const_iterator pos(strBegin);
401 nsCOMPtr<nsIFile> parentDir;
402 while (FindInReadable(kParentDirStr, nodeBegin, nodeEnd)) {
403 rv = targetFile->GetParent(getter_AddRefs(parentDir));
404 if (NS_FAILED(rv)) {
405 return rv;
407 if (!parentDir) {
408 return NS_ERROR_FILE_UNRECOGNIZED_PATH;
410 targetFile = parentDir;
412 nodeBegin = nodeEnd;
413 pos = nodeEnd;
414 nodeEnd = strEnd;
417 nodeBegin = nodeEnd = pos;
418 while (nodeEnd != strEnd) {
419 FindCharInReadable('/', nodeEnd, strEnd);
420 targetFile->Append(NS_ConvertUTF8toUTF16(Substring(nodeBegin, nodeEnd)));
421 if (nodeEnd != strEnd) { // If there's more left in the string, inc over
422 // the '/' nodeEnd is on.
423 ++nodeEnd;
425 nodeBegin = nodeEnd;
428 return InitWithFile(targetFile);
431 NS_IMETHODIMP
432 nsLocalFile::GetRelativePath(nsIFile* aFromFile, nsACString& aResult) {
433 return GetRelativeDescriptor(aFromFile, aResult);
436 NS_IMETHODIMP
437 nsLocalFile::SetRelativePath(nsIFile* aFromFile,
438 const nsACString& aRelativePath) {
439 return SetRelativeDescriptor(aFromFile, aRelativePath);