aboutsummaryrefslogtreecommitdiffstats
path: root/src/libutil/addr.c
blob: 3c4db3c8f9c1645adbee243b5eb192f6c0534ad1 (plain)
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
/* Copyright (c) 2014, Vsevolod Stakhov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *       * Redistributions of source code must retain the above copyright
 *         notice, this list of conditions and the following disclaimer.
 *       * Redistributions in binary form must reproduce the above copyright
 *         notice, this list of conditions and the following disclaimer in the
 *         documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "addr.h"
#include "util.h"
#include "logger.h"

enum {
	RSPAMD_IPV6_UNDEFINED = 0,
	RSPAMD_IPV6_SUPPORTED,
	RSPAMD_IPV6_UNSUPPORTED
} ipv6_status = RSPAMD_IPV6_UNDEFINED;


static void
rspamd_ip_validate_af (rspamd_inet_addr_t *addr)
{
	if (addr->addr.sa.sa_family != addr->af) {
		addr->addr.sa.sa_family = addr->af;
	}
	if (addr->af == AF_INET) {
		addr->slen = sizeof (addr->addr.s4);
	}
	else if (addr->af == AF_INET6) {
		addr->slen = sizeof (addr->addr.s6);
	}
	else if (addr->af == AF_UNIX) {
#ifdef SUN_LEN
		addr->slen = SUN_LEN (&addr->addr.su);
#else
		addr->slen = sizeof (addr->addr.su);
#endif
	}
}

static void
rspamd_ip_check_ipv6 (void)
{
	if (ipv6_status == RSPAMD_IPV6_UNDEFINED) {
		gint s, r;
		struct sockaddr_in6 sin6;
		const struct in6_addr ip6_local = IN6ADDR_LOOPBACK_INIT;

		s = socket (AF_INET6, SOCK_STREAM, 0);
		if (s == -1) {
			ipv6_status = RSPAMD_IPV6_UNSUPPORTED;
		}
		else {
			/*
			 * Some systems allow ipv6 sockets creating but not binding,
			 * so here we try to bind to some local address and check, whether it
			 * is possible
			 */
			memset (&sin6, 0, sizeof (sin6));
			sin6.sin6_family = AF_INET6;
			sin6.sin6_port = g_random_int_range (20000, 60000);
			sin6.sin6_addr = ip6_local;

			r = bind (s, (struct sockaddr *)&sin6, sizeof (sin6));
			if (r == -1 && errno != EADDRINUSE) {
				ipv6_status = RSPAMD_IPV6_UNSUPPORTED;
			}
			else {
				ipv6_status = RSPAMD_IPV6_SUPPORTED;
			}
			close (s);
		}
	}
}

gboolean
rspamd_ip_is_valid (rspamd_inet_addr_t *addr)
{
	const struct in_addr ip4_any = { INADDR_ANY }, ip4_none = { INADDR_NONE };
	const struct in6_addr ip6_any = IN6ADDR_ANY_INIT;
	gboolean ret = FALSE;

	if (G_LIKELY (addr->af == AF_INET)) {
		if (memcmp (&addr->addr.s4.sin_addr, &ip4_any,
			sizeof (struct in_addr)) != 0 &&
			memcmp (&addr->addr.s4.sin_addr, &ip4_none,
			sizeof (struct in_addr)) != 0) {
			ret = TRUE;
		}
	}
	else if (G_UNLIKELY (addr->af == AF_INET6)) {
		if (memcmp (&addr->addr.s6.sin6_addr, &ip6_any,
			sizeof (struct in6_addr)) != 0) {
			ret = TRUE;
		}
	}

	return ret;
}

gint
rspamd_accept_from_socket (gint sock, rspamd_inet_addr_t *addr)
{
	gint nfd, serrno;
	socklen_t len = sizeof (addr->addr.ss);

	if ((nfd = accept (sock, &addr->addr.sa, &len)) == -1) {
		if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK) {
			return 0;
		}
		return -1;
	}

	addr->slen = len;
	addr->af = addr->addr.sa.sa_family;

	if (rspamd_socket_nonblocking (nfd) < 0) {
		goto out;
	}

	/* Set close on exec */
	if (fcntl (nfd, F_SETFD, FD_CLOEXEC) == -1) {
		msg_warn ("fcntl failed: %d, '%s'", errno, strerror (errno));
		goto out;
	}

	return (nfd);

out:
	serrno = errno;
	close (nfd);
	errno = serrno;
	return (-1);

}

static gboolean
rspamd_parse_unix_path (rspamd_inet_addr_t *target, const char *src)
{
	gchar **tokens, **cur_tok, *p, *pwbuf;
	gint pwlen;
	struct passwd pw, *ppw;
	struct group gr, *pgr;

	tokens = g_strsplit_set (src, " ", -1);

	target->af = AF_UNIX;
	target->slen = sizeof (target->addr.su);
	rspamd_strlcpy (target->addr.su.sun_path, tokens[0],
			sizeof (target->addr.su.sun_path));
	#ifdef FREEBSD
	target->addr.su.sun_len = SUN_LEN (&target->addr.su);
	#endif

	target->mode = 00644;
	target->owner = 0;
	target->group = 0;

	cur_tok = &tokens[1];
	pwlen = sysconf (_SC_GETPW_R_SIZE_MAX);
	g_assert (pwlen > 0);
	pwbuf = g_alloca (pwlen);

	while (*cur_tok) {
		if (g_ascii_strncasecmp (*cur_tok, "mode=", sizeof ("mode=") - 1) == 0) {
			p = strchr (*cur_tok, '=');
			/* XXX: add error check */
			target->mode = strtoul (p + 1, NULL, 0);

			if (target->mode == 0) {
				msg_err ("bad mode: %s", p + 1);
				errno = EINVAL;
				return FALSE;
			}
		}
		else if (g_ascii_strncasecmp (*cur_tok, "owner=",
				sizeof ("owner=") - 1) == 0) {
			p = strchr (*cur_tok, '=');

			if (getpwnam_r (p + 1, &pw, pwbuf, pwlen, &ppw) != 0 || ppw == NULL) {
				msg_err ("bad user: %s", p + 1);
				if (ppw == NULL) {
					errno = ENOENT;
				}
				return FALSE;
			}
			target->owner = pw.pw_uid;
			target->group = pw.pw_gid;
		}
		else if (g_ascii_strncasecmp (*cur_tok, "group=",
				sizeof ("group=") - 1) == 0) {
			p = strchr (*cur_tok, '=');

			if (getgrnam_r (p + 1, &gr, pwbuf, pwlen, &pgr) != 0 || pgr == NULL) {
				msg_err ("bad group: %s", p + 1);
				if (pgr == NULL) {
					errno = ENOENT;
				}
				return FALSE;
			}
			target->group = gr.gr_gid;
		}
		cur_tok ++;
	}

	return TRUE;
}

gboolean
rspamd_parse_inet_address (rspamd_inet_addr_t *target, const char *src)
{
	gboolean ret = FALSE;

	rspamd_ip_check_ipv6 ();

	if (src[0] == '/' || src[0] == '.') {
		return rspamd_parse_unix_path (target, src);
	}
	else if (ipv6_status == RSPAMD_IPV6_SUPPORTED &&
			inet_pton (AF_INET6, src, &target->addr.s6.sin6_addr) == 1) {
		target->af = AF_INET6;
		target->slen = sizeof (target->addr.s6);
		ret = TRUE;
	}
	else if (inet_pton (AF_INET, src, &target->addr.s4.sin_addr) == 1) {
		target->af = AF_INET;
		target->slen = sizeof (target->addr.s4);
		ret = TRUE;
	}

	target->addr.sa.sa_family = target->af;

	return ret;
}

const char *
rspamd_inet_address_to_string (rspamd_inet_addr_t *addr)
{
	static char addr_str[INET6_ADDRSTRLEN + 1];

	switch (addr->af) {
	case AF_INET:
		return inet_ntop (addr->af, &addr->addr.s4.sin_addr, addr_str,
				   sizeof (addr_str));
	case AF_INET6:
		return inet_ntop (addr->af, &addr->addr.s6.sin6_addr, addr_str,
				   sizeof (addr_str));
	case AF_UNIX:
		return addr->addr.su.sun_path;
	}

	return "undefined";
}

uint16_t
rspamd_inet_address_get_port (rspamd_inet_addr_t *addr)
{
	switch (addr->af) {
	case AF_INET:
		return ntohs (addr->addr.s4.sin_port);
	case AF_INET6:
		return ntohs (addr->addr.s6.sin6_port);
	}

	return 0;
}

void
rspamd_inet_address_set_port (rspamd_inet_addr_t *addr, uint16_t port)
{
	switch (addr->af) {
	case AF_INET:
		addr->addr.s4.sin_port = htons (port);
		break;
	case AF_INET6:
		addr->addr.s6.sin6_port = htons (port);
		break;
	}
}

int
rspamd_inet_address_connect (rspamd_inet_addr_t *addr, gint type,
		gboolean async)
{
	int fd, r;

	if (addr == NULL) {
		return -1;
	}

	rspamd_ip_validate_af (addr);

	fd = rspamd_socket_create (addr->af, type, 0, async);
	if (fd == -1) {
		return -1;
	}

	r = connect (fd, &addr->addr.sa, addr->slen);

	if (r == -1) {
		if (!async || errno != EINPROGRESS) {
			close (fd);
			msg_warn ("connect failed: %d, '%s'", errno,
						strerror (errno));
			return -1;
		}
	}

	return fd;
}

int
rspamd_inet_address_listen (rspamd_inet_addr_t *addr, gint type,
		gboolean async)
{
	gint fd, r;
	gint on = 1;

	if (addr == NULL) {
		return -1;
	}

	rspamd_ip_validate_af (addr);
	fd = rspamd_socket_create (addr->af, type, 0, async);
	if (fd == -1) {
		return -1;
	}

	if (addr->af == AF_UNIX && access (addr->addr.su.sun_path, W_OK) != -1) {
		/* Unlink old socket */
		(void)unlink (addr->addr.su.sun_path);
	}

	setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof (gint));
	r = bind (fd, &addr->addr.sa, addr->slen);
	if (r == -1) {
		if (!async || errno != EINPROGRESS) {
			close (fd);
			msg_warn ("bind failed: %d, '%s'", errno,
						strerror (errno));
			return -1;
		}
	}

	if (type != SOCK_DGRAM) {

		if (addr->af == AF_UNIX) {
			/* Try to set mode and owner */
			if (chown (addr->addr.su.sun_path, addr->owner, addr->group) == -1) {
				msg_info ("cannot change owner for %s to %d:%d: %s",
						addr->addr.su.sun_path, addr->owner, addr->group,
						strerror (errno));
			}
			if (chmod (addr->addr.su.sun_path, addr->mode) == -1) {
				msg_info ("cannot change mode for %s to %od %s",
						addr->addr.su.sun_path, addr->mode, strerror (errno));
			}
		}
		r = listen (fd, -1);

		if (r == -1) {
			msg_warn ("listen failed: %d, '%s'", errno, strerror (errno));
			close (fd);
			return -1;
		}
	}

	return fd;
}

gboolean
rspamd_parse_host_port_priority_strv (gchar **tokens,
	rspamd_inet_addr_t **addr,
	guint *max_addrs,
	guint *priority,
	gchar **name,
	guint default_port,
	rspamd_mempool_t *pool)
{
	gchar *err_str, portbuf[8];
	const gchar *cur_tok, *cur_port;
	struct addrinfo hints, *res, *cur;
	rspamd_inet_addr_t *cur_addr;
	guint addr_cnt;
	guint port_parsed, priority_parsed, saved_errno = errno;
	gint r;

	rspamd_ip_check_ipv6 ();
	/* Now try to parse host and write address to ina */
	memset (&hints, 0, sizeof (hints));
	hints.ai_socktype = SOCK_STREAM; /* Type of the socket */
	hints.ai_flags = AI_NUMERICSERV;

	cur_tok = tokens[0];

	if (strcmp (cur_tok, "*") == 0) {
		hints.ai_flags |= AI_PASSIVE;
		cur_tok = NULL;
	}

	if (ipv6_status == RSPAMD_IPV6_SUPPORTED) {
		hints.ai_family = AF_UNSPEC;
	}
	else {
		hints.ai_family = AF_INET;
	}

	if (tokens[1] != NULL) {
		/* Port part */
		rspamd_strlcpy (portbuf, tokens[1], sizeof (portbuf));
		cur_port = portbuf;
		errno = 0;
		port_parsed = strtoul (tokens[1], &err_str, 10);
		if (*err_str != '\0' || errno != 0) {
			msg_warn ("cannot parse port: %s, at symbol %c, error: %s",
					tokens[1],
					*err_str,
					strerror (errno));
			hints.ai_flags ^= AI_NUMERICSERV;
		}
		else if (port_parsed > G_MAXUINT16) {
			errno = ERANGE;
			msg_warn ("cannot parse port: %s, error: %s",
					tokens[1],
					*err_str,
					strerror (errno));
			hints.ai_flags ^= AI_NUMERICSERV;
		}
		if (priority != NULL) {
			const gchar *tok;

			tok = tokens[2];
			if (tok != NULL) {
				/* Priority part */
				errno = 0;
				priority_parsed = strtoul (tok, &err_str, 10);
				if (*err_str != '\0' || errno != 0) {
					msg_warn (
						"cannot parse priority: %s, at symbol %c, error: %s",
						tok,
						*err_str,
						strerror (errno));
				}
				else {
					*priority = priority_parsed;
				}
			}
		}
	}
	else if (default_port != 0) {
		rspamd_snprintf (portbuf, sizeof (portbuf), "%ud", default_port);
		cur_port = portbuf;
	}
	else {
		cur_port = NULL;
	}

	if (*tokens[0] != '/') {
		if ((r = getaddrinfo (cur_tok, cur_port, &hints, &res)) == 0) {
			/* Now copy up to max_addrs of addresses */
			addr_cnt = 0;
			cur = res;
			while (cur && addr_cnt < *max_addrs) {
				cur = cur->ai_next;
				addr_cnt ++;
			}

			if (pool == NULL) {
				*addr = g_new (rspamd_inet_addr_t, addr_cnt);
			}
			else {
				*addr = rspamd_mempool_alloc (pool, addr_cnt *
						sizeof (rspamd_inet_addr_t));
			}

			cur = res;
			addr_cnt = 0;
			while (cur && addr_cnt < *max_addrs) {
				cur_addr = &(*addr)[addr_cnt];
				memcpy (&cur_addr->addr, cur->ai_addr,
						MIN (sizeof (cur_addr->addr), cur->ai_addrlen));
				cur_addr->af = cur->ai_family;
				rspamd_ip_validate_af (cur_addr);
				cur_addr->slen = cur->ai_addrlen;
				cur = cur->ai_next;
				addr_cnt ++;
			}

			*max_addrs = addr_cnt;

			freeaddrinfo (res);
		}
		else {
			msg_err ("address resolution for %s failed: %s",
					tokens[0],
					gai_strerror (r));
			goto err;
		}
	}
	else {
		/* Special case of unix socket, as getaddrinfo cannot deal with them */
		if (pool == NULL) {
			*addr = g_new0 (rspamd_inet_addr_t, 1);
		}
		else {
			*addr = rspamd_mempool_alloc0 (pool, sizeof (rspamd_inet_addr_t));
		}

		cur_addr = *addr;
		if (!rspamd_parse_inet_address (cur_addr, tokens[0])) {
			msg_err ("cannot parse unix socket definition %s: %s",
					tokens[0],
					strerror (errno));
			goto err;
		}
		*max_addrs = 1;
	}

	/* Restore errno */
	if (name != NULL) {
		if (pool == NULL) {
			*name = g_strdup (tokens[0]);
		}
		else {
			*name = rspamd_mempool_strdup (pool, tokens[0]);
		}
	}
	errno = saved_errno;
	return TRUE;

err:
	errno = saved_errno;
	return FALSE;
}

gboolean
rspamd_parse_host_port_priority (
	const gchar *str,
	rspamd_inet_addr_t **addr,
	guint *max_addrs,
	guint *priority,
	gchar **name,
	guint default_port,
	rspamd_mempool_t *pool)
{
	gchar **tokens;
	gboolean ret;

	tokens = g_strsplit_set (str, ":", 0);
	if (!tokens || !tokens[0]) {
		return FALSE;
	}

	ret = rspamd_parse_host_port_priority_strv (tokens, addr, max_addrs,
			priority, name, default_port, pool);

	g_strfreev (tokens);

	return ret;
}

gboolean
rspamd_parse_host_port (const gchar *str,
	rspamd_inet_addr_t **addr,
	guint *max_addrs,
	gchar **name,
	guint default_port,
	rspamd_mempool_t *pool)
{
	return rspamd_parse_host_port_priority (str, addr, max_addrs, NULL,
			name, default_port, pool);
}