so://phie

sock

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

blob: 0a64182363d3e19ca5bafba4157c68af9e1ea8e8 (11390 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

20#ifndef _SO_SOCK_H

21#define _SO_SOCK_H

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// @type 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// @struct sock

81// @group sock_t

82struct sock {

83 sock_bind_t *binds;

84 size_t binds_len;

85 pthread_t thread;

86 bool quit;

87 SSL_CTX *ssl_ctx;

88 sock_global_fn_t fn;

89 void *ext;

90};

91

92// @func sock_init

93// @group sock_t

94sock_t *sock_init(void);

95

96// @func sock_cleanup

97// @group sock_t

98void sock_cleanup(sock_t *self);

99

100// @func sock_set_ext

101// @group sock_t

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

103

104// @func sock_on_global

105// @group sock_t

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

107

108// @func sock_bind

109// @group sock_t

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

111

112// @func sock_listen

113// @group sock_t

114sock_err_t sock_listen(sock_t *self);

115

116// @func sock_bind_listen

117// @group sock_t

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

119

120// @func sock_close

121// @group sock_t

122void sock_close(sock_t *self);

123

124// @func sock_conn_read

125// @group sock_conn_t

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

127

128// @func sock_conn_write

129// @group sock_conn_t

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

131

132#ifdef SO_SOCK_IMPL

133

134#include <stdio.h>

135#include <stdlib.h>

136#include <time.h>

137#include <unistd.h>

138#include <pthread.h>

139#include <netdb.h>

140#include <poll.h>

141#include <errno.h>

142#include <signal.h>

143

144// @macro SOCK_SERVER_BACKLOG

145// @internal

146#define SOCK_SERVER_BACKLOG 5

147

148// @macro SOCK_SERVER_SLEEP_TIME

149// @internal

150#define SOCK_SERVER_SLEEP_TIME 100000000

151

152// @macro SOCK_SERVER_POLL_TIME

153// @internal

154#define SOCK_SERVER_POLL_TIME 100

155

156// @impl sock_init

157sock_t *sock_init(void) {

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

159 *self = (sock_t) {

160 .binds = NULL,

161 .binds_len = 0,

162 .quit = false,

163 .ssl_ctx = NULL,

164 .fn = NULL,

165 .ext = NULL,

166 };

167 return self;

168}

169

170// @impl sock_cleanup

171void sock_cleanup(sock_t *self) {

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

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

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

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

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

177 }

178 }

179 }

180 free(self->binds);

181 }

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

183 SSL_CTX_free(self->ssl_ctx);

184 }

185 free(self);

186}

187

188// @impl sock_set_ext

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

190 self->ext = ext;

191}

192

193// @impl sock_on_global

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

195 self->fn = fn;

196}

197

198// @impl sock_conn_read

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

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

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

202 }

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

204}

205

206// @impl sock_conn_write

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

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

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

210 }

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

212}

213

214// @func _sock_client_handle

215// @internal

216void *_sock_client_handle(void *ptr) {

217 if (!ptr) {

218 pthread_exit(0);

219 }

220 sock_conn_t *conn = (sock_conn_t *) ptr;

221 struct timeval timeout;

222 timeout.tv_sec = 5;

223 timeout.tv_usec = 0;

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

225 close(conn->sockfd);

226 free(conn);

227 pthread_exit(0);

228 }

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

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

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

232 if (

233 conn->ssl == NULL ||

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

235 SSL_accept(conn->ssl) <= 0

236 ) {

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

238 SSL_shutdown(conn->ssl);

239 SSL_free(conn->ssl);

240 }

241 close(conn->sockfd);

242 free(conn);

243 pthread_exit(0);

244 }

245 }

246 else {

247 unsigned char peek_byte = 0;

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

249 if (read > 0) {

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

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

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

253 close(conn->sockfd);

254 free(conn);

255 pthread_exit(0);

256 }

257 }

258 }

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

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

261 if (err != SOCK_ERR_OK) {

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

263 SSL_shutdown(conn->ssl);

264 SSL_free(conn->ssl);

265 }

266 close(conn->sockfd);

267 free(conn);

268 pthread_exit(0);

269 }

270 }

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

272 SSL_shutdown(conn->ssl);

273 SSL_free(conn->ssl);

274 }

275 close(conn->sockfd);

276 free(conn);

277 pthread_exit(0);

278}

279

280// @func _sock_server_handle

281// @internal

282void *_sock_server_handle(void *ptr) {

283 sock_t *self = (sock_t *) ptr;

284 struct pollfd fds[self->binds_len];

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

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

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

288 }

289 while (!self->quit) {

290 struct timespec sleep_req, sleep_rem;

291 sleep_req.tv_sec = 0;

292 sleep_req.tv_nsec = SOCK_SERVER_SLEEP_TIME;

293 nanosleep(&sleep_req, &sleep_rem);

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

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

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

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

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

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

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

301 conn->ssl = NULL;

302 conn->sock = self;

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

304 free(conn);

305 }

306 else {

307 pthread_t thread;

308 pthread_attr_t thread_attr;

309 pthread_attr_init(&thread_attr);

310 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

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

312 pthread_attr_destroy(&thread_attr);

313 }

314 }

315 }

316 }

317 }

318 pthread_exit(0);

319}

320

321// @func _sock_tls_sni_callback

322// @internal

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

324 (void) al;

325 sock_conn_t *conn = (sock_conn_t *) arg;

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

327 if (hostname != NULL) {

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

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

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

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

332 conn->curr_host = sock_host;

333 SSL_set_SSL_CTX(ssl, sock_host->ssl_ctx);

334 return SSL_TLSEXT_ERR_OK;

335 }

336 }

337 }

338 }

339 return SSL_TLSEXT_ERR_NOACK;

340}

341

342// @impl sock_bind

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

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

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

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

347 sock_bind->port = port;

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

349 return SOCK_ERR_NO_SOCKET;

350 }

351 struct hostent *host = gethostbyname(hostname);

352 if (!host) {

353 return SOCK_ERR_UNKNOWN_HOST;

354 }

355 struct sockaddr_in addr;

356 addr.sin_family = AF_INET;

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

358 addr.sin_port = htons(port);

359 int enable = 1;

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

361 return SOCK_ERR_NO_ADDR_REUSE;

362 }

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

364 return SOCK_ERR_ADDR_IN_USE;

365 }

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

367 return SOCK_ERR_NO_LISTEN;

368 }

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

370 sock_host_t *sock_host = &hosts[i];

371 sock_host->ssl_ctx = NULL;

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

373 const SSL_METHOD *method = TLS_server_method();

374 sock_host->ssl_ctx = SSL_CTX_new(method);

375 if (!sock_host->ssl_ctx) {

376 return SOCK_ERR_NO_SSL_CONTEXT;

377 }

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

379 return SOCK_ERR_INVALID_CERTIFICATE;

380 }

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

382 return SOCK_ERR_INVALID_PRIVATE_KEY;

383 }

384 }

385 }

386 sock_bind->hosts = hosts;

387 sock_bind->hosts_len = hosts_len;

388 self->binds_len++;

389 return SOCK_ERR_OK;

390}

391

392// @impl sock_listen

393sock_err_t sock_listen(sock_t *self) {

394 signal(SIGPIPE, SIG_IGN);

395 const SSL_METHOD *method = TLS_server_method();

396 self->ssl_ctx = SSL_CTX_new(method);

397 if (!self->ssl_ctx) {

398 return SOCK_ERR_NO_SSL_CONTEXT;

399 }

400 SSL_CTX_set_tlsext_servername_callback(self->ssl_ctx, _sock_tls_sni_callback);

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

402 return SOCK_ERR_OK;

403}

404

405// @impl sock_bind_listen

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

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

408 if (err != SOCK_ERR_OK) {

409 return err;

410 }

411 return sock_listen(self);

412}

413

414// @impl sock_close

415void sock_close(sock_t *self) {

416 self->quit = true;

417 pthread_join(self->thread, NULL);

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

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

420 }

421}

422

423#endif // SO_SOCK_IMPL

424#endif // _SO_SOCK_H