summaryrefslogtreecommitdiffstats
path: root/src/common/compat.cc
blob: 3ec0ca2009c73166e1ced045bc7254ab9a7cae57 (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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2011 New Dream Network
 * Copyright (C) 2018 Red Hat, Inc.
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <cstdio>

#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <thread>
#ifndef _WIN32
#include <sys/mount.h>
#else
#include <stdlib.h>
#endif
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#if defined(__linux__) 
#include <sys/vfs.h>
#endif

#include "include/compat.h"
#include "include/sock_compat.h"
#include "common/safe_io.h"

// The type-value for a ZFS FS in fstatfs.
#define FS_ZFS_TYPE 0xde

// On FreeBSD, ZFS fallocate always fails since it is considered impossible to
// reserve space on a COW filesystem. posix_fallocate() returns EINVAL
// Linux in this case already emulates the reservation in glibc
// In which case it is allocated manually, and still that is not a real guarantee
// that a full buffer is allocated on disk, since it could be compressed.
// To prevent this the written buffer needs to be loaded with random data.
int manual_fallocate(int fd, off_t offset, off_t len) {
  int r = lseek(fd, offset, SEEK_SET);
  if (r == -1)
    return errno;
  char data[1024*128];
  // TODO: compressing filesystems would require random data
  // FIPS zeroization audit 20191115: this memset is not security related.
  memset(data, 0x42, sizeof(data));
  for (off_t off = 0; off < len; off += sizeof(data)) {
    if (off + static_cast<off_t>(sizeof(data)) > len)
      r = safe_write(fd, data, len - off);
    else
      r = safe_write(fd, data, sizeof(data));
    if (r == -1) {
      return errno;
    }
  }
  return 0;
}

int on_zfs(int basedir_fd) {
  #ifndef _WIN32
  struct statfs basefs;
  (void)fstatfs(basedir_fd, &basefs);
  return (basefs.f_type == FS_ZFS_TYPE);
  #else
  return 0;
  #endif
}

int ceph_posix_fallocate(int fd, off_t offset, off_t len) {
  // Return 0 if oke, otherwise errno > 0

#ifdef HAVE_POSIX_FALLOCATE
  if (on_zfs(fd)) {
    return manual_fallocate(fd, offset, len);
  } else {
    return posix_fallocate(fd, offset, len);
  }
#elif defined(__APPLE__)
  fstore_t store;
  store.fst_flags = F_ALLOCATECONTIG;
  store.fst_posmode = F_PEOFPOSMODE;
  store.fst_offset = offset;
  store.fst_length = len;

  int ret = fcntl(fd, F_PREALLOCATE, &store);
  if (ret == -1) {
    ret = errno;
  }
  return ret;
#else
  return manual_fallocate(fd, offset, len);
#endif
} 

int pipe_cloexec(int pipefd[2], int flags)
{
#if defined(HAVE_PIPE2)
  return pipe2(pipefd, O_CLOEXEC | flags);
#else
  if (pipe(pipefd) == -1)
    return -1;

  #ifndef _WIN32
  /*
   * The old-fashioned, race-condition prone way that we have to fall
   * back on if pipe2 does not exist.
   */
  if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) < 0) {
    goto fail;
  }

  if (fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) < 0) {
    goto fail;
  }
  #endif

  return 0;
fail:
  int save_errno = errno;
  VOID_TEMP_FAILURE_RETRY(close(pipefd[0]));
  VOID_TEMP_FAILURE_RETRY(close(pipefd[1]));
  return (errno = save_errno, -1);
#endif
}


int socket_cloexec(int domain, int type, int protocol)
{
#ifdef SOCK_CLOEXEC
  return socket(domain, type|SOCK_CLOEXEC, protocol);
#else
  int fd = socket(domain, type, protocol);
  if (fd == -1)
    return -1;

  #ifndef _WIN32
  if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
    goto fail;
  #endif

  return fd;
fail:
  int save_errno = errno;
  VOID_TEMP_FAILURE_RETRY(close(fd));
  return (errno = save_errno, -1);
#endif
}

int socketpair_cloexec(int domain, int type, int protocol, int sv[2])
{
#ifdef SOCK_CLOEXEC
  return socketpair(domain, type|SOCK_CLOEXEC, protocol, sv);
#elif _WIN32
  /* TODO */
  return -ENOTSUP;
#else
  int rc = socketpair(domain, type, protocol, sv);
  if (rc == -1)
    return -1;

  #ifndef _WIN32
  if (fcntl(sv[0], F_SETFD, FD_CLOEXEC) < 0)
    goto fail;

  if (fcntl(sv[1], F_SETFD, FD_CLOEXEC) < 0)
    goto fail;
  #endif

  return 0;
fail:
  int save_errno = errno;
  VOID_TEMP_FAILURE_RETRY(close(sv[0]));
  VOID_TEMP_FAILURE_RETRY(close(sv[1]));
  return (errno = save_errno, -1);
#endif
}

int accept_cloexec(int sockfd, struct sockaddr* addr, socklen_t* addrlen)
{
#ifdef HAVE_ACCEPT4
  return accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
#else
  int fd = accept(sockfd, addr, addrlen);
  if (fd == -1)
    return -1;

  #ifndef _WIN32
  if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
    goto fail;
  #endif

  return fd;
fail:
  int save_errno = errno;
  VOID_TEMP_FAILURE_RETRY(close(fd));
  return (errno = save_errno, -1);
#endif
}

#if defined(__FreeBSD__)
int sched_setaffinity(pid_t pid, size_t cpusetsize,
                      cpu_set_t *mask)
{
  return 0;
}
#endif

char *ceph_strerror_r(int errnum, char *buf, size_t buflen)
{
#ifdef _WIN32
  strerror_s(buf, buflen, errnum);
  return buf;
#elif defined(STRERROR_R_CHAR_P)
  return strerror_r(errnum, buf, buflen);
#else
  if (strerror_r(errnum, buf, buflen)) {
    snprintf(buf, buflen, "Unknown error %d", errnum);
  }
  return buf;
#endif
}

int ceph_memzero_s(void *dest, size_t destsz, size_t count) {
#ifdef __STDC_LIB_EXT1__
    return memset_s(dest, destsz, 0, count);
#elif defined(_WIN32)
    SecureZeroMemory(dest, count);
#else
    explicit_bzero(dest, count);
#endif
    return 0;
}

#ifdef _WIN32

#include <iomanip>
#include <ctime>

// chown is not available on Windows. Plus, changing file owners is not
// a common practice on Windows.
int chown(const char *path, uid_t owner, gid_t group) {
  return 0;
}

int fchown(int fd, uid_t owner, gid_t group) {
  return 0;
}

int lchown(const char *path, uid_t owner, gid_t group) {
  return 0;
}

int posix_memalign(void **memptr, size_t alignment, size_t size) {
  *memptr = _aligned_malloc(size, alignment);
  return *memptr ? 0 : errno;
}

char *strptime(const char *s, const char *format, struct tm *tm) {
  std::istringstream input(s);
  input.imbue(std::locale(setlocale(LC_ALL, nullptr)));
  input >> std::get_time(tm, format);
  if (input.fail()) {
    return nullptr;
  }
  return (char*)(s + input.tellg());
}

int pipe(int pipefd[2]) {
  // We'll use the same pipe size as Linux (64kb).
  return _pipe(pipefd, 0x10000, O_NOINHERIT);
}

// lrand48 is not available on Windows. We'll generate a pseudo-random
// value in the 0 - 2^31 range by calling rand twice.
long int lrand48(void) {
  long int val;
  val = (long int) rand();
  val <<= 16;
  val += (long int) rand();
  return val;
}

int random() {
  return rand();
}

int fsync(int fd) {
  HANDLE handle = (HANDLE*)_get_osfhandle(fd);
  if (handle == INVALID_HANDLE_VALUE)
    return -1;
  if (!FlushFileBuffers(handle))
    return -1;
  return 0;
}

ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset) {
  DWORD bytes_written = 0;

  HANDLE handle = (HANDLE*)_get_osfhandle(fd);
  if (handle == INVALID_HANDLE_VALUE)
    return -1;

  OVERLAPPED overlapped = { 0 };
  ULARGE_INTEGER offsetUnion;
  offsetUnion.QuadPart = offset;

  overlapped.Offset = offsetUnion.LowPart;
  overlapped.OffsetHigh = offsetUnion.HighPart;

  if (!WriteFile(handle, buf, count, &bytes_written, &overlapped))
    // we may consider mapping error codes, although that may
    // not be exhaustive.
    return -1;

  return bytes_written;
}

ssize_t pread(int fd, void *buf, size_t count, off_t offset) {
  DWORD bytes_read = 0;

  HANDLE handle = (HANDLE*)_get_osfhandle(fd);
  if (handle == INVALID_HANDLE_VALUE)
    return -1;

  OVERLAPPED overlapped = { 0 };
  ULARGE_INTEGER offsetUnion;
  offsetUnion.QuadPart = offset;

  overlapped.Offset = offsetUnion.LowPart;
  overlapped.OffsetHigh = offsetUnion.HighPart;

  if (!ReadFile(handle, buf, count, &bytes_read, &overlapped)) {
    if (GetLastError() != ERROR_HANDLE_EOF)
      return -1;
  }

  return bytes_read;
}

ssize_t preadv(int fd, const struct iovec *iov, int iov_cnt) {
  ssize_t read = 0;

  for (int i = 0; i < iov_cnt; i++) {
    int r = ::read(fd, iov[i].iov_base, iov[i].iov_len);
    if (r < 0)
      return r;
    read += r;
    if (r < iov[i].iov_len)
      break;
  }

  return read;
}

ssize_t writev(int fd, const struct iovec *iov, int iov_cnt) {
  ssize_t written = 0;

  for (int i = 0; i < iov_cnt; i++) {
    int r = ::write(fd, iov[i].iov_base, iov[i].iov_len);
    if (r < 0)
      return r;
    written += r;
    if (r < iov[i].iov_len)
      break;
  }

  return written;
}

int &alloc_tls() {
  static __thread int tlsvar;
  tlsvar++;
  return tlsvar;
}

void apply_tls_workaround() {
  // Workaround for the following Mingw bugs:
  // https://sourceforge.net/p/mingw-w64/bugs/727/
  // https://sourceforge.net/p/mingw-w64/bugs/527/
  // https://sourceforge.net/p/mingw-w64/bugs/445/
  // https://gcc.gnu.org/bugzilla/attachment.cgi?id=41382
  pthread_key_t key;
  pthread_key_create(&key, nullptr);
  // Use a TLS slot for emutls
  alloc_tls();
  // Free up a slot that can now be used for c++ destructors
  pthread_key_delete(key);
}

CEPH_CONSTRUCTOR(ceph_windows_init) {
  // This will run at startup time before invoking main().
  WSADATA wsaData;
  int error;

  #ifdef __MINGW32__
  apply_tls_workaround();
  #endif

  error = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if (error != 0) {
    fprintf(stderr, "WSAStartup failed: %d", WSAGetLastError());
    exit(error);
  }
}

int _win_socketpair(int socks[2])
{
  union {
     struct sockaddr_in inaddr;
     struct sockaddr addr;
  } a;
  SOCKET listener;
  int e;
  socklen_t addrlen = sizeof(a.inaddr);
  int reuse = 1;

  if (socks == 0) {
    WSASetLastError(WSAEINVAL);
    return -1;
  }

  listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (listener == INVALID_SOCKET) {
    return -1;
  }

  memset(&a, 0, sizeof(a));
  a.inaddr.sin_family = AF_INET;
  a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  a.inaddr.sin_port = 0;

  socks[0] = socks[1] = -1;
  SOCKET s[2] = { INVALID_SOCKET, INVALID_SOCKET };

  do {
    if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,
           (char*) &reuse, (socklen_t) sizeof(reuse)) == -1)
      break;
    if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
      break;
    if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR)
      break;
    if (listen(listener, 1) == SOCKET_ERROR)
      break;
    s[0] = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s[0] == INVALID_SOCKET)
      break;
    if (connect(s[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
      break;
    s[1] = accept(listener, NULL, NULL);
    if (s[1] == INVALID_SOCKET)
      break;

    closesocket(listener);

    // The Windows socket API is mostly compatible with the Berkeley
    // API, with a few exceptions. The Windows socket functions use
    // SOCKET instead of int. The issue is that on x64 systems,
    // SOCKET uses 64b while int uses 32b. There's been much debate
    // whether casting a Windows socket to an int is safe or not.
    // Worth noting that Windows kernel objects use 32b. For now,
    // we're just adding a check.
    //
    // Ideally, we should update ceph to use the right type but this
    // can be quite difficult, especially considering that there are
    // a significant number of functions that accept both sockets and
    // file descriptors.
    if (s[0] >> 32 || s[1] >> 32) {
      WSASetLastError(WSAENAMETOOLONG);
      break;
    }

    socks[0] = s[0];
    socks[1] = s[1];

    return 0;

  } while (0);

  e = WSAGetLastError();
  closesocket(listener);
  closesocket(s[0]);
  closesocket(s[1]);
  WSASetLastError(e);
  return -1;
}

int win_socketpair(int socks[2]) {
  int r = 0;
  for (int i = 0; i < 15; i++) {
    r = _win_socketpair(socks);
    if (r && WSAGetLastError() == WSAEADDRINUSE) {
      sleep(2);
      continue;
    }
    else {
      break;
    }
  }
  return r;
}

unsigned get_page_size() {
  SYSTEM_INFO system_info;
  GetSystemInfo(&system_info);
  return system_info.dwPageSize;
}

int setenv(const char *name, const char *value, int overwrite) {
  if (!overwrite && getenv(name)) {
    return 0;
  }
  return _putenv_s(name, value);
}

ssize_t get_self_exe_path(char* path, int buff_length) {
  return GetModuleFileName(NULL, path, buff_length - 1);
}

int geteuid()
{
  return 0;
}

int getegid()
{
  return 0;
}

int getuid()
{
  return 0;
}

int getgid()
{
  return 0;
}

#else

unsigned get_page_size() {
  return sysconf(_SC_PAGESIZE);
}

ssize_t get_self_exe_path(char* path, int buff_length) {
  return readlink("/proc/self/exe", path,
                  sizeof(buff_length) - 1);
}

#endif /* _WIN32 */