summaryrefslogtreecommitdiffstats
path: root/xpcom/io/nsLocalFileCommon.cpp
blob: 7e9d7151c1d5ad011ca0e422d9d22c822050e0f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsLocalFile.h"  // includes platform-specific headers

#include "nsString.h"
#include "nsCOMPtr.h"
#include "nsReadableUtils.h"
#include "nsPrintfCString.h"
#include "nsCRT.h"
#include "nsNativeCharsetUtils.h"
#include "nsUTF8Utils.h"
#include "nsArray.h"
#include "nsLocalFileCommon.h"

#ifdef XP_WIN
#  include <string.h>
#endif

// Extensions that should be considered 'executable', ie will not allow users
// to open immediately without first saving to disk, and potentially provoke
// other warnings. PLEASE read the longer comment in
// toolkit/components/reputationservice/ApplicationReputation.cpp
// before modifying this list!
// If you update this list, make sure to update the length of sExecutableExts
// in nsLocalFileCommmon.h.
/* static */
const char* const sExecutableExts[] = {
    // clang-format off
  ".accda",       // MS Access database
  ".accdb",       // MS Access database
  ".accde",       // MS Access database
  ".accdr",       // MS Access database
  ".ad",
  ".ade",         // access project extension
  ".adp",
  ".afploc",      // Apple Filing Protocol Location
  ".air",         // Adobe AIR installer
  ".app",         // executable application
  ".application", // from bug 348763
  ".appref-ms",   // ClickOnce link
  ".appx",
  ".appxbundle",
  ".asp",
  ".atloc",       // Appletalk Location
  ".bas",
  ".bat",
  ".cer",         // Signed certificate file
  ".chm",
  ".cmd",
  ".com",
  ".cpl",
  ".crt",
  ".der",
  ".diagcab",     // Windows archive
  ".exe",
  ".fileloc",     // Apple finder internet location data file
  ".ftploc",      // Apple FTP Location
  ".fxp",         // FoxPro compiled app
  ".hlp",
  ".hta",
  ".inetloc",     // Apple finder internet location data file
  ".inf",
  ".ins",
  ".isp",
  ".jar",         // java application bundle
#ifndef MOZ_ESR
  ".jnlp",
#endif
  ".js",
  ".jse",
  ".lnk",
  ".mad",         // Access Module Shortcut
  ".maf",         // Access
  ".mag",         // Access Diagram Shortcut
  ".mam",         // Access Macro Shortcut
  ".maq",         // Access Query Shortcut
  ".mar",         // Access Report Shortcut
  ".mas",         // Access Stored Procedure
  ".mat",         // Access Table Shortcut
  ".mau",         // Media Attachment Unit
  ".mav",         // Access View Shortcut
  ".maw",         // Access Data Access Page
  ".mda",         // Access Add-in, MDA Access 2 Workgroup
  ".mdb",
  ".mde",
  ".mdt",         // Access Add-in Data
  ".mdw",         // Access Workgroup Information
  ".mdz",         // Access Wizard Template
  ".msc",
  ".msh",         // Microsoft Shell
  ".msh1",        // Microsoft Shell
  ".msh1xml",     // Microsoft Shell
  ".msh2",        // Microsoft Shell
  ".msh2xml",     // Microsoft Shell
  ".mshxml",      // Microsoft Shell
  ".msi",
  ".msix",
  ".msixbundle",
  ".msp",
  ".mst",
  ".ops",         // Office Profile Settings
  ".pcd",
  ".pif",
  ".plg",         // Developer Studio Build Log
  ".prf",         // windows system file
  ".prg",
  ".pst",
  ".reg",
  ".scf",         // Windows explorer command
  ".scr",
  ".sct",
  ".settingcontent-ms",
  ".shb",
  ".shs",
  ".url",
  ".vb",
  ".vbe",
  ".vbs",
  ".vdx",
  ".vsd",
  ".vsdm",
  ".vsdx",
  ".vsmacros",    // Visual Studio .NET Binary-based Macro Project
  ".vss",
  ".vssm",
  ".vssx",
  ".vst",
  ".vstm",
  ".vstx",
  ".vsw",
  ".vsx",
  ".vtx",
  ".webloc",       // MacOS website location file
  ".ws",
  ".wsc",
  ".wsf",
  ".wsh",
  ".xll",         // MS Excel dynamic link library
  ".xrm-ms"
    // clang-format on
};

#if !defined(MOZ_WIDGET_COCOA) && !defined(XP_WIN)
NS_IMETHODIMP
nsLocalFile::InitWithFile(nsIFile* aFile) {
  if (NS_WARN_IF(!aFile)) {
    return NS_ERROR_INVALID_ARG;
  }

  nsAutoCString path;
  aFile->GetNativePath(path);
  if (path.IsEmpty()) {
    return NS_ERROR_INVALID_ARG;
  }
  return InitWithNativePath(path);
}
#endif

#define kMaxFilenameLength 255
#define kMaxExtensionLength 100
#define kMaxSequenceNumberLength 5  // "-9999"
// requirement: kMaxExtensionLength <
//                kMaxFilenameLength - kMaxSequenceNumberLength

NS_IMETHODIMP
nsLocalFile::CreateUnique(uint32_t aType, uint32_t aAttributes) {
  nsresult rv;
  bool longName;

#ifdef XP_WIN
  nsAutoString pathName, leafName, rootName, suffix;
  rv = GetPath(pathName);
#else
  nsAutoCString pathName, leafName, rootName, suffix;
  rv = GetNativePath(pathName);
#endif
  if (NS_FAILED(rv)) {
    return rv;
  }

  auto FailedBecauseExists = [&](nsresult aRv) {
    if (aRv == NS_ERROR_FILE_ACCESS_DENIED) {
      bool exists;
      return NS_SUCCEEDED(Exists(&exists)) && exists;
    }
    return aRv == NS_ERROR_FILE_ALREADY_EXISTS;
  };

  longName =
      (pathName.Length() + kMaxSequenceNumberLength > kMaxFilenameLength);
  if (!longName) {
    rv = Create(aType, aAttributes);
    if (!FailedBecauseExists(rv)) {
      return rv;
    }
  }

#ifdef XP_WIN
  rv = GetLeafName(leafName);
  if (NS_FAILED(rv)) {
    return rv;
  }

  const int32_t lastDot = leafName.RFindChar(char16_t('.'));
#else
  rv = GetNativeLeafName(leafName);
  if (NS_FAILED(rv)) {
    return rv;
  }

  const int32_t lastDot = leafName.RFindChar('.');
#endif

  if (lastDot == kNotFound) {
    rootName = leafName;
  } else {
    suffix = Substring(leafName, lastDot);       // include '.'
    rootName = Substring(leafName, 0, lastDot);  // strip suffix and dot
  }

  if (longName) {
    int32_t maxRootLength =
        (kMaxFilenameLength - (pathName.Length() - leafName.Length()) -
         suffix.Length() - kMaxSequenceNumberLength);

    // We cannot create an item inside a directory whose name is too long.
    // Also, ensure that at least one character remains after we truncate
    // the root name, as we don't want to end up with an empty leaf name.
    if (maxRootLength < 2) {
      return NS_ERROR_FILE_UNRECOGNIZED_PATH;
    }

#ifdef XP_WIN
    // ensure that we don't cut the name in mid-UTF16-character
    rootName.SetLength(NS_IS_LOW_SURROGATE(rootName[maxRootLength])
                           ? maxRootLength - 1
                           : maxRootLength);
    SetLeafName(rootName + suffix);
#else
    if (NS_IsNativeUTF8()) {
      // ensure that we don't cut the name in mid-UTF8-character
      // (assume the name is valid UTF8 to begin with)
      while (UTF8traits::isInSeq(rootName[maxRootLength])) {
        --maxRootLength;
      }

      // Another check to avoid ending up with an empty leaf name.
      if (maxRootLength == 0 && suffix.IsEmpty()) {
        return NS_ERROR_FILE_UNRECOGNIZED_PATH;
      }
    }

    rootName.SetLength(maxRootLength);
    SetNativeLeafName(rootName + suffix);
#endif
    nsresult rvCreate = Create(aType, aAttributes);
    if (!FailedBecauseExists(rvCreate)) {
      return rvCreate;
    }
  }

  for (int indx = 1; indx < 10000; ++indx) {
    // start with "Picture-1.jpg" after "Picture.jpg" exists
#ifdef XP_WIN
    SetLeafName(rootName +
                NS_ConvertASCIItoUTF16(nsPrintfCString("-%d", indx)) + suffix);
#else
    SetNativeLeafName(rootName + nsPrintfCString("-%d", indx) + suffix);
#endif
    rv = Create(aType, aAttributes);
    if (NS_SUCCEEDED(rv) || !FailedBecauseExists(rv)) {
      return rv;
    }
  }

  // The disk is full, sort of
  return NS_ERROR_FILE_TOO_BIG;
}

#if defined(XP_WIN)
static const char16_t kPathSeparatorChar = '\\';
#elif defined(XP_UNIX)
static const char16_t kPathSeparatorChar = '/';
#else
#  error Need to define file path separator for your platform
#endif

static void SplitPath(char16_t* aPath, nsTArray<char16_t*>& aNodeArray) {
  if (*aPath == 0) {
    return;
  }

  if (*aPath == kPathSeparatorChar) {
    aPath++;
  }
  aNodeArray.AppendElement(aPath);

  for (char16_t* cp = aPath; *cp != 0; ++cp) {
    if (*cp == kPathSeparatorChar) {
      *cp++ = 0;
      if (*cp == 0) {
        break;
      }
      aNodeArray.AppendElement(cp);
    }
  }
}

NS_IMETHODIMP
nsLocalFile::GetRelativeDescriptor(nsIFile* aFromFile, nsACString& aResult) {
  if (NS_WARN_IF(!aFromFile)) {
    return NS_ERROR_INVALID_ARG;
  }

  //
  // aResult will be UTF-8 encoded
  //

  nsresult rv;
  aResult.Truncate(0);

  nsAutoString thisPath, fromPath;
  AutoTArray<char16_t*, 32> thisNodes;
  AutoTArray<char16_t*, 32> fromNodes;

  rv = GetPath(thisPath);
  if (NS_FAILED(rv)) {
    return rv;
  }
  rv = aFromFile->GetPath(fromPath);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // get raw pointer to mutable string buffer
  char16_t* thisPathPtr = thisPath.BeginWriting();
  char16_t* fromPathPtr = fromPath.BeginWriting();

  SplitPath(thisPathPtr, thisNodes);
  SplitPath(fromPathPtr, fromNodes);

  size_t nodeIndex;
  for (nodeIndex = 0;
       nodeIndex < thisNodes.Length() && nodeIndex < fromNodes.Length();
       ++nodeIndex) {
#ifdef XP_WIN
    if (_wcsicmp(char16ptr_t(thisNodes[nodeIndex]),
                 char16ptr_t(fromNodes[nodeIndex]))) {
      break;
    }
#else
    if (nsCRT::strcmp(thisNodes[nodeIndex], fromNodes[nodeIndex])) {
      break;
    }
#endif
  }

  size_t branchIndex = nodeIndex;
  for (nodeIndex = branchIndex; nodeIndex < fromNodes.Length(); ++nodeIndex) {
    aResult.AppendLiteral("../");
  }
  StringJoinAppend(aResult, "/"_ns, mozilla::Span{thisNodes}.From(branchIndex),
                   [](nsACString& dest, const auto& thisNode) {
                     // XXX(Bug 1682869) We wouldn't need to reconstruct a
                     // nsDependentString here if SplitPath already returned
                     // nsDependentString. In fact, it seems SplitPath might be
                     // replaced by ParseString?
                     AppendUTF16toUTF8(nsDependentString{thisNode}, dest);
                   });

  return NS_OK;
}

NS_IMETHODIMP
nsLocalFile::SetRelativeDescriptor(nsIFile* aFromFile,
                                   const nsACString& aRelativeDesc) {
  constexpr auto kParentDirStr = "../"_ns;

  nsCOMPtr<nsIFile> targetFile;
  nsresult rv = aFromFile->Clone(getter_AddRefs(targetFile));
  if (NS_FAILED(rv)) {
    return rv;
  }

  //
  // aRelativeDesc is UTF-8 encoded
  //

  nsCString::const_iterator strBegin, strEnd;
  aRelativeDesc.BeginReading(strBegin);
  aRelativeDesc.EndReading(strEnd);

  nsCString::const_iterator nodeBegin(strBegin), nodeEnd(strEnd);
  nsCString::const_iterator pos(strBegin);

  nsCOMPtr<nsIFile> parentDir;
  while (FindInReadable(kParentDirStr, nodeBegin, nodeEnd)) {
    rv = targetFile->GetParent(getter_AddRefs(parentDir));
    if (NS_FAILED(rv)) {
      return rv;
    }
    if (!parentDir) {
      return NS_ERROR_FILE_UNRECOGNIZED_PATH;
    }
    targetFile = parentDir;

    nodeBegin = nodeEnd;
    pos = nodeEnd;
    nodeEnd = strEnd;
  }

  nodeBegin = nodeEnd = pos;
  while (nodeEnd != strEnd) {
    FindCharInReadable('/', nodeEnd, strEnd);
    targetFile->Append(NS_ConvertUTF8toUTF16(Substring(nodeBegin, nodeEnd)));
    if (nodeEnd != strEnd) {  // If there's more left in the string, inc over
                              // the '/' nodeEnd is on.
      ++nodeEnd;
    }
    nodeBegin = nodeEnd;
  }

  return InitWithFile(targetFile);
}

NS_IMETHODIMP
nsLocalFile::GetRelativePath(nsIFile* aFromFile, nsACString& aResult) {
  return GetRelativeDescriptor(aFromFile, aResult);
}

NS_IMETHODIMP
nsLocalFile::SetRelativePath(nsIFile* aFromFile,
                             const nsACString& aRelativePath) {
  return SetRelativeDescriptor(aFromFile, aRelativePath);
}