aboutsummaryrefslogtreecommitdiff
path: root/libs/coding/internal/file_data.cpp
blob: 44bbaabb6d722a37e49cebb6d22320ae5e5eeff5 (plain) (blame)
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
#include "coding/internal/file_data.hpp"

#include "coding/constants.hpp"
#include "coding/internal/file64_api.hpp"
#include "coding/reader.hpp"  // For Reader exceptions.
#include "coding/writer.hpp"  // For Writer exceptions.

#include "base/exception.hpp"
#include "base/logging.hpp"
#include "base/string_utils.hpp"

#include "std/target_os.hpp"

#include <algorithm>
#include <cerrno>
#include <cstring>
#include <exception>
#include <fstream>
#include <vector>

#ifdef OMIM_OS_WINDOWS
#include <io.h>
#else
#include <unistd.h>  // ftruncate
#endif

namespace base
{
std::ostream & operator<<(std::ostream & stream, FileData::Op op)
{
  switch (op)
  {
  case FileData::Op::READ: stream << "READ"; break;
  case FileData::Op::WRITE_TRUNCATE: stream << "WRITE_TRUNCATE"; break;
  case FileData::Op::WRITE_EXISTING: stream << "WRITE_EXISTING"; break;
  case FileData::Op::APPEND: stream << "APPEND"; break;
  }
  return stream;
}

FileData::FileData(std::string const & fileName, Op op) : m_FileName(fileName), m_Op(op)
{
  char const * const modes[] = {"rb", "wb", "r+b", "ab"};

  errno = 0;
  m_File = fopen(fileName.c_str(), modes[static_cast<int>(op)]);
  if (m_File)
  {
#if defined(_MSC_VER)
    // Move file pointer to the end of the file to make it consistent with other platforms
    if (op == Op::APPEND)
      fseek64(m_File, 0, SEEK_END);
#endif
    return;
  }

  if (op == Op::WRITE_EXISTING)
  {
    // Special case, since "r+b" fails if file doesn't exist.
    m_File = fopen(fileName.c_str(), "wb");
    if (m_File)
      return;
  }

  // if we're here - something bad is happened
  if (m_Op != Op::READ)
    MYTHROW(Writer::OpenException, (GetErrorProlog()));
  else if (errno == EMFILE || errno == ENFILE)
    MYTHROW(Reader::TooManyFilesException, (GetErrorProlog()));
  else
    MYTHROW(Reader::OpenException, (GetErrorProlog()));
}

FileData::~FileData()
{
  if (m_File)
  {
    if (fclose(m_File))
      LOG(LWARNING, ("Error closing file", GetErrorProlog()));
  }
}

std::string FileData::GetErrorProlog() const
{
  std::ostringstream stream;
  stream << m_FileName << "; " << m_Op << "; " << strerror(errno);
  return stream.str();
}

static int64_t constexpr INVALID_POS = -1;

uint64_t FileData::Size() const
{
  int64_t const pos = ftell64(m_File);
  if (pos == INVALID_POS)
    MYTHROW(Reader::SizeException, (GetErrorProlog(), pos));

  if (fseek64(m_File, 0, SEEK_END))
    MYTHROW(Reader::SizeException, (GetErrorProlog()));

  int64_t const size = ftell64(m_File);
  if (size == INVALID_POS)
    MYTHROW(Reader::SizeException, (GetErrorProlog(), size));

  if (fseek64(m_File, static_cast<off_t>(pos), SEEK_SET))
    MYTHROW(Reader::SizeException, (GetErrorProlog(), pos));

  ASSERT_GREATER_OR_EQUAL(size, 0, ());
  return static_cast<uint64_t>(size);
}

void FileData::Read(uint64_t pos, void * p, size_t size)
{
  if (fseek64(m_File, static_cast<off_t>(pos), SEEK_SET))
    MYTHROW(Reader::ReadException, (GetErrorProlog(), pos));

  size_t const bytesRead = fread(p, 1, size, m_File);
  if (bytesRead != size || ferror(m_File))
    MYTHROW(Reader::ReadException, (GetErrorProlog(), bytesRead, pos, size));
}

uint64_t FileData::Pos() const
{
  int64_t const pos = ftell64(m_File);
  if (pos == INVALID_POS)
    MYTHROW(Writer::PosException, (GetErrorProlog(), pos));

  ASSERT_GREATER_OR_EQUAL(pos, 0, ());
  return static_cast<uint64_t>(pos);
}

void FileData::Seek(uint64_t pos)
{
  ASSERT_NOT_EQUAL(m_Op, Op::APPEND, (m_FileName, m_Op, pos));
  if (fseek64(m_File, static_cast<off_t>(pos), SEEK_SET))
    MYTHROW(Writer::SeekException, (GetErrorProlog(), pos));
}

void FileData::Write(void const * p, size_t size)
{
  size_t const bytesWritten = fwrite(p, 1, size, m_File);
  if (bytesWritten != size || ferror(m_File))
    MYTHROW(Writer::WriteException, (GetErrorProlog(), bytesWritten, size));
}

void FileData::Flush()
{
  if (fflush(m_File))
    MYTHROW(Writer::WriteException, (GetErrorProlog()));
}

void FileData::Truncate(uint64_t sz)
{
#ifdef OMIM_OS_WINDOWS
  int const res = _chsize(fileno(m_File), sz);
#else
  int const res = ftruncate(fileno(m_File), static_cast<off_t>(sz));
#endif

  if (res)
    MYTHROW(Writer::WriteException, (GetErrorProlog(), sz));
}

bool GetFileSize(std::string const & fName, uint64_t & sz)
{
  try
  {
    typedef FileData fdata_t;
    fdata_t f(fName, fdata_t::Op::READ);
    sz = f.Size();
    return true;
  }
  catch (RootException const &)
  {
    // supress all exceptions here
    return false;
  }
}

namespace
{

bool CheckFileOperationResult(int res, std::string const & fName)
{
  if (!res)
    return true;

  LOG(LWARNING, ("File operation error for file:", fName, "-", strerror(errno)));

  // additional check if file really was removed correctly
  uint64_t dummy;
  if (GetFileSize(fName, dummy))
    LOG(LERROR, ("File exists but can't be deleted. Sharing violation?", fName));

  return false;
}

bool IsEOF(std::ifstream & fs)
{
  return fs.peek() == std::ifstream::traits_type::eof();
}

}  // namespace

bool DeleteFileX(std::string const & fName)
{
  int res = std::remove(fName.c_str());
  return CheckFileOperationResult(res, fName);
}

bool RenameFileX(std::string const & fOld, std::string const & fNew)
{
  int res = rename(fOld.c_str(), fNew.c_str());
  return CheckFileOperationResult(res, fOld);
}

bool MoveFileX(std::string const & fOld, std::string const & fNew)
{
  // Try to rename the file first.
  int res = rename(fOld.c_str(), fNew.c_str());
  if (res == 0)
    return true;

  // Otherwise perform the full move.
  if (!CopyFileX(fOld, fNew))
  {
    (void)DeleteFileX(fNew);
    return false;
  }
  (void)DeleteFileX(fOld);
  return true;
}

bool WriteToTempAndRenameToFile(std::string const & dest, std::function<bool(std::string const &)> const & write,
                                std::string const & tmp)
{
  std::string const tmpFileName = tmp.empty() ? dest + ".tmp" + strings::to_string(std::this_thread::get_id()) : tmp;
  if (!write(tmpFileName))
  {
    LOG(LERROR, ("Can't write to", tmpFileName));
    DeleteFileX(tmpFileName);
    return false;
  }
  if (!RenameFileX(tmpFileName, dest))
  {
    LOG(LERROR, ("Can't rename file", tmpFileName, "to", dest));
    DeleteFileX(tmpFileName);
    return false;
  }
  return true;
}

void AppendFileToFile(std::string const & fromFilename, std::string const & toFilename)
{
  std::ifstream from;
  from.exceptions(std::fstream::failbit | std::fstream::badbit);
  from.open(fromFilename, std::ios::binary);

  std::ofstream to;
  to.exceptions(std::fstream::badbit);
  to.open(toFilename, std::ios::binary | std::ios::app);

  auto * buffer = from.rdbuf();
  if (!IsEOF(from))
    to << buffer;
}

bool CopyFileX(std::string const & fOld, std::string const & fNew)
{
  std::ifstream ifs;
  std::ofstream ofs;
  ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  ofs.exceptions(std::ifstream::failbit | std::ifstream::badbit);

  try
  {
    ifs.open(fOld.c_str());
    ofs.open(fNew.c_str());

    // If source file is empty - make empty dest file without any errors.
    if (IsEOF(ifs))
      return true;

    ofs << ifs.rdbuf();
    ofs.flush();
    return true;
  }
  catch (std::system_error const &)
  {
    LOG(LWARNING, ("Failed to copy file from", fOld, "to", fNew, ":", strerror(errno)));
  }
  catch (std::exception const &)
  {
    LOG(LERROR, ("Unknown error when coping files:", fOld, "to", fNew, strerror(errno)));
  }

  // Don't care about possible error here ..
  (void)DeleteFileX(fNew);
  return false;
}

bool IsEqualFiles(std::string const & firstFile, std::string const & secondFile)
{
  FileData first(firstFile, FileData::Op::READ);
  FileData second(secondFile, FileData::Op::READ);
  if (first.Size() != second.Size())
    return false;

  size_t constexpr bufSize = READ_FILE_BUFFER_SIZE;
  std::vector<char> buf1, buf2;
  buf1.resize(bufSize);
  buf2.resize(bufSize);
  size_t const fileSize = static_cast<size_t>(first.Size());
  size_t currSize = 0;

  while (currSize < fileSize)
  {
    size_t const toRead = std::min(bufSize, fileSize - currSize);

    first.Read(currSize, &buf1[0], toRead);
    second.Read(currSize, &buf2[0], toRead);

    if (buf1 != buf2)
      return false;

    currSize += toRead;
  }

  return true;
}

std::vector<uint8_t> ReadFile(std::string const & filePath)
{
  FileData file(filePath, FileData::Op::READ);
  uint64_t const sz = file.Size();
  std::vector<uint8_t> contents(sz);
  file.Read(0, contents.data(), sz);
  return contents;
}

}  // namespace base