-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsocket.h
More file actions
339 lines (282 loc) · 8.93 KB
/
socket.h
File metadata and controls
339 lines (282 loc) · 8.93 KB
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
/*
* Simple lightweight c/c++ socket implementation
* Supports: ssl, ftp, and udp
*
* By Gavin D 2022
*
* Contents are under the MIT licence
*
* This is a `botching` tool, not meant to be perfect or super efficent, only easy
*/
#ifndef INCLUDED_SOCKET_H
#define INCLUDED_SOCKET_H
#define WINDOWS defined(_WIN32)
#define GNUcompiler defined(__GNUC__) || defined(__GNUG__)
#define MSCcompiler defined(_MSC_VER)
#ifdef __cplusplus
extern "C" {
#endif
#if WINDOWS
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif
#define __USE_SSL__ (!defined(__NO_SSL__))
#if __USE_SSL__
#include <openssl/err.h>
#include <openssl/ssl.h>
#endif
#if MSCcompiler
#pragma comment(lib,"ws2_32")
#if __USE_SSL__
#pragma comment(lib, "crypto");
#pragma comment(lib, "ssl");
#endif
#endif
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#if __USE_SSL__
#warning bind doesnt support ssl (yet)
#warning listen doesnt support ssl (yet)
#endif // __USE_SSL__
// internal function
// throws the error from the socket implementation
void throwSocketError(){
fprintf(stderr, "Thrown error: ");
fflush(stderr);
#if __USE_SSL__
ERR_print_errors_fp(stderr);
#elif WINDOWS
fprintf(stderr, "%d (WSA ERROR CODE)",WSAGetLastError());
#endif
exit(-1);
}
typedef enum errCode{
no_err = 0,
/* types */
err_locs = (1 << 5) - 1, // locs = locations (bits)
err_ftp = 1,
err_ssl = 2,
err_udp = 3,
/* codes */
cant_create_sock = 1 << 5,
cant_connect_sock = 1 << 6,
cant_bind_sock = 1 << 7,
cant_listen_sock = 1 << 8,
cant_recive_host_info = 1 << 9,
cant_init_winsock = 1 << 10,
} errCode;
const char* getErrMsg(errCode e){
int type = e & err_locs;
switch (e & (~err_locs)){
case no_err: return "no error";
case cant_create_sock: {
switch (type){
case err_ftp : return "cant create socket (ftp)";
case err_ssl : return "cant create socket (ssl)";
case err_udp : return "cant create socket (udp)";
}
return "cant create socket";
}
case cant_connect_sock: {
switch (type){
case err_ftp : return "cant connect socket (ftp) [check if server is http and check port]";
case err_ssl : return "cant connect socket (ssl) [check if server is https and check port]";
// udp doesnt have a connect handshake
}
return "cant connect socket";
};
case cant_bind_sock: return "cant bind sock";
case cant_listen_sock: return "sock failed to execute listen";
case cant_recive_host_info: return "cant recive host info";
case cant_init_winsock: return "cant initialize winsock";
}
return "err op";
}
void throwError(errCode e){
fprintf(stderr, "Thrown error: %s", getErrMsg(e));
exit(-1);
}
typedef struct SOCKET_t{
#if __USE_SSL__
const SSL_METHOD *method;
SSL_CTX *ctx;
SSL* ssl;
#endif
int socketfd;
bool sslViable;
} *SOCKET_t;
void closeSock(SOCKET_t sock);
/* sock contructor */
SOCKET_t createSock(){
SOCKET_t sock = malloc(sizeof(struct SOCKET_t));
return sock;
}
/* sock initiator (ftp/ssl) */
errCode initSock(SOCKET_t sock){
#if WINDOWS
WSADATA wsa;
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
return cant_init_winsock;
#endif
sock->socketfd = socket(PF_INET, SOCK_STREAM, 0);
if(sock->socketfd == 0)
return cant_create_sock | err_ftp;
#if __USE_SSL__
sock->sslViable = 1;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
SSL_library_init();
sock->method = TLS_client_method();
if((sock->ctx = SSL_CTX_new(sock->method) ) == NULL)
return cant_create_sock | err_ssl;
#else
sock->sslViable = 0;
#endif
return no_err;
}
/* sock initiator (udp) */
errCode initSockUDP(SOCKET_t sock){
#if WINDOWS
WSADATA wsa;
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
return cant_init_winsock;
#endif
sock->socketfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock->socketfd == 0)
return cant_create_sock | err_udp;
sock->sslViable = 0;
/* bind */
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr(INADDR_ANY);
local.sin_port = 0;
bind(sock->socketfd, (struct sockaddr *)&local, sizeof(local));
return no_err;
}
/* connects to server */
errCode connectSock(const char* hostname, int port, bool attemptSSL, SOCKET_t sock){
errCode e;
if((e = initSock(sock)) != no_err) return e;
// get host info
struct hostent *host;
struct sockaddr_in addr;
if((host = gethostbyname(hostname)) == NULL)
return cant_recive_host_info;
// connect sock
memset(&addr, 0, sizeof(addr)); // clear address
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sock->socketfd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
return cant_connect_sock | err_ftp;
if(attemptSSL){
#if __USE_SSL__
// create SSL and connect to socket
sock->ssl = SSL_new(sock->ctx);
SSL_set_fd(sock->ssl, sock->socketfd);
SSL_set_tlsext_host_name(sock->ssl, hostname);
if(SSL_connect(sock->ssl) == -1){
sock->sslViable = 0;
}
#else
sock->sslViable = 0;
#endif
}else
sock->sslViable = 0;
return no_err;
}
/* send */
void sendBytes(const char* bytes, int len, SOCKET_t sock) {
#if __USE_SSL__
if(sock->sslViable) SSL_write(sock->ssl, bytes, len);
else send(sock->socketfd, bytes, len, 0);
#else
send(sock->socketfd, (char*)bytes, len, 0);
#endif
}
// sends bytes to a specific hostname and port
errCode sendBytesTo(const char* bytes, int len, const char* hostname, int port, SOCKET_t sock){
/* server addr */
struct hostent *host;
struct sockaddr_in server;
if((host = gethostbyname(hostname)) == NULL)
return cant_recive_host_info;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = *(long*)(host->h_addr);
server.sin_port = htons(port);
/* send */
sendto(sock->socketfd, (char*)bytes, len, 0, (struct sockaddr *)&server, sizeof(server));
return no_err;
}
/* bind */
errCode bindSock(const char* hostname, int port, SOCKET_t sock){
struct hostent *host;
struct sockaddr_in server;
if((host = gethostbyname(hostname)) == NULL)
return cant_recive_host_info;
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = *(long*)(host->h_addr);
server.sin_port = htons(port);
if(bind(sock->socketfd, (struct sockaddr *)&server , sizeof(server)) < 0)
return cant_bind_sock | err_ftp;
return no_err;
}
/* listen
* onConn: a function that is ran on each connection to the binded sock
* maxConn: maximum ammount of connections
* arg: a argument that is passed to the `onConn` func when a connection is made
*/
errCode listenSock(void (*onConn)(SOCKET_t conn, void* arg), int maxConn, SOCKET_t sock, void* arg){
while(1){
if(listen(sock->socketfd, maxConn) < 0)
return cant_listen_sock;
SOCKET_t c = createSock();
initSock(c);
c->sslViable = 0;
int conn = accept(sock->socketfd, NULL, NULL);
c->socketfd = conn;
onConn(c, arg);
closeSock(c);
}
return no_err; // never reached
}
/* recv
* buf: preinitialized array
* bufSize: length of the `buf` array
* delay: how long in milliseconds to wait for a message (0 is infinite)
*/
int recvBytes(char buf[], int bufSize, int delay, SOCKET_t sock){
#if WINDOWS
setsockopt(sock->socketfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&delay, sizeof(delay));
#else
struct timeval tv = {(long)(delay / 1000), (long)((delay % 1000) * 1000)};
setsockopt(sock->socketfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
#endif
if(sock->sslViable){
#if __USE_SSL__
return SSL_read(sock->ssl, buf, bufSize);
#endif
}else
return recv(sock->socketfd, buf, bufSize, 0);
return 0; // never reached
}
/* clean & close */
void closeSock(SOCKET_t sock){
#if WINDOWS
closesocket(sock->socketfd);
#else
close(sock->socketfd)
#endif
free(sock);
}
#ifdef __cplusplus
}
#endif
#endif // INCLUDED_SOCKET_H