-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminetd.c
More file actions
614 lines (525 loc) · 15.4 KB
/
minetd.c
File metadata and controls
614 lines (525 loc) · 15.4 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <poll.h>
#include <time.h>
#include <sys/stat.h>
#define MAX_SERVICES 32
#define MAX_ARGS 16
#define MAX_LINE 512
#define MAX_CONN_RATE 60 /* default max per window */
#define RATE_WINDOW_SEC 60 /* 1-minute window */
struct service {
int fd; /* listening socket, -1 if unused */
char *name; /* label */
char *cmdline; /* raw command line (owned) */
char *args[MAX_ARGS + 1]; /* argv for execvp */
int max_conn; /* max connections per window */
time_t window_start; /* rate limiting window start */
int conn_count; /* connections in current window */
};
static struct service services[MAX_SERVICES];
static size_t num_services = 0;
static volatile sig_atomic_t stop_flag = 0;
static volatile sig_atomic_t reload_flag = 0;
static const char *g_config_path = "/etc/minetd.conf";
static const char *g_pidfile_path = "/var/run/minetd.pid";
/* ---------- Signal handlers ---------- */
static void on_sigint(int sig) {
(void)sig;
stop_flag = 1;
}
static void on_sigchld(int sig) {
(void)sig;
int saved = errno;
while (waitpid(-1, NULL, WNOHANG) > 0) {}
errno = saved;
}
static void on_sighup(int sig) {
(void)sig;
reload_flag = 1;
}
/* ---------- Small helpers ---------- */
static int set_nonblock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags < 0) return -1;
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) return -1;
return 0;
}
static char *trim(char *s) {
char *end;
while (*s && (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
s++;
if (*s == '\0') return s;
end = s + strlen(s) - 1;
while (end > s && (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r')) {
*end-- = '\0';
}
return s;
}
/* Parse "host:port" into malloc'd host/port strings. Caller frees. */
static int parse_listen(const char *spec, char **host_out, char **port_out) {
const char *colon = strrchr(spec, ':');
if (!colon || colon == spec) {
return -1;
}
size_t host_len = (size_t)(colon - spec);
char *h = malloc(host_len + 1);
if (!h) return -1;
memcpy(h, spec, host_len);
h[host_len] = '\0';
char *p = strdup(colon + 1);
if (!p) {
free(h);
return -1;
}
*host_out = h;
*port_out = p;
return 0;
}
/* Create listening socket. host may be NULL for AI_PASSIVE. */
static int create_listener(const char *host, const char *port) {
struct addrinfo hints, *res = NULL, *rp;
int fd = -1;
int yes = 1;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
int rc = getaddrinfo(host, port, &hints, &res);
if (rc != 0) {
fprintf(stderr, "getaddrinfo(%s,%s): %s\n",
host ? host : "*", port, gai_strerror(rc));
return -1;
}
for (rp = res; rp != NULL; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd < 0)
continue;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
close(fd);
fd = -1;
continue;
}
if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0) {
close(fd);
fd = -1;
continue;
}
if (listen(fd, 16) < 0) {
close(fd);
fd = -1;
continue;
}
break; /* success */
}
freeaddrinfo(res);
if (fd < 0) {
fprintf(stderr, "Failed to bind %s:%s\n", host ? host : "*", port);
return -1;
}
if (set_nonblock(fd) < 0) {
perror("set_nonblock");
close(fd);
return -1;
}
return fd;
}
/* Split cmdline (in-place) into argv. */
static int split_cmdline(char *cmdline, char **argv_out, size_t max_args) {
size_t argc = 0;
char *p = cmdline;
while (*p && argc < max_args) {
while (*p == ' ' || *p == '\t')
p++;
if (!*p)
break;
char *start = p;
while (*p && *p != ' ' && *p != '\t')
p++;
if (*p) {
*p = '\0';
p++;
}
argv_out[argc++] = start;
}
argv_out[argc] = NULL;
return (int)argc;
}
/* ---------- Service lifecycle helpers ---------- */
static void clear_service(struct service *svc) {
if (svc->fd >= 0) {
close(svc->fd);
svc->fd = -1;
}
if (svc->name) {
free(svc->name);
svc->name = NULL;
}
if (svc->cmdline) {
free(svc->cmdline);
svc->cmdline = NULL;
}
for (size_t i = 0; i < MAX_ARGS + 1; i++) {
svc->args[i] = NULL;
}
svc->max_conn = 0;
svc->window_start = 0;
svc->conn_count = 0;
}
static void clear_all_services(struct service *svcs, size_t *n) {
for (size_t i = 0; i < *n; i++) {
clear_service(&svcs[i]);
}
*n = 0;
}
/* Add service into arbitrary array (for normal load or reload) */
static int add_service_to_array(struct service *svcs,
size_t *num_svcs,
size_t max_svcs,
char *name,
char *listen_spec,
char *cmdline,
int max_conn)
{
if (*num_svcs >= max_svcs) {
fprintf(stderr, "Too many services (max %zu)\n", max_svcs);
return -1;
}
char *host = NULL, *port = NULL;
if (parse_listen(listen_spec, &host, &port) < 0) {
fprintf(stderr, "Invalid listen spec: %s (expected host:port)\n", listen_spec);
free(host);
free(port);
return -1;
}
int fd = create_listener(*host ? host : NULL, port);
free(host);
free(port);
if (fd < 0)
return -1;
struct service *svc = &svcs[*num_svcs];
memset(svc, 0, sizeof(*svc));
svc->fd = fd;
svc->name = strdup(name);
svc->cmdline = strdup(cmdline);
svc->max_conn = (max_conn > 0) ? max_conn : MAX_CONN_RATE;
svc->window_start = time(NULL);
svc->conn_count = 0;
if (!svc->name || !svc->cmdline) {
perror("strdup");
clear_service(svc);
return -1;
}
split_cmdline(svc->cmdline, svc->args, MAX_ARGS);
if (!svc->args[0]) {
fprintf(stderr, "Service %s: empty command\n", svc->name);
clear_service(svc);
return -1;
}
(*num_svcs)++;
return 0;
}
/* Load config into a given array. On error, does NOT touch caller's existing services. */
static int load_config_into(const char *path,
struct service *svcs,
size_t *out_num,
size_t max_svcs)
{
FILE *f = fopen(path, "r");
if (!f) {
perror("fopen config");
return -1;
}
char line[MAX_LINE];
int lineno = 0;
size_t n = 0;
while (fgets(line, sizeof(line), f)) {
lineno++;
char *s = trim(line);
if (*s == '#' || *s == '\0')
continue;
/* Format:
service <name> <host:port> <max_conn_per_min> <prog> [args...]
*/
char *kw = strtok(s, " \t");
if (!kw || strcmp(kw, "service") != 0) {
fprintf(stderr, "%s:%d: expected 'service' keyword\n", path, lineno);
continue;
}
char *svc_name = strtok(NULL, " \t");
char *listen_spec = strtok(NULL, " \t");
char *max_str = strtok(NULL, " \t");
char *cmd = strtok(NULL, "\n");
if (!svc_name || !listen_spec || !max_str || !cmd) {
fprintf(stderr, "%s:%d: invalid service line\n", path, lineno);
continue;
}
cmd = trim(cmd);
int max_conn = atoi(max_str);
if (add_service_to_array(svcs, &n, max_svcs, svc_name, listen_spec, cmd, max_conn) < 0) {
fprintf(stderr, "%s:%d: failed to add service\n", path, lineno);
/* keep going, but we don't add this one */
}
}
fclose(f);
if (n == 0) {
fprintf(stderr, "No valid services configured in %s\n", path);
return -1;
}
*out_num = n;
return 0;
}
/* Convenience wrapper for initial load into global array. */
static int load_config_global(const char *path) {
size_t n = 0;
if (load_config_into(path, services, &n, MAX_SERVICES) < 0) {
return -1;
}
num_services = n;
return 0;
}
/* Reload config on SIGHUP.
- Build a new array.
- If successful, replace old services.
- If not, keep old services running. */
static void reload_config(void) {
fprintf(stderr, "[minetd] Reloading config from %s\n", g_config_path);
struct service new_services[MAX_SERVICES];
memset(new_services, 0, sizeof(new_services));
size_t new_num = 0;
if (load_config_into(g_config_path, new_services, &new_num, MAX_SERVICES) < 0) {
fprintf(stderr, "[minetd] Reload failed, keeping existing configuration.\n");
clear_all_services(new_services, &new_num);
return;
}
/* Success: drop old services (close old listeners) */
clear_all_services(services, &num_services);
/* Move new configuration in (shallow copy, but ownership of fds+ptrs moves) */
memcpy(services, new_services, sizeof(struct service) * new_num);
num_services = new_num;
fprintf(stderr, "[minetd] Reload successful: %zu services\n", num_services);
}
/* ---------- Rate limiting ---------- */
static int check_rate(struct service *svc) {
time_t now = time(NULL);
if (now - svc->window_start >= RATE_WINDOW_SEC) {
svc->window_start = now;
svc->conn_count = 0;
}
if (svc->conn_count >= svc->max_conn) {
return -1; /* over limit */
}
svc->conn_count++;
return 0;
}
/* ---------- Client handling ---------- */
static void handle_client(struct service *svc) {
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
int client_fd = accept(svc->fd, (struct sockaddr *)&ss, &slen);
if (client_fd < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
perror("accept");
return;
}
if (check_rate(svc) < 0) {
const char msg[] = "Service busy, try later\n";
(void)write(client_fd, msg, sizeof(msg) - 1);
close(client_fd);
return;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
close(client_fd);
return;
}
if (pid == 0) {
/* Child */
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
signal(SIGHUP, SIG_DFL);
if (dup2(client_fd, STDIN_FILENO) < 0 ||
dup2(client_fd, STDOUT_FILENO) < 0 ||
dup2(client_fd, STDERR_FILENO) < 0) {
perror("dup2");
_exit(127);
}
if (client_fd > 2)
close(client_fd);
/* Close all other fds (paranoid) */
for (int i = 3; i < 1024; i++) {
close(i);
}
/* TODO: drop privileges, chroot, setrlimit, etc. here */
execvp(svc->args[0], svc->args);
perror("execvp");
_exit(127);
}
/* Parent */
close(client_fd);
}
/* ---------- PID file ---------- */
static void write_pidfile(void) {
FILE *f = fopen(g_pidfile_path, "w");
if (!f) {
perror("fopen pidfile");
return;
}
fprintf(f, "%d\n", (int)getpid());
fclose(f);
}
static void remove_pidfile(void) {
if (unlink(g_pidfile_path) < 0) {
/* not fatal */
}
}
static int send_reload_signal(void) {
FILE *f = fopen(g_pidfile_path, "r");
if (!f) {
fprintf(stderr, "minetd: cannot open pidfile %s\n", g_pidfile_path);
return 1;
}
int pid = 0;
if (fscanf(f, "%d", &pid) != 1 || pid <= 0) {
fprintf(stderr, "minetd: invalid pidfile %s\n", g_pidfile_path);
fclose(f);
return 1;
}
fclose(f);
if (kill((pid_t)pid, SIGHUP) != 0) {
perror("kill --reload");
return 1;
}
printf("Reload signal sent to minetd (pid %d)\n", pid);
return 0;
}
/* ---------- Main loop ---------- */
static void main_loop(void) {
while (!stop_flag) {
if (reload_flag) {
reload_flag = 0;
reload_config();
}
if (num_services == 0) {
/* Nothing to do, sleep a bit. */
struct timespec ts = { .tv_sec = 1, .tv_nsec = 0 };
nanosleep(&ts, NULL);
continue;
}
struct pollfd pfds[MAX_SERVICES];
nfds_t nfds = 0;
for (size_t i = 0; i < num_services; i++) {
pfds[nfds].fd = services[i].fd;
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
nfds++;
}
int rc = poll(pfds, nfds, 1000); /* 1 second timeout */
if (rc < 0) {
if (errno == EINTR)
continue;
perror("poll");
break;
}
if (rc == 0)
continue;
for (nfds_t i = 0; i < nfds; i++) {
if (pfds[i].revents & POLLIN) {
handle_client(&services[i]);
}
}
}
/* Graceful shutdown: close listeners, children exit naturally. */
clear_all_services(services, &num_services);
}
/* ---------- Daemonization ---------- */
static void daemonize(void) {
pid_t pid = fork();
if (pid < 0)
exit(1);
if (pid > 0)
exit(0); /* parent */
if (setsid() < 0)
exit(1);
pid = fork();
if (pid < 0)
exit(1);
if (pid > 0)
exit(0);
umask(027);
if (chdir("/") < 0) {
/* ignore */
}
int fd = open("/dev/null", O_RDWR);
if (fd >= 0) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > 2)
close(fd);
}
}
/* ---------- main ---------- */
static void print_usage(const char *prog) {
fprintf(stderr,
"Usage:\n"
" %s [-f] [-c config]\n"
" %s --reload\n",
prog, prog);
}
int main(int argc, char **argv) {
int foreground = 0;
/* First, handle control mode: --reload */
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--reload") == 0) {
return send_reload_signal();
}
}
int opt;
while ((opt = getopt(argc, argv, "fc:")) != -1) {
switch (opt) {
case 'f':
foreground = 1;
break;
case 'c':
g_config_path = optarg;
break;
default:
print_usage(argv[0]);
return 1;
}
}
if (load_config_global(g_config_path) < 0) {
fprintf(stderr, "Failed to load config, exiting.\n");
return 1;
}
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sigemptyset(&sa.sa_mask);
sa.sa_handler = on_sigint;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
sa.sa_handler = on_sigchld;
sigaction(SIGCHLD, &sa, NULL);
sa.sa_handler = on_sighup;
sigaction(SIGHUP, &sa, NULL);
if (!foreground) {
daemonize();
}
write_pidfile();
main_loop();
remove_pidfile();
return 0;
}