so://phie

sock

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

blob: 6f0da8dceaca3331decc8f86df2e26d101ff6e3a (11343 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#pragma once

20

21#include <stdbool.h>

22#include <sys/socket.h>

23

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

25#include <openssl/ssl.h>

26

27// @enum sock_err_t

28typedef enum {

29 SOCK_ERR_OK = 0,

30 SOCK_ERR_NO_SOCKET = 1,

31 SOCK_ERR_UNKNOWN_HOST = 2,

32 SOCK_ERR_NO_ADDR_REUSE = 3,

33 SOCK_ERR_ADDR_IN_USE = 4,

34 SOCK_ERR_NO_LISTEN = 5,

35 SOCK_ERR_NO_SSL_CONTEXT = 6,

36 SOCK_ERR_INVALID_CERTIFICATE = 7,

37 SOCK_ERR_INVALID_PRIVATE_KEY = 8,

38 SOCK_ERR_READ_TIMEOUT = 9,

39 SOCK_ERR_REQUEST_TOO_LONG = 10,

40 SOCK_ERR__COUNT

41} sock_err_t;

42

43// @type sock_t

44// @groupdef sock_t

45typedef struct sock sock_t;

46

47// @struct sock_host_t

48typedef struct {

49 char *hostname;

50 char *certificate;

51 char *private_key;

52 SSL_CTX *ssl_ctx;

53} sock_host_t;

54

55// @struct sock_bind_t

56typedef struct {

57 int sockfd;

58 sock_host_t *hosts;

59 int hosts_len;

60 int port;

61} sock_bind_t;

62

63// @struct sock_conn_t

64// @groupdef sock_conn_t

65typedef struct {

66 int sockfd;

67 struct sockaddr addr;

68 int addr_len;

69 SSL *ssl;

70 sock_bind_t *curr_bind;

71 sock_host_t *curr_host;

72 sock_t *sock;

73} sock_conn_t;

74

75// @type sock_global_fn_t

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

77

78// @struct sock

79// @group sock_t

80struct sock {

81 sock_bind_t *binds;

82 size_t binds_len;

83 pthread_t thread;

84 bool quit;

85 SSL_CTX *ssl_ctx;

86 sock_global_fn_t fn;

87 void *ext;

88};

89

90// @func sock_init

91// @group sock_t

92sock_t *sock_init(void);

93

94// @func sock_cleanup

95// @group sock_t

96void sock_cleanup(sock_t *self);

97

98// @func sock_set_ext

99// @group sock_t

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

101

102// @func sock_on_global

103// @group sock_t

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

105

106// @func sock_bind

107// @group sock_t

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

109

110// @func sock_listen

111// @group sock_t

112sock_err_t sock_listen(sock_t *self);

113

114// @func sock_bind_listen

115// @group sock_t

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

117

118// @func sock_close

119// @group sock_t

120void sock_close(sock_t *self);

121

122// @func sock_conn_read

123// @group sock_conn_t

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

125

126// @func sock_conn_write

127// @group sock_conn_t

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

129

130#ifdef SO_SOCK_IMPL

131

132#include <stdio.h>

133#include <stdlib.h>

134#include <time.h>

135#include <unistd.h>

136#include <pthread.h>

137#include <netdb.h>

138#include <poll.h>

139#include <errno.h>

140#include <signal.h>

141

142// @macro SOCK_SERVER_BACKLOG

143// @internal

144#define SOCK_SERVER_BACKLOG 5

145

146// @macro SOCK_SERVER_SLEEP_TIME

147// @internal

148#define SOCK_SERVER_SLEEP_TIME 100000000

149

150// @macro SOCK_SERVER_POLL_TIME

151// @internal

152#define SOCK_SERVER_POLL_TIME 100

153

154// @impl sock_init

155sock_t *sock_init(void) {

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

157 *self = (sock_t) {

158 .binds = NULL,

159 .binds_len = 0,

160 .quit = false,

161 .ssl_ctx = NULL,

162 .fn = NULL,

163 .ext = NULL,

164 };

165 return self;

166}

167

168// @impl sock_cleanup

169void sock_cleanup(sock_t *self) {

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

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

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

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

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

175 }

176 }

177 }

178 free(self->binds);

179 }

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

181 SSL_CTX_free(self->ssl_ctx);

182 }

183 free(self);

184}

185

186// @impl sock_set_ext

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

188 self->ext = ext;

189}

190

191// @impl sock_on_global

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

193 self->fn = fn;

194}

195

196// @impl sock_conn_read

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

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

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

200 }

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

202}

203

204// @impl sock_conn_write

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

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

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

208 }

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

210}

211

212// @func _sock_client_handle

213// @internal

214void *_sock_client_handle(void *ptr) {

215 if (!ptr) {

216 pthread_exit(0);

217 }

218 sock_conn_t *conn = (sock_conn_t *) ptr;

219 struct timeval timeout;

220 timeout.tv_sec = 5;

221 timeout.tv_usec = 0;

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

223 close(conn->sockfd);

224 free(conn);

225 pthread_exit(0);

226 }

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

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

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

230 if (

231 conn->ssl == NULL ||

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

233 SSL_accept(conn->ssl) <= 0

234 ) {

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

236 SSL_shutdown(conn->ssl);

237 SSL_free(conn->ssl);

238 }

239 close(conn->sockfd);

240 free(conn);

241 pthread_exit(0);

242 }

243 }

244 else {

245 unsigned char peek_byte = 0;

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

247 if (read > 0) {

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

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

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

251 close(conn->sockfd);

252 free(conn);

253 pthread_exit(0);

254 }

255 }

256 }

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

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

259 if (err != SOCK_ERR_OK) {

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

261 SSL_shutdown(conn->ssl);

262 SSL_free(conn->ssl);

263 }

264 close(conn->sockfd);

265 free(conn);

266 pthread_exit(0);

267 }

268 }

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

270 SSL_shutdown(conn->ssl);

271 SSL_free(conn->ssl);

272 }

273 close(conn->sockfd);

274 free(conn);

275 pthread_exit(0);

276}

277

278// @func _sock_server_handle

279// @internal

280void *_sock_server_handle(void *ptr) {

281 sock_t *self = (sock_t *) ptr;

282 struct pollfd fds[self->binds_len];

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

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

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

286 }

287 while (!self->quit) {

288 struct timespec sleep_req, sleep_rem;

289 sleep_req.tv_sec = 0;

290 sleep_req.tv_nsec = SOCK_SERVER_SLEEP_TIME;

291 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

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

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

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

299 conn->ssl = NULL;

300 conn->sock = self;

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

302 free(conn);

303 }

304 else {

305 pthread_t thread;

306 pthread_attr_t thread_attr;

307 pthread_attr_init(&thread_attr);

308 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

310 pthread_attr_destroy(&thread_attr);

311 }

312 }

313 }

314 }

315 }

316 pthread_exit(0);

317}

318

319// @func _sock_tls_sni_callback

320// @internal

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

322 (void) al;

323 sock_conn_t *conn = (sock_conn_t *) arg;

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

325 if (hostname != NULL) {

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

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

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

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

330 conn->curr_host = sock_host;

331 SSL_set_SSL_CTX(ssl, sock_host->ssl_ctx);

332 return SSL_TLSEXT_ERR_OK;

333 }

334 }

335 }

336 }

337 return SSL_TLSEXT_ERR_NOACK;

338}

339

340// @impl sock_bind

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

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

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

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

345 sock_bind->port = port;

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

347 return SOCK_ERR_NO_SOCKET;

348 }

349 struct hostent *host = gethostbyname(hostname);

350 if (!host) {

351 return SOCK_ERR_UNKNOWN_HOST;

352 }

353 struct sockaddr_in addr;

354 addr.sin_family = AF_INET;

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

356 addr.sin_port = htons(port);

357 int enable = 1;

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

359 return SOCK_ERR_NO_ADDR_REUSE;

360 }

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

362 return SOCK_ERR_ADDR_IN_USE;

363 }

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

365 return SOCK_ERR_NO_LISTEN;

366 }

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

368 sock_host_t *sock_host = &hosts[i];

369 sock_host->ssl_ctx = NULL;

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

371 const SSL_METHOD *method = TLS_server_method();

372 sock_host->ssl_ctx = SSL_CTX_new(method);

373 if (!sock_host->ssl_ctx) {

374 return SOCK_ERR_NO_SSL_CONTEXT;

375 }

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

377 return SOCK_ERR_INVALID_CERTIFICATE;

378 }

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

380 return SOCK_ERR_INVALID_PRIVATE_KEY;

381 }

382 }

383 }

384 sock_bind->hosts = hosts;

385 sock_bind->hosts_len = hosts_len;

386 self->binds_len++;

387 return SOCK_ERR_OK;

388}

389

390// @impl sock_listen

391sock_err_t sock_listen(sock_t *self) {

392 signal(SIGPIPE, SIG_IGN);

393 const SSL_METHOD *method = TLS_server_method();

394 self->ssl_ctx = SSL_CTX_new(method);

395 if (!self->ssl_ctx) {

396 return SOCK_ERR_NO_SSL_CONTEXT;

397 }

398 SSL_CTX_set_tlsext_servername_callback(self->ssl_ctx, _sock_tls_sni_callback);

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

400 return SOCK_ERR_OK;

401}

402

403// @impl sock_bind_listen

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

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

406 if (err != SOCK_ERR_OK) {

407 return err;

408 }

409 return sock_listen(self);

410}

411

412// @impl sock_close

413void sock_close(sock_t *self) {

414 self->quit = true;

415 pthread_join(self->thread, NULL);

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

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

418 }

419}

420

421#endif // SO_SOCK_IMPL