aboutsummaryrefslogtreecommitdiff
path: root/src/lib/fs/mmap.c
blob: cc1c40b7ab4ebf82834dcd4838965e7c3ed310dc (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
/* Copyright (c) 2003-2004, Roger Dingledine
 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
 * Copyright (c) 2007-2020, The Tor Project, Inc. */
/* See LICENSE for licensing information */

/**
 * \file mmap.c
 *
 * \brief Cross-platform support for mapping files into our address space.
 **/

#include "lib/fs/mmap.h"
#include "lib/fs/files.h"
#include "lib/log/log.h"
#include "lib/log/util_bug.h"
#include "lib/log/win32err.h"
#include "lib/string/compat_string.h"
#include "lib/malloc/malloc.h"

#ifdef HAVE_MMAP
#include <sys/mman.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

#ifdef _WIN32
#include <windows.h>
#endif

#include <errno.h>
#include <string.h>

#if defined(HAVE_MMAP) || defined(RUNNING_DOXYGEN)
/** Try to create a memory mapping for <b>filename</b> and return it.  On
 * failure, return NULL. Sets errno properly, using ERANGE to mean
 * "empty file". Must only be called on trusted Tor-owned files, as changing
 * the underlying file's size causes unspecified behavior. */
MOCK_IMPL(tor_mmap_t *,
tor_mmap_file,(const char *filename))
{
  int fd; /* router file */
  char *string;
  int result;
  tor_mmap_t *res;
  size_t size, filesize;
  struct stat st;

  tor_assert(filename);

  fd = tor_open_cloexec(filename, O_RDONLY, 0);
  if (fd<0) {
    int save_errno = errno;
    int severity = (errno == ENOENT) ? LOG_INFO : LOG_WARN;
    log_fn(severity, LD_FS,"Could not open \"%s\" for mmap(): %s",filename,
           strerror(errno));
    errno = save_errno;
    return NULL;
  }

  /* Get the size of the file */
  result = fstat(fd, &st);
  if (result != 0) {
    int save_errno = errno;
    log_warn(LD_FS,
             "Couldn't fstat opened descriptor for \"%s\" during mmap: %s",
             filename, strerror(errno));
    close(fd);
    errno = save_errno;
    return NULL;
  }
  size = filesize = (size_t)(st.st_size);

  if (st.st_size > SSIZE_T_CEILING || (off_t)size < st.st_size) {
    log_warn(LD_FS, "File \"%s\" is too large. Ignoring.",filename);
    errno = EFBIG;
    close(fd);
    return NULL;
  }
  if (!size) {
    /* Zero-length file. If we call mmap on it, it will succeed but
     * return NULL, and bad things will happen. So just fail. */
    log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
    errno = ERANGE;
    close(fd);
    return NULL;
  }

  string = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
  close(fd);
  if (string == MAP_FAILED) {
    int save_errno = errno;
    log_warn(LD_FS,"Could not mmap file \"%s\": %s", filename,
             strerror(errno));
    errno = save_errno;
    return NULL;
  }

  res = tor_malloc_zero(sizeof(tor_mmap_t));
  res->data = string;
  res->size = filesize;
  res->mapping_size = size;

  return res;
}
/** Release storage held for a memory mapping; returns 0 on success,
 * or -1 on failure (and logs a warning). */
MOCK_IMPL(int,
tor_munmap_file,(tor_mmap_t *handle))
{
  int res;

  if (handle == NULL)
    return 0;

  res = munmap((char*)handle->data, handle->mapping_size);
  if (res == 0) {
    /* munmap() succeeded */
    tor_free(handle);
  } else {
    log_warn(LD_FS, "Failed to munmap() in tor_munmap_file(): %s",
             strerror(errno));
    res = -1;
  }

  return res;
}
#elif defined(_WIN32)
MOCK_IMPL(tor_mmap_t *,
tor_mmap_file,(const char *filename))
{
  TCHAR tfilename[MAX_PATH]= {0};
  tor_mmap_t *res = tor_malloc_zero(sizeof(tor_mmap_t));
  int empty = 0;
  HANDLE file_handle = INVALID_HANDLE_VALUE;
  DWORD size_low, size_high;
  uint64_t real_size;
  res->mmap_handle = NULL;
#ifdef UNICODE
  mbstowcs(tfilename,filename,MAX_PATH);
#else
  strlcpy(tfilename,filename,MAX_PATH);
#endif
  file_handle = CreateFile(tfilename,
                           GENERIC_READ, FILE_SHARE_READ,
                           NULL,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           0);

  if (file_handle == INVALID_HANDLE_VALUE)
    goto win_err;

  size_low = GetFileSize(file_handle, &size_high);

  if (size_low == INVALID_FILE_SIZE && GetLastError() != NO_ERROR) {
    log_warn(LD_FS,"Error getting size of \"%s\".",filename);
    goto win_err;
  }
  if (size_low == 0 && size_high == 0) {
    log_info(LD_FS,"File \"%s\" is empty. Ignoring.",filename);
    empty = 1;
    goto err;
  }
  real_size = (((uint64_t)size_high)<<32) | size_low;
  if (real_size > SIZE_MAX) {
    log_warn(LD_FS,"File \"%s\" is too big to map; not trying.",filename);
    goto err;
  }
  res->size = real_size;

  res->mmap_handle = CreateFileMapping(file_handle,
                                       NULL,
                                       PAGE_READONLY,
                                       size_high,
                                       size_low,
                                       NULL);
  if (res->mmap_handle == NULL)
    goto win_err;
  res->data = (char*) MapViewOfFile(res->mmap_handle,
                                    FILE_MAP_READ,
                                    0, 0, 0);
  if (!res->data)
    goto win_err;

  CloseHandle(file_handle);
  return res;
 win_err: {
    DWORD e = GetLastError();
    int severity = (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND) ?
      LOG_INFO : LOG_WARN;
    char *msg = format_win32_error(e);
    log_fn(severity, LD_FS, "Couldn't mmap file \"%s\": %s", filename, msg);
    tor_free(msg);
    if (e == ERROR_FILE_NOT_FOUND || e == ERROR_PATH_NOT_FOUND)
      errno = ENOENT;
    else
      errno = EINVAL;
  }
 err:
  if (empty)
    errno = ERANGE;
  if (file_handle != INVALID_HANDLE_VALUE)
    CloseHandle(file_handle);
  tor_munmap_file(res);
  return NULL;
}

/* Unmap the file, and return 0 for success or -1 for failure */
MOCK_IMPL(int,
tor_munmap_file,(tor_mmap_t *handle))
{
  if (handle == NULL)
    return 0;

  if (handle->data) {
    /* This is an ugly cast, but without it, "data" in struct tor_mmap_t would
       have to be redefined as non-const. */
    BOOL ok = UnmapViewOfFile( (LPVOID) handle->data);
    if (!ok) {
      log_warn(LD_FS, "Failed to UnmapViewOfFile() in tor_munmap_file(): %d",
               (int)GetLastError());
    }
  }

  if (handle->mmap_handle != NULL)
    CloseHandle(handle->mmap_handle);
  tor_free(handle);

  return 0;
}
#else
#error "cannot implement tor_mmap_file"
#endif /* defined(HAVE_MMAP) || defined(RUNNING_DOXYGEN) || ... */