1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// http://code.google.com/p/protobuf/
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
85void File::WriteStringToFileOrDie(const string& contents, const string& name) {
86  FILE* file = fopen(name.c_str(), "wb");
87  GOOGLE_CHECK(file != NULL)
88      << "fopen(" << name << ", \"wb\"): " << strerror(errno);
89  GOOGLE_CHECK_EQ(fwrite(contents.data(), 1, contents.size(), file),
90                  contents.size())
91      << "fwrite(" << name << "): " << strerror(errno);
92  GOOGLE_CHECK(fclose(file) == 0)
93      << "fclose(" << name << "): " << strerror(errno);
94}
95
96bool File::CreateDir(const string& name, int mode) {
97  return mkdir(name.c_str(), mode) == 0;
98}
99
100bool File::RecursivelyCreateDir(const string& path, int mode) {
101  if (CreateDir(path, mode)) return true;
102
103  if (Exists(path)) return false;
104
105  // Try creating the parent.
106  string::size_type slashpos = path.find_last_of('/');
107  if (slashpos == string::npos) {
108    // No parent given.
109    return false;
110  }
111
112  return RecursivelyCreateDir(path.substr(0, slashpos), mode) &&
113         CreateDir(path, mode);
114}
115
116void File::DeleteRecursively(const string& name,
117                             void* dummy1, void* dummy2) {
118  // We don't care too much about error checking here since this is only used
119  // in tests to delete temporary directories that are under /tmp anyway.
120
121#ifdef _MSC_VER
122  // This interface is so weird.
123  WIN32_FIND_DATA find_data;
124  HANDLE find_handle = FindFirstFile((name + "/*").c_str(), &find_data);
125  if (find_handle == INVALID_HANDLE_VALUE) {
126    // Just delete it, whatever it is.
127    DeleteFile(name.c_str());
128    RemoveDirectory(name.c_str());
129    return;
130  }
131
132  do {
133    string entry_name = find_data.cFileName;
134    if (entry_name != "." && entry_name != "..") {
135      string path = name + "/" + entry_name;
136      if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
137        DeleteRecursively(path, NULL, NULL);
138        RemoveDirectory(path.c_str());
139      } else {
140        DeleteFile(path.c_str());
141      }
142    }
143  } while(FindNextFile(find_handle, &find_data));
144  FindClose(find_handle);
145
146  RemoveDirectory(name.c_str());
147#else
148  // Use opendir()!  Yay!
149  // lstat = Don't follow symbolic links.
150  struct stat stats;
151  if (lstat(name.c_str(), &stats) != 0) return;
152
153  if (S_ISDIR(stats.st_mode)) {
154    DIR* dir = opendir(name.c_str());
155    if (dir != NULL) {
156      while (true) {
157        struct dirent* entry = readdir(dir);
158        if (entry == NULL) break;
159        string entry_name = entry->d_name;
160        if (entry_name != "." && entry_name != "..") {
161          DeleteRecursively(name + "/" + entry_name, NULL, NULL);
162        }
163      }
164    }
165
166    closedir(dir);
167    rmdir(name.c_str());
168
169  } else if (S_ISREG(stats.st_mode)) {
170    remove(name.c_str());
171  }
172#endif
173}
174
175}  // namespace protobuf
176}  // namespace google
177