Coverage Report

Created: 2025-07-23 07:04

/src/samba/lib/util/close_low_fd.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Unix SMB/CIFS implementation.
3
 * Samba utility functions
4
 * Copyright (C) Volker Lendecke 2014
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
#include "replace.h"
21
#include "system/filesys.h"
22
#include "close_low_fd.h"
23
24
#ifdef HAVE_VALGRIND_VALGRIND_H
25
#include <valgrind/valgrind.h>
26
#elif defined(HAVE_VALGRIND_H)
27
#include <valgrind.h>
28
#else
29
0
#define RUNNING_ON_VALGRIND 0
30
#endif
31
32
_PUBLIC_ int close_low_fd(int fd)
33
0
{
34
0
  int ret, dev_null;
35
36
0
  if (RUNNING_ON_VALGRIND) {
37
0
    return 0;
38
0
  }
39
40
0
  dev_null = open("/dev/null", O_RDWR, 0);
41
42
0
  if ((dev_null == -1) && (errno == ENFILE)) {
43
    /*
44
     * Try to free up an fd
45
     */
46
0
    ret = close(fd);
47
0
    if (ret != 0) {
48
0
      return errno;
49
0
    }
50
51
0
    dev_null = open("/dev/null", O_RDWR, 0);
52
0
  }
53
54
0
  if (dev_null == -1) {
55
0
    dev_null = open("/dev/null", O_WRONLY, 0);
56
0
  }
57
0
  if (dev_null == -1) {
58
0
    return errno;
59
0
  }
60
61
0
  if (dev_null == fd) {
62
    /*
63
     * This can happen in the ENFILE case above
64
     */
65
0
    return 0;
66
0
  }
67
68
0
  ret = dup2(dev_null, fd);
69
0
  if (ret == -1) {
70
0
    int err = errno;
71
0
    close(dev_null);
72
0
    return err;
73
0
  }
74
0
  close(dev_null);
75
0
  return 0;
76
0
}