so://phie

sock

An extensible multi-threaded TCP/TLS socket library
git clone git://soophie.de/sock

blob: 8e7c98d62ea2321cd6183c05a7853b65c3f33066 (11402 bytes)[doc][blame][raw]

1/*

2 * Copyright (C) 2026 Sophie Sitzler

3 *

4 * This program is free software: you can redistribute it and/or modify

5 * it under the terms of the GNU General Public License as published by

6 * the Free Software Foundation, either version 3 of the License, or

7 * (at your option) any later version.

8 *

9 * This program is distributed in the hope that it will be useful,

10 * but WITHOUT ANY WARRANTY; without even the implied warranty of

11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

12 * GNU General Public License for more details.

13 *

14 * You should have received a copy of the GNU General Public License

15 * along with this program. If not, see <https://www.gnu.org/licenses/>.

16 */

17

18// @file sock.h

19// @desc An extensible multi-threaded TCP/TLS socket library

20

21#pragma once

22

23#include <stdbool.h>

24#include <sys/socket.h>

25

26// @include <openssl/ssl.h>

27#include <openssl/ssl.h>

28

29// @enum sock_err_t

30typedef enum {

31 SOCK_ERR_OK = 0,

32 SOCK_ERR_NO_SOCKET = 1,

33 SOCK_ERR_UNKNOWN_HOST = 2,

34 SOCK_ERR_NO_ADDR_REUSE = 3,

35 SOCK_ERR_ADDR_IN_USE = 4,

36 SOCK_ERR_NO_LISTEN = 5,

37 SOCK_ERR_NO_SSL_CONTEXT = 6,

38 SOCK_ERR_INVALID_CERTIFICATE = 7,

39 SOCK_ERR_INVALID_PRIVATE_KEY = 8,

40 SOCK_ERR_READ_TIMEOUT = 9,

41 SOCK_ERR_REQUEST_TOO_LONG = 10,

42 SOCK_ERR__COUNT

43} sock_err_t;

44

45// @struct sock_t

46// @groupdef sock_t

47typedef struct sock sock_t;

48

49// @struct sock_host_t

50typedef struct {

51 char *hostname;

52 char *certificate;

53 char *private_key;

54 SSL_CTX *ssl_ctx;

55} sock_host_t;

56

57// @struct sock_bind_t

58typedef struct {

59 int sockfd;

60 sock_host_t *hosts;

61 int hosts_len;

62 int port;

63} sock_bind_t;

64

65// @struct sock_conn_t

66// @groupdef sock_conn_t

67typedef struct {

68 int sockfd;

69 struct sockaddr addr;

70 int addr_len;

71 SSL *ssl;

72 sock_bind_t *curr_bind;

73 sock_host_t *curr_host;

74 sock_t *sock;

75} sock_conn_t;

76

77// @type sock_global_fn_t

78typedef sock_err_t (*sock_global_fn_t)(sock_t *, sock_conn_t *);

79

80// @impl sock_t

81struct sock {

82 sock_bind_t *binds;

83 size_t binds_len;

84 pthread_t thread;

85 bool quit;

86 SSL_CTX *ssl_ctx;

87 sock_global_fn_t fn;

88 void *ext;

89};

90

91// @func sock_init

92// @group sock_t

93sock_t *sock_init(void);

94

95// @func sock_cleanup

96// @group sock_t

97void sock_cleanup(sock_t *self);

98

99// @func sock_set_ext

100// @group sock_t

101void sock_set_ext(sock_t *self, void *ext);

102

103// @func sock_on_global

104// @group sock_t

105void sock_on_global(sock_t *self, sock_global_fn_t fn);

106

107// @func sock_bind

108// @group sock_t

109sock_err_t sock_bind(sock_t *self, char *hostname, int port, sock_host_t *hosts, int hosts_len);

110

111// @func sock_listen

112// @group sock_t

113sock_err_t sock_listen(sock_t *self);

114

115// @func sock_bind_listen

116// @group sock_t

117sock_err_t sock_bind_listen(sock_t *self, char *hostname, int port);

118

119// @func sock_close

120// @group sock_t

121void sock_close(sock_t *self);

122

123// @func sock_conn_read

124// @group sock_conn_t

125ssize_t sock_conn_read(sock_conn_t *conn, char *buffer, size_t len);

126

127// @func sock_conn_write

128// @group sock_conn_t

129ssize_t sock_conn_write(sock_conn_t *conn, char *buffer, size_t len);

130

131#ifdef SOCK_IMPL

132

133#include <stdio.h>

134#include <stdlib.h>

135#include <time.h>

136#include <unistd.h>

137#include <pthread.h>

138#include <netdb.h>

139#include <poll.h>

140#include <errno.h>

141#include <signal.h>

142

143// @macro SOCK_SERVER_BACKLOG

144// @internal

145#define SOCK_SERVER_BACKLOG 5

146

147// @macro SOCK_SERVER_SLEEP_TIME

148// @internal

149#define SOCK_SERVER_SLEEP_TIME 100000000

150

151// @macro SOCK_SERVER_POLL_TIME

152// @internal

153#define SOCK_SERVER_POLL_TIME 100

154

155// @impl sock_init

156sock_t *sock_init(void) {

157 sock_t *self= (sock_t *) malloc(sizeof(sock_t));

158 *self = (sock_t) {

159 .binds = NULL,

160 .binds_len = 0,

161 .quit = false,

162 .ssl_ctx = NULL,

163 .fn = NULL,

164 .ext = NULL,

165 };

166 return self;

167}

168

169// @impl sock_cleanup

170void sock_cleanup(sock_t *self) {

171 if (self->binds != NULL) {

172 for (size_t i = 0; i < self->binds_len; i++) {

173 for (size_t j = 0; j < (size_t) self->binds[i].hosts_len; j++) {

174 if (self->binds[i].hosts[j].ssl_ctx != NULL) {

175 SSL_CTX_free(self->binds[i].hosts[j].ssl_ctx);

176 }

177 }

178 }

179 free(self->binds);

180 }

181 if (self->ssl_ctx != NULL) {

182 SSL_CTX_free(self->ssl_ctx);

183 }

184 free(self);

185}

186

187// @impl sock_set_ext

188void sock_set_ext(sock_t *self, void *ext) {

189 self->ext = ext;

190}

191

192// @impl sock_on_global

193void sock_on_global(sock_t *self, sock_global_fn_t fn) {

194 self->fn = fn;

195}

196

197// @impl sock_conn_read

198ssize_t sock_conn_read(sock_conn_t *conn, char *buffer, size_t len) {

199 if (conn->ssl != NULL) {

200 return SSL_read(conn->ssl, buffer, len);

201 }

202 return read(conn->sockfd, buffer, len);

203}

204

205// @impl sock_conn_write

206ssize_t sock_conn_write(sock_conn_t *conn, char *buffer, size_t len) {

207 if (conn->ssl != NULL) {

208 return SSL_write(conn->ssl, buffer, len);

209 }

210 return write(conn->sockfd, buffer, len);

211}

212

213// @func _sock_client_handle

214// @internal

215void *_sock_client_handle(void *ptr) {

216 if (!ptr) {

217 pthread_exit(0);

218 }

219 sock_conn_t *conn = (sock_conn_t *) ptr;

220 struct timeval timeout;

221 timeout.tv_sec = 5;

222 timeout.tv_usec = 0;

223 if (setsockopt(conn->sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) < 0) {

224 close(conn->sockfd);

225 free(conn);

226 pthread_exit(0);

227 }

228 if (conn->curr_bind->hosts_len > 0) {

229 SSL_CTX_set_tlsext_servername_arg(conn->sock->ssl_ctx, (void *) conn);

230 conn->ssl = SSL_new(conn->sock->ssl_ctx);

231 if (

232 conn->ssl == NULL ||

233 SSL_set_fd(conn->ssl, conn->sockfd) <= 0 ||

234 SSL_accept(conn->ssl) <= 0

235 ) {

236 if (conn->ssl != NULL) {

237 SSL_shutdown(conn->ssl);

238 SSL_free(conn->ssl);

239 }

240 close(conn->sockfd);

241 free(conn);

242 pthread_exit(0);

243 }

244 }

245 else {

246 unsigned char peek_byte = 0;

247 ssize_t read = recv(conn->sockfd, &peek_byte, 1, MSG_PEEK);

248 if (read > 0) {

249 // 0x16 = TLS Record Type: Handshake (ClientHello)

250 // Anything < 32 is non-printable ASCII (not valid HTTP method)

251 if (peek_byte == 0x16 || peek_byte < 32) {

252 close(conn->sockfd);

253 free(conn);

254 pthread_exit(0);

255 }

256 }

257 }

258 if (conn->sock->fn != NULL) {

259 sock_err_t err = conn->sock->fn(conn->sock, conn);

260 if (err != SOCK_ERR_OK) {

261 if (conn->ssl != NULL) {

262 SSL_shutdown(conn->ssl);

263 SSL_free(conn->ssl);

264 }

265 close(conn->sockfd);

266 free(conn);

267 pthread_exit(0);

268 }

269 }

270 if (conn->ssl != NULL) {

271 SSL_shutdown(conn->ssl);

272 SSL_free(conn->ssl);

273 }

274 close(conn->sockfd);

275 free(conn);

276 pthread_exit(0);

277}

278

279// @func _sock_server_handle

280// @internal

281void *_sock_server_handle(void *ptr) {

282 sock_t *self = (sock_t *) ptr;

283 struct pollfd fds[self->binds_len];

284 for (size_t i = 0; i < self->binds_len; i++) {

285 fds[i].fd = self->binds[i].sockfd;

286 fds[i].events = POLLIN | POLLPRI;

287 }

288 while (!self->quit) {

289 struct timespec sleep_req, sleep_rem;

290 sleep_req.tv_sec = 0;

291 sleep_req.tv_nsec = SOCK_SERVER_SLEEP_TIME;

292 nanosleep(&sleep_req, &sleep_rem);

293 if (poll(fds, self->binds_len, SOCK_SERVER_POLL_TIME)) {

294 for (size_t i = 0; i < self->binds_len; i++) {

295 if (fds[i].revents & POLLIN) {

296 sock_conn_t *conn = (sock_conn_t *) malloc(sizeof(sock_conn_t));

297 conn->addr_len = sizeof(conn->addr);

298 conn->sockfd = accept(self->binds[i].sockfd, &conn->addr, (socklen_t *) &conn->addr_len);

299 conn->curr_bind = &self->binds[i];

300 conn->ssl = NULL;

301 conn->sock = self;

302 if (conn->sockfd <= 0) {

303 free(conn);

304 }

305 else {

306 pthread_t thread;

307 pthread_attr_t thread_attr;

308 pthread_attr_init(&thread_attr);

309 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

310 pthread_create(&thread, &thread_attr, _sock_client_handle, (void *) conn);

311 pthread_attr_destroy(&thread_attr);

312 }

313 }

314 }

315 }

316 }

317 pthread_exit(0);

318}

319

320// @func _sock_tls_sni_callback

321// @internal

322int _sock_tls_sni_callback(SSL *ssl, int *al, void *arg) {

323 (void) al;

324 sock_conn_t *conn = (sock_conn_t *) arg;

325 const char *hostname = SSL_get_servername(ssl, 0);

326 if (hostname != NULL) {

327 for (size_t i = 0; i < conn->sock->binds_len; i++) {

328 for (size_t j = 0; j < (size_t) conn->sock->binds[i].hosts_len; j++) {

329 sock_host_t *sock_host = &conn->sock->binds[i].hosts[j];

330 if (strcmp(sock_host->hostname, hostname) == 0) {

331 conn->curr_host = sock_host;

332 SSL_set_SSL_CTX(ssl, sock_host->ssl_ctx);

333 return SSL_TLSEXT_ERR_OK;

334 }

335 }

336 }

337 }

338 return SSL_TLSEXT_ERR_NOACK;

339}

340

341// @impl sock_bind

342sock_err_t sock_bind(sock_t *self, char *hostname, int port, sock_host_t *hosts, int hosts_len) {

343 self->binds = (sock_bind_t *) realloc(self->binds, sizeof(sock_bind_t) * (self->binds_len + 1));

344 sock_bind_t *sock_bind = &self->binds[self->binds_len];

345 sock_bind->sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

346 sock_bind->port = port;

347 if (sock_bind->sockfd <= 0) {

348 return SOCK_ERR_NO_SOCKET;

349 }

350 struct hostent *host = gethostbyname(hostname);

351 if (!host) {

352 return SOCK_ERR_UNKNOWN_HOST;

353 }

354 struct sockaddr_in addr;

355 addr.sin_family = AF_INET;

356 memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);

357 addr.sin_port = htons(port);

358 int enable = 1;

359 if (setsockopt(sock_bind->sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) {

360 return SOCK_ERR_NO_ADDR_REUSE;

361 }

362 if (bind(sock_bind->sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)) < 0) {

363 return SOCK_ERR_ADDR_IN_USE;

364 }

365 if (listen(sock_bind->sockfd, SOCK_SERVER_BACKLOG) < 0) {

366 return SOCK_ERR_NO_LISTEN;

367 }

368 for (int i = 0; i < hosts_len; i++) {

369 sock_host_t *sock_host = &hosts[i];

370 sock_host->ssl_ctx = NULL;

371 if (sock_host->certificate != NULL && sock_host->private_key != NULL) {

372 const SSL_METHOD *method = TLS_server_method();

373 sock_host->ssl_ctx = SSL_CTX_new(method);

374 if (!sock_host->ssl_ctx) {

375 return SOCK_ERR_NO_SSL_CONTEXT;

376 }

377 if (SSL_CTX_use_certificate_chain_file(sock_host->ssl_ctx, sock_host->certificate) <= 0) {

378 return SOCK_ERR_INVALID_CERTIFICATE;

379 }

380 if (SSL_CTX_use_PrivateKey_file(sock_host->ssl_ctx, sock_host->private_key, SSL_FILETYPE_PEM) <= 0) {

381 return SOCK_ERR_INVALID_PRIVATE_KEY;

382 }

383 }

384 }

385 sock_bind->hosts = hosts;

386 sock_bind->hosts_len = hosts_len;

387 self->binds_len++;

388 return SOCK_ERR_OK;

389}

390

391// @impl sock_listen

392sock_err_t sock_listen(sock_t *self) {

393 signal(SIGPIPE, SIG_IGN);

394 const SSL_METHOD *method = TLS_server_method();

395 self->ssl_ctx = SSL_CTX_new(method);

396 if (!self->ssl_ctx) {

397 return SOCK_ERR_NO_SSL_CONTEXT;

398 }

399 SSL_CTX_set_tlsext_servername_callback(self->ssl_ctx, _sock_tls_sni_callback);

400 pthread_create(&self->thread, 0, _sock_server_handle, (void *) self);

401 return SOCK_ERR_OK;

402}

403

404// @impl sock_bind_listen

405sock_err_t sock_bind_listen(sock_t *self, char *hostname, int port) {

406 sock_err_t err = sock_bind(self, hostname, port, NULL, 0);

407 if (err != SOCK_ERR_OK) {

408 return err;

409 }

410 return sock_listen(self);

411}

412

413// @impl sock_close

414void sock_close(sock_t *self) {

415 self->quit = true;

416 pthread_join(self->thread, NULL);

417 for (size_t i = 0; i < self->binds_len; i++) {

418 close(self->binds[i].sockfd);

419 }

420}

421

422#endif // SOCK_IMPL