aboutsummaryrefslogtreecommitdiff
path: root/libs/archive/src/extractcallback.cpp
blob: 76292988cd39156fb7fa556c1160a3162244388a (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
/*
Mod Organizer archive handling

Copyright (C) 2012 Sebastian Herbord, 2020 MO2 Team. All rights reserved.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "compat.h"

#include <algorithm>
#include <filesystem>
#include <format>
#include <stdexcept>
#include <string>

#include "archive.h"
#include "extractcallback.h"
#include "propertyvariant.h"

std::wstring operationResultToString(Int32 operationResult)
{
  namespace R = NArchive::NExtract::NOperationResult;

  switch (operationResult) {
  case R::kOK:
    return {};

  case R::kUnsupportedMethod:
    return L"Encoding method unsupported";

  case R::kDataError:
    return L"Data error";

  case R::kCRCError:
    return L"CRC error";

  case R::kUnavailable:
    return L"Unavailable";

  case R::kUnexpectedEnd:
    return L"Unexpected end of archive";

  case R::kDataAfterEnd:
    return L"Data after end of archive";

  case R::kIsNotArc:
    return L"Not an ARC";

  case R::kHeadersError:
    return L"Bad headers";

  case R::kWrongPassword:
    return L"Wrong password";

  default:
    return std::format(L"Unknown error {}", operationResult);
  }
}

CArchiveExtractCallback::CArchiveExtractCallback(
    Archive::ProgressCallback progressCallback,
    Archive::FileChangeCallback fileChangeCallback,
    Archive::ErrorCallback errorCallback, Archive::PasswordCallback passwordCallback,
    Archive::LogCallback logCallback, IInArchive* archiveHandler,
    std::wstring const& directoryPath, FileData* const* fileData, std::size_t nbFiles,
    UInt64 totalFileSize, std::wstring* password)
    : m_ArchiveHandler(archiveHandler), m_Total(0), m_DirectoryPath(),
      m_Extracting(false), m_Canceled(false), m_Timers{}, m_ProcessedFileInfo{},
      m_OutputFileStream{}, m_OutFileStreamCom{}, m_FileData(fileData),
      m_NbFiles(nbFiles), m_TotalFileSize(totalFileSize), m_LastCallbackFileSize(0),
      m_ExtractedFileSize(0), m_ProgressCallback(progressCallback),
      m_FileChangeCallback(fileChangeCallback), m_ErrorCallback(errorCallback),
      m_PasswordCallback(passwordCallback), m_LogCallback(logCallback),
      m_Password(password)
{
  m_DirectoryPath = IO::make_path(directoryPath);
}

CArchiveExtractCallback::~CArchiveExtractCallback()
{
#ifdef INSTRUMENT_ARCHIVE
  m_LogCallback(Archive::LogLevel::Debug, m_Timers.GetStream.toString(L"GetStream"));
  m_LogCallback(Archive::LogLevel::Debug, m_Timers.SetOperationResult.SetMTime.toString(
                                              L"SetOperationResult.SetMTime"));
  m_LogCallback(Archive::LogLevel::Debug, m_Timers.SetOperationResult.Close.toString(
                                              L"SetOperationResult.Close"));
  m_LogCallback(Archive::LogLevel::Debug, m_Timers.SetOperationResult.Release.toString(
                                              L"SetOperationResult.Release"));
  m_LogCallback(Archive::LogLevel::Debug,
                m_Timers.SetOperationResult.SetFileAttributesW.toString(
                    L"SetOperationResult.SetFileAttributesW"));
#endif
}

STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 size) throw()
{
  m_Total = size;
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64* completed) throw()
{
  if (m_ProgressCallback) {
    m_ProgressCallback(Archive::ProgressType::ARCHIVE, *completed, m_Total);
  }
  return m_Canceled ? E_ABORT : S_OK;
}

template <typename T>
bool CArchiveExtractCallback::getOptionalProperty(UInt32 index, int property,
                                                  T* result) const
{
  PropertyVariant prop;
  if (m_ArchiveHandler->GetProperty(index, property, &prop) != S_OK) {
    m_LogCallback(Archive::LogLevel::Error,
                  std::format(L"Error getting property {}.", property));
    return false;
  }
  if (prop.is_empty()) {
    return false;
  }
  *result = static_cast<T>(prop);
  return true;
}

template <typename T>
bool CArchiveExtractCallback::getProperty(UInt32 index, int property, T* result) const
{
  PropertyVariant prop;
  if (m_ArchiveHandler->GetProperty(index, property, &prop) != S_OK) {
    m_LogCallback(Archive::LogLevel::Error,
                  std::format(L"Error getting property {}.", property));
    return false;
  }

  *result = static_cast<T>(prop);
  return true;
}

STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index,
                                                ISequentialOutStream** outStream,
                                                Int32 askExtractMode) throw()
{
  [[maybe_unused]] auto guard = m_Timers.GetStream.instrument();
  namespace fs = std::filesystem;

  *outStream = nullptr;
  m_OutFileStreamCom.Release();

  m_FullProcessedPaths.clear();
  m_Extracting = false;

  if (askExtractMode != NArchive::NExtract::NAskMode::kExtract) {
    return S_OK;
  }

  std::vector<std::wstring> filenames = m_FileData[index]->getOutputFilePaths();
  m_FileData[index]->clearOutputFilePaths();
  if (filenames.empty()) {
    return S_OK;
  }

#ifndef _WIN32
  // Archives from Windows contain backslash path separators which are valid
  // filename characters on Linux - convert them to forward slashes.
  for (auto& fn : filenames) {
    std::replace(fn.begin(), fn.end(), L'\\', L'/');
  }
#endif

  try {
    m_ProcessedFileInfo.AttribDefined =
        getOptionalProperty(index, kpidAttrib, &m_ProcessedFileInfo.Attrib);

    if (!getProperty(index, kpidIsDir, &m_ProcessedFileInfo.isDir)) {
      return E_ABORT;
    }

    // Why do we do this? And if we are doing this, shouldn't we copy the created
    // and accessed times (kpidATime, kpidCTime) as well?
    m_ProcessedFileInfo.MTimeDefined =
        getOptionalProperty(index, kpidMTime, &m_ProcessedFileInfo.MTime);

    if (m_ProcessedFileInfo.isDir) {
      for (auto const& filename : filenames) {
        auto fullpath = m_DirectoryPath / fs::path(filename).make_preferred();
        std::error_code ec;
        std::filesystem::create_directories(fullpath, ec);
        if (ec) {
          reportError(L"cannot created directory '{}': {}", fullpath, ec);
          return E_ABORT;
        }
        m_FullProcessedPaths.push_back(fullpath);
      }
    } else {
      for (auto const& filename : filenames) {
        auto fullProcessedPath = m_DirectoryPath / fs::path(filename).make_preferred();
        // If the filename contains a '/' we want to make the directory
        auto directoryPath = fullProcessedPath.parent_path();
        if (!fs::exists(directoryPath)) {
          // Make the containing directory
          std::error_code ec;
          std::filesystem::create_directories(directoryPath, ec);
          if (ec) {
            reportError(L"cannot created directory '{}': {}", directoryPath, ec);
            return E_ABORT;
          }
          // m_DirectoryPath.mkpath(filename.left(slashPos));
        }
        // If the file already exists, delete it
        if (fs::exists(fullProcessedPath)) {
          std::error_code ec;
          if (!fs::remove(fullProcessedPath, ec)) {
            reportError(L"cannot delete output file '{}': {}", fullProcessedPath, ec);
            return E_ABORT;
          }
        }
        m_FullProcessedPaths.push_back(fullProcessedPath);
      }

      m_OutputFileStream = new MultiOutputStream([this](UInt32 size, UInt64) {
        m_ExtractedFileSize += size;
        if (m_ProgressCallback) {
          m_ProgressCallback(Archive::ProgressType::EXTRACTION, m_ExtractedFileSize,
                             m_TotalFileSize);
        }
      });
      CComPtr<MultiOutputStream> outStreamCom(m_OutputFileStream);

      if (!m_OutputFileStream->Open(m_FullProcessedPaths)) {
        reportError(L"cannot open output file '{}': {}", m_FullProcessedPaths[0],
                    ::GetLastError());
        return E_ABORT;
      }

      UInt64 fileSize;
      auto fileSizeFound = getOptionalProperty(index, kpidSize, &fileSize);
      if (fileSizeFound && m_OutputFileStream->SetSize(fileSize) != S_OK) {
        m_LogCallback(Archive::LogLevel::Error,
                      std::format(L"SetSize() failed on {}.", m_FullProcessedPaths[0]));
      }

      // This is messy but I can't find another way of doing it. A simple
      // assignment of m_outFileStream to *outStream doesn't increase the
      // reference count.
      m_OutFileStreamCom = outStreamCom;
      *outStream         = outStreamCom.Detach();
    }

    if (m_FileChangeCallback) {
      m_FileChangeCallback(Archive::FileChangeType::EXTRACTION_START, filenames[0]);
    }

    return S_OK;
  } catch (std::exception const& e) {
    m_LogCallback(Archive::LogLevel::Error,
                  std::format(L"Caught exception {} in GetStream.", e));
  }
  return E_FAIL;
}

STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 askExtractMode) throw()
{
  if (m_Canceled) {
    return E_ABORT;
  }
  m_Extracting = askExtractMode == NArchive::NExtract::NAskMode::kExtract;
  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult) throw()
{
  if (operationResult != NArchive::NExtract::NOperationResult::kOK) {
    reportError(operationResultToString(operationResult));
  }

  if (m_OutFileStreamCom) {
    if (m_ProcessedFileInfo.MTimeDefined) {
      [[maybe_unused]] auto guard = m_Timers.SetOperationResult.SetMTime.instrument();
      m_OutputFileStream->SetMTime(&m_ProcessedFileInfo.MTime);
    }
    [[maybe_unused]] auto guard = m_Timers.SetOperationResult.Close.instrument();
    RINOK(m_OutputFileStream->Close())
  }

  {
    [[maybe_unused]] auto guard = m_Timers.SetOperationResult.Release.instrument();
    m_OutFileStreamCom.Release();
  }

  [[maybe_unused]] auto guard2 = m_Timers.SetOperationResult.SetFileAttributesW.instrument();
  if (m_Extracting && m_ProcessedFileInfo.AttribDefined) {
    // this is moderately annoying. I can't do this on the file handle because if
    // the file in question is a directory there isn't a file handle.
    // Also I'd like to convert the attributes to QT attributes but I'm not sure
    // if that's possible. Hence the conversions and strange string.
    for (auto& path : m_FullProcessedPaths) {
#ifdef _WIN32
      std::wstring const fn = L"\\\\?\\" + path.native();
      // If the attributes are POSIX-based, fix that
      if (m_ProcessedFileInfo.Attrib & 0xF0000000)
        m_ProcessedFileInfo.Attrib &= 0x7FFF;

      // Should probably log any errors here somehow
      ::SetFileAttributesW(fn.c_str(), m_ProcessedFileInfo.Attrib);
#else
      // On Linux, we could set file permissions based on the attributes,
      // but Windows file attributes don't map well to POSIX permissions.
      // For now, we only handle the read-only attribute and only for files.
      // Applying read-only to directories can break extraction when later
      // files need to be created inside those directories.
      if (!m_ProcessedFileInfo.isDir &&
          (m_ProcessedFileInfo.Attrib & FILE_ATTRIBUTE_READONLY)) {
        std::filesystem::permissions(path,
          std::filesystem::perms::owner_write,
          std::filesystem::perm_options::remove);
      } else if (m_ProcessedFileInfo.isDir) {
        // Keep extracted directories writable for the owner.
        std::filesystem::permissions(path,
          std::filesystem::perms::owner_write,
          std::filesystem::perm_options::add);
      }
#endif
    }
  }

  return S_OK;
}

STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR* passwordOut) throw()
{
  // if we've already got a password, don't ask again (and again...)
  if (m_Password->empty() && m_PasswordCallback) {
    *m_Password = m_PasswordCallback();
  }

  *passwordOut = ::SysAllocString(m_Password->c_str());
  return *passwordOut != 0 ? S_OK : E_OUTOFMEMORY;
}

void CArchiveExtractCallback::SetCanceled(bool aCanceled)
{
  m_Canceled = aCanceled;
}

void CArchiveExtractCallback::reportError(std::wstring const& message)
{
  if (m_ErrorCallback) {
    m_ErrorCallback(message);
  }
}