summaryrefslogtreecommitdiff
path: root/source/kit/sockets.h
blob: a9e275454e78153f6b51b6f4fa4072b4a2fcacac (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
#ifndef KIT_SOCKETS_H
#define KIT_SOCKETS_H

#include "status.h"

#ifndef KIT_DISABLE_SYSTEM_SOCKETS
#  ifdef __GNUC__
#    pragma GCC diagnostic push
#    pragma GCC diagnostic ignored "-Wunused-function"
#    pragma GCC diagnostic ignored "-Wunknown-pragmas"
#  endif

#  ifdef __cplusplus
extern "C" {
#  endif

#  if defined(_WIN32) && !defined(__CYGWIN__)

#    define WIN32_LEAN_AND_MEAN
#    include <winsock2.h>
#    include <ws2tcpip.h>

#    define socket_t SOCKET
#    define socklen_t i32

static kit_status_t kit_sockets_init(void) {
  WSADATA data;
  memset(&data, 0, sizeof data);
  WORD version = MAKEWORD(2, 2);
  return WSAStartup(version, &data) == ERROR_SUCCESS
             ? KIT_OK
             : KIT_ERROR_SOCKETS_STARTUP_FAILED;
}

static kit_status_t kit_sockets_cleanup(void) {
  WSACleanup();
  return KIT_OK;
}

static i32 kit_socket_set_blocking(socket_t s) {
  u_long flag = 0;
  return ioctlsocket(s, FIONBIO, &flag) == 0
             ? KIT_OK
             : KIT_ERROR_SOCKET_CONTROL_FAILED;
}

static i32 kit_socket_set_nonblocking(socket_t s) {
  u_long flag = 1;
  return ioctlsocket(s, FIONBIO, &flag) == 0
             ? KIT_OK
             : KIT_ERROR_SOCKET_CONTROL_FAILED;
}

#  else

#    include <arpa/inet.h>
#    include <errno.h>
#    include <fcntl.h>
#    include <netinet/in.h>
#    include <signal.h>
#    include <sys/ioctl.h>
#    include <sys/select.h>
#    include <sys/socket.h>
#    include <sys/types.h>
#    include <unistd.h>
#    include <netdb.h>

#    define socket_t i32
#    define closesocket close
#    define INVALID_SOCKET -1

static kit_status_t kit_sockets_init(void) {
  signal(SIGPIPE, SIG_IGN);
  return KIT_OK;
}

static kit_status_t kit_sockets_cleanup(void) {
  return KIT_OK;
}

static i32 kit_socket_set_blocking(socket_t s) {
  i32 flags = fcntl(s, F_GETFL, 0);
  return fcntl(s, F_SETFL, flags & ~O_NONBLOCK) == 0
             ? KIT_OK
             : KIT_ERROR_SOCKET_CONTROL_FAILED;
}

static i32 kit_socket_set_nonblocking(socket_t s) {
  i32 flags = fcntl(s, F_GETFL, 0);
  return fcntl(s, F_SETFL, flags | O_NONBLOCK) == 0
             ? KIT_OK
             : KIT_ERROR_SOCKET_CONTROL_FAILED;
}

#  endif

#  ifdef __cplusplus
}
#  endif

#  ifdef __GNUC__
#    pragma GCC diagnostic pop
#  endif
#endif

#endif