1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31// Author: kenton@google.com (Kenton Varda)
32// emulates google3/file/base/file.cc
33
34#include <google/protobuf/testing/file.h>
35#include <stdio.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38#ifdef _MSC_VER
39#define WIN32_LEAN_AND_MEAN  // yeah, right
40#include <windows.h>         // Find*File().  :(
41#include <io.h>
42#include <direct.h>
43#else
44#include <dirent.h>
45#include <unistd.h>
46#endif
47#include <errno.h>
48
49namespace google {
50namespace protobuf {
51
52#ifdef _WIN32
53#define mkdir(name, mode) mkdir(name)
54// Windows doesn't have symbolic links.
55#define lstat stat
56#ifndef F_OK
57#define F_OK 00  // not defined by MSVC for whatever reason
58#endif
59#endif
60
61bool File::Exists(const string& name) {
62  return access(name.c_str(), F_OK) == 0;
63}
64
65bool File::ReadFileToString(const string& name, string* output) {
66  char buffer[1024];
67  FILE* file = fopen(name.c_str(), "rb");
68  if (file == NULL) return false;
69
70  while (true) {
71    size_t n = fread(buffer, 1, sizeof(buffer), file);
72    if (n <= 0) break;
73    output->append(buffer, n);
74  }
75
76  int error = ferror(file);
77  if (fclose(file) != 0) return false;
78  return error == 0;
79}
80
81void File::ReadFileToStringOrDie(const string& name, string* output) {
82  GOOGLE_CHECK(ReadFileToString(name, output)) << "Could not read: " << name;
83}
84
85bool File::WriteStringToFile(const string& contents, const string& name) {
86  FILE* file = fopen(name.c_str(), "wb");
87  if (file == NULL) {
88    GOOGLE_LOG(ERROR) << "fopen(" << name << ", \"wb\"): " << strerror(errno);
89    return false;
90  }
91
92  if (fwrite(contents.data(), 1, contents.size(), file) != contents.size()) {
93    GOOGLE_LOG(ERROR) << "fwrite(" << name << "): " << strerror(errno);
94    return false;
95  }
96
97  if (fclose(file) != 0) {
98    return false;
99  }
100  return true;
101}
102
103void File::WriteStringToFileOrDie(const string& contents, const string& name) {
104  FILE* file = fopen(name.c_str(), "wb");
105  GOOGLE_CHECK(file != NULL)
106      << "fopen(" << name << ", \"wb\"): " << strerror(errno);
107  GOOGLE_CHECK_EQ(fwrite(contents.data(), 1, contents.size(), file),
108                  contents.size())
109      << "fwrite(" << name << "): " << strerror(errno);
110  GOOGLE_CHECK(fclose(file) == 0)
111      << "fclose(" << name << "): " << strerror(errno);
112}
113
114bool File::CreateDir(const string& name, int mode) {
115  return mkdir(name.c_str(), mode) == 0;
116}
117
118bool File::RecursivelyCreateDir(const string& path, int mode) {
119  if (CreateDir(path, mode)) return true;
120
121  if (Exists(path)) return false;
122
123  // Try creating the parent.
124  string::size_type slashpos = path.find_last_of('/');
125  if (slashpos == string::npos) {
126    // No parent given.
127    return false;
128  }
129
130  return RecursivelyCreateDir(path.substr(0, slashpos), mode) &&
131         CreateDir(path, mode);
132}
133
134void File::DeleteRecursively(const string& name,
135                             void* dummy1, void* dummy2) {
136  // We don't care too much about error checking here since this is only used
137  // in tests to delete temporary directories that are under /tmp anyway.
138
139#ifdef _MSC_VER
140  // This interface is so weird.
141  WIN32_FIND_DATA find_data;
142  HANDLE find_handle = FindFirstFile((name + "/*").c_str(), &find_data);
143  if (find_handle == INVALID_HANDLE_VALUE) {
144    // Just delete it, whatever it is.
145    DeleteFile(name.c_str());
146    RemoveDirectory(name.c_str());
147    return;
148  }
149
150  do {
151    string entry_name = find_data.cFileName;
152    if (entry_name != "." && entry_name != "..") {
153      string path = name + "/" + entry_name;
154      if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
155        DeleteRecursively(path, NULL, NULL);
156        RemoveDirectory(path.c_str());
157      } else {
158        DeleteFile(path.c_str());
159      }
160    }
161  } while(FindNextFile(find_handle, &find_data));
162  FindClose(find_handle);
163
164  RemoveDirectory(name.c_str());
165#else
166  // Use opendir()!  Yay!
167  // lstat = Don't follow symbolic links.
168  struct stat stats;
169  if (lstat(name.c_str(), &stats) != 0) return;
170
171  if (S_ISDIR(stats.st_mode)) {
172    DIR* dir = opendir(name.c_str());
173    if (dir != NULL) {
174      while (true) {
175        struct dirent* entry = readdir(dir);
176        if (entry == NULL) break;
177        string entry_name = entry->d_name;
178        if (entry_name != "." && entry_name != "..") {
179          DeleteRecursively(name + "/" + entry_name, NULL, NULL);
180        }
181      }
182    }
183
184    closedir(dir);
185    rmdir(name.c_str());
186
187  } else if (S_ISREG(stats.st_mode)) {
188    remove(name.c_str());
189  }
190#endif
191}
192
193}  // namespace protobuf
194}  // namespace google
195