summaryrefslogtreecommitdiff
path: root/src/win32/socket.cpp
blob: 6c8d801de8d848ec30b498e0a172440d37db673c (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
/* POSIX emulation layer for Windows.
 *
 * (C) 2008-2024 Anope Team
 * Contact us at team@anope.org
 *
 * Please read COPYING and README for further details.
 */

#define WIN32_NO_OVERRIDE
#include "services.h"

inline static bool is_socket(int fd)
{
	int optval;
	socklen_t optlen = sizeof(optval);
	return getsockopt(fd, SOL_SOCKET, SO_TYPE, reinterpret_cast<char *>(&optval), &optlen) == 0;
}

int read(int fd, char *buf, size_t count)
{
	if (is_socket(fd))
		return recv(fd, buf, count, 0);
	else
		return _read(fd, buf, count);
}

int write(int fd, const char *buf, size_t count)
{
	if (is_socket(fd))
		return send(fd, buf, count, 0);
	else
		return _write(fd, buf, count);
}

int windows_close(int fd)
{
	if (is_socket(fd))
		return closesocket(fd);
	else
		return close(fd);
}

int windows_accept(int fd, struct sockaddr *addr, int *addrlen)
{
	int i = accept(fd, addr, addrlen);
	if (i == INVALID_SOCKET)
		return -1;
	return i;
}

int fcntl(int fd, int cmd, int arg)
{
	if (cmd == F_GETFL)
	{
		return 0;
	}
	else if (cmd == F_SETFL)
	{
		if (arg & O_NONBLOCK)
		{
			unsigned long opt = 1;
			return ioctlsocket(fd, FIONBIO, &opt);
		}
		else
		{
			unsigned long opt = 0;
			return ioctlsocket(fd, FIONBIO, &opt);
		}
	}

	return -1;
}