aboutsummaryrefslogtreecommitdiffstats
path: root/src/lua/lua_ip.c
blob: 92a0664067b23361ef9ae818cb257c95cb0ebc1b (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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/*-
 * Copyright 2016 Vsevolod Stakhov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "lua_common.h"
#include "libserver/maps/map_helpers.h"

/***
 * @module rspamd_ip
 * `rspamd_ip` is a helper module to simplify IP addresses manipulations.
 * @example
local print_octets = function(ip)
        print('Normal order octets:')
        for _,o in ipairs(ip:str_octets()) do
                print(o)
        end
        print('Reversed order octets:')
        for _,o in ipairs(ip:inversed_str_octets()) do
                print(o)
        end
        print('Numeric octets:')
        for _,o in ipairs(ip:to_table()) do
                print(o)
        end
end

local rspamd_ip = require "rspamd_ip"
-- Create ipv4
local ip4 = rspamd_ip.from_string('127.0.0.1')
-- Implicit conversion to string
print(ip4)
-- Numeric version
print(ip4:get_version())
print_octets(ip4)

-- Create a sample ipv6 address
local ip6 = rspamd_ip.from_string('2001:41d0:8:dd9a::100')
print(ip6)
print(ip6:get_version())
print_octets(ip6)
 */

/***
 * @method ip:to_string([pretty=false])
 * Converts valid IP address to string
 * @param {bool} pretty print IP address with port and braces (for IPv6)
 * @return {string or nil} string representation of IP or `nil` if IP is invalid
 */
LUA_FUNCTION_DEF(ip, to_string);
/***
 * @method ip:to_number()
 * Converts valid IP address to number or list of numbers in case of IPv6
 * @return {integer(s) or nil} numeric representation of IP in *host* byte order or `nil` if IP is invalid
 */
LUA_FUNCTION_DEF(ip, to_number);

/***
 * @method ip:to_table()
 * Converts valid IP address to the table of numeric octets
 * @return {table or nil} numeric octets of IP address or `nil` if IP is invalid
 * @example
local ip = rspamd_ip.from_string('127.0.0.1')
for _,o in ipairs(ip:to_table()) do
    print(o)
end
-- Output:
-- 127
-- 0
-- 0
-- 1
 */
LUA_FUNCTION_DEF(ip, to_table);
/***
 * @method ip:str_octets()
 * Converts valid IP address to the table of string octets. The difference from
 * @see ip:to_table() is that this method returns just hex strings for ipv6
 * addresses.
 * @return {table or nil} string octets of IP address or `nil` if IP is invalid
 */
LUA_FUNCTION_DEF(ip, str_octets);
/***
 * @method ip:str_octets()
 * Converts valid IP address to the table of string octets in reversed order. The difference from
 * @see ip:to_table() is that this method returns just hex strings for ipv6
 * addresses.
 * @return {table or nil} string octets of IP address or `nil` if IP is invalid
 * @example
local ip = rspamd_ip.from_string('127.0.0.1')
for _,o in ipairs(ip:to_table()) do
    print(o)
end
-- Output:
-- 1
-- 0
-- 0
-- 127
 */
LUA_FUNCTION_DEF(ip, inversed_str_octets);
/***
 * @function rspamd_ip.from_string(line)
 * Create IP address from its string representation.
 * @param {string} line valid IP address string (either ipv4 or ipv6)
 * @return {ip} new ip object or `nil` if input is invalid
 */
LUA_FUNCTION_DEF(ip, from_string);
/***
 * @method ip:__gc()
 * Automatically destroys IP object.
 */
LUA_FUNCTION_DEF(ip, destroy);
/***
 * @method ip:get_version()
 * Gets numeric version of ip address
 * @return {number} `4` for IPv4 and `6` for IPv6
 */
LUA_FUNCTION_DEF(ip, get_version);
/***
 * @method ip:is_valid()
 * Checks if an IP object is a valid IP address.
 * @return {boolean} `true` if IP is valid and `false` otherwise
 */
LUA_FUNCTION_DEF(ip, is_valid);
/***
 * @method ip:apply_mask(mask)
 * Applies mask to IP address, resetting up to `mask` least significant bits to zero.
 * @param {integer} mask how many bits to reset
 * @return {ip} new IP object with `mask` bits reset
 */
LUA_FUNCTION_DEF(ip, apply_mask);
/***
 * @method ip:__eq(other)
 * Compares two IP addresses
 * @param {ip} other IP to compare
 * @return {boolean} `true` if two objects are the same
 */
LUA_FUNCTION_DEF(ip, equal);
/***
 * @method ip:copy()
 * Performs deep copy of IP address.
 * @return {ip} a fresh copy of IP address
 */
LUA_FUNCTION_DEF(ip, copy);

/**
 * @method ip:get_port()
 * Returns associated port for this IP address
 * @return {number} port number or nil
 */
LUA_FUNCTION_DEF(ip, get_port);
/***
 * @method ip:is_local()
 * Returns true if address is local one
 * @return {boolean} `true` if address is local
 */
LUA_FUNCTION_DEF(ip, is_local);

/***
 * @method ip:less_than(other)
 * Returns true if address is less than other
 * @return {boolean}
 */
LUA_FUNCTION_DEF(ip, less_than);

static const struct luaL_reg iplib_m[] = {
	LUA_INTERFACE_DEF(ip, to_string),
	LUA_INTERFACE_DEF(ip, to_table),
	LUA_INTERFACE_DEF(ip, to_number),
	LUA_INTERFACE_DEF(ip, str_octets),
	LUA_INTERFACE_DEF(ip, inversed_str_octets),
	LUA_INTERFACE_DEF(ip, get_version),
	LUA_INTERFACE_DEF(ip, get_port),
	LUA_INTERFACE_DEF(ip, is_valid),
	LUA_INTERFACE_DEF(ip, apply_mask),
	LUA_INTERFACE_DEF(ip, copy),
	LUA_INTERFACE_DEF(ip, is_local),
	{"tostring", lua_ip_to_string},
	{"totable", lua_ip_to_table},
	{"tonumber", lua_ip_to_number},
	{"__tostring", lua_ip_to_string},
	{"__eq", lua_ip_equal},
	{"__gc", lua_ip_destroy},
	{"__lt", lua_ip_less_than},
	{NULL, NULL}};

static const struct luaL_reg iplib_f[] = {
	LUA_INTERFACE_DEF(ip, from_string),
	{"fromstring", lua_ip_from_string},
	{"fromip", lua_ip_copy},
	{"from_ip", lua_ip_copy},
	{NULL, NULL}};

static struct rspamd_lua_ip *
lua_ip_new(lua_State *L, struct rspamd_lua_ip *old)
{
	struct rspamd_lua_ip *ip, **pip;

	ip = g_malloc0(sizeof(*ip));

	if (old != NULL && old->addr != NULL) {
		ip->addr = rspamd_inet_address_copy(old->addr, NULL);
	}

	pip = lua_newuserdata(L, sizeof(struct rspamd_lua_ip *));
	rspamd_lua_setclass(L, "rspamd{ip}", -1);
	*pip = ip;


	return ip;
}

struct rspamd_lua_ip *
lua_check_ip(lua_State *L, gint pos)
{
	void *ud = rspamd_lua_check_udata(L, pos, "rspamd{ip}");

	luaL_argcheck(L, ud != NULL, pos, "'ip' expected");
	return ud ? *((struct rspamd_lua_ip **) ud) : NULL;
}

static gint
lua_ip_to_table(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);
	guint max, i;
	guint8 *ptr;

	if (ip != NULL && ip->addr) {
		ptr = rspamd_inet_address_get_hash_key(ip->addr, &max);
		lua_createtable(L, max, 0);

		for (i = 1; i <= max; i++, ptr++) {
			lua_pushinteger(L, *ptr);
			lua_rawseti(L, -2, i);
		}
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_str_octets(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);
	guint max, i;
	guint8 *ptr;
	gint af;
	char numbuf[8];

	if (ip != NULL && ip->addr) {
		af = rspamd_inet_address_get_af(ip->addr);
		ptr = rspamd_inet_address_get_hash_key(ip->addr, &max);
		lua_createtable(L, max * 2, 0);

		for (i = 1; i <= max; i++, ptr++) {
			if (af == AF_INET) {
				rspamd_snprintf(numbuf, sizeof(numbuf), "%d", *ptr);
				lua_pushstring(L, numbuf);
				lua_rawseti(L, -2, i);
			}
			else {
				rspamd_snprintf(numbuf,
								sizeof(numbuf),
								"%xd",
								(*ptr & 0xf0) >> 4);
				lua_pushstring(L, numbuf);
				lua_rawseti(L, -2, i * 2 - 1);
				rspamd_snprintf(numbuf, sizeof(numbuf), "%xd", *ptr & 0x0f);
				lua_pushstring(L, numbuf);
				lua_rawseti(L, -2, i * 2);
			}
		}
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_inversed_str_octets(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);
	guint max, i;
	guint8 *ptr;
	char numbuf[4];
	gint af;

	if (ip != NULL && ip->addr) {
		ptr = rspamd_inet_address_get_hash_key(ip->addr, &max);
		af = rspamd_inet_address_get_af(ip->addr);
		lua_createtable(L, max * 2, 0);

		ptr += max - 1;
		for (i = 1; i <= max; i++, ptr--) {
			if (af == AF_INET) {
				rspamd_snprintf(numbuf, sizeof(numbuf), "%d", *ptr);
				lua_pushstring(L, numbuf);
				lua_rawseti(L, -2, i);
			}
			else {
				rspamd_snprintf(numbuf, sizeof(numbuf), "%xd", *ptr & 0x0f);
				lua_pushstring(L, numbuf);
				lua_rawseti(L, -2, i * 2 - 1);
				rspamd_snprintf(numbuf,
								sizeof(numbuf),
								"%xd",
								(*ptr & 0xf0) >> 4);
				lua_pushstring(L, numbuf);
				lua_rawseti(L, -2, i * 2);
			}
		}
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_to_string(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);

	if (ip != NULL && ip->addr) {
		if (lua_isboolean(L, 2) && lua_toboolean(L, 2) == true) {
			lua_pushstring(L, rspamd_inet_address_to_string_pretty(ip->addr));
		}
		else {
			lua_pushstring(L, rspamd_inet_address_to_string(ip->addr));
		}
	}
	else {
		luaL_error(L, "invalid arguments");
	}

	return 1;
}

static gint
lua_ip_get_port(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);

	if (ip != NULL && ip->addr) {
		lua_pushinteger(L, rspamd_inet_address_get_port(ip->addr));
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_from_string(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip;
	const gchar *ip_str;
	gsize len;

	ip_str = luaL_checklstring(L, 1, &len);
	if (ip_str) {
		ip = lua_ip_new(L, NULL);

		if (!rspamd_parse_inet_address(&ip->addr,
									   ip_str, len, RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
			msg_warn("cannot parse ip: %*s", (gint) len, ip_str);
			ip->addr = NULL;
		}
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_to_number(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);
	guint32 c;
	guint max, i;
	guchar *ptr;

	if (ip != NULL && ip->addr) {
		ptr = rspamd_inet_address_get_hash_key(ip->addr, &max);

		for (i = 0; i < max / sizeof(c); i++) {
			memcpy(&c, ptr + i * sizeof(c), sizeof(c));
			lua_pushinteger(L, ntohl(c));
		}

		return max / sizeof(c);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}


static gint
lua_ip_destroy(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);

	if (ip) {
		if (ip->addr) {
			rspamd_inet_address_free(ip->addr);
		}
		g_free(ip);
	}

	return 0;
}

static gint
lua_ip_get_version(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);

	if (ip && ip->addr) {
		lua_pushinteger(L, rspamd_inet_address_get_af(ip->addr) == AF_INET6 ? 6 : 4);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_is_valid(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);

	if (ip) {
		lua_pushboolean(L, ip->addr != NULL);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_apply_mask(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1), *nip;
	gint mask;

	mask = lua_tonumber(L, 2);
	if (mask > 0 && ip != NULL && ip->addr) {
		nip = lua_ip_new(L, ip);
		rspamd_inet_address_apply_mask(nip->addr, mask);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_equal(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip1 = lua_check_ip(L, 1),
						 *ip2 = lua_check_ip(L, 2);
	gboolean res = FALSE;

	if (ip1 && ip2 && ip1->addr && ip2->addr) {
		res = rspamd_inet_address_compare(ip1->addr, ip2->addr, TRUE) == 0;
	}

	lua_pushboolean(L, res);

	return 1;
}

static gint
lua_ip_copy(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);

	if (ip) {
		lua_ip_new(L, ip);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_is_local(lua_State *L)
{
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1);
	gboolean check_laddrs = TRUE;

	if (ip && ip->addr) {

		if (lua_type(L, 2) == LUA_TBOOLEAN) {
			check_laddrs = lua_toboolean(L, 2);
		}

		if (rspamd_inet_address_is_local(ip->addr)) {
			lua_pushboolean(L, true);

			return 1;
		}
		else if (check_laddrs) {
			struct rspamd_radix_map_helper *local_addrs =
				rspamd_inet_library_get_lib_ctx();
			if (local_addrs) {
				if (rspamd_match_radix_map_addr(local_addrs, ip->addr) != NULL) {
					lua_pushboolean(L, true);

					return 1;
				}
			}
		}

		lua_pushboolean(L, false);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

static gint
lua_ip_less_than(lua_State *L)
{
	LUA_TRACE_POINT;
	struct rspamd_lua_ip *ip = lua_check_ip(L, 1),
						 *other = lua_check_ip(L, 2);

	if (ip && other) {
		lua_pushboolean(L,
						rspamd_inet_address_compare(ip->addr, other->addr, true) < 0);
	}
	else {
		lua_pushnil(L);
	}

	return 1;
}

void rspamd_lua_ip_push(lua_State *L, rspamd_inet_addr_t *addr)
{
	struct rspamd_lua_ip *ip, **pip;

	if (addr) {
		ip = g_malloc0(sizeof(struct rspamd_lua_ip));
		ip->addr = rspamd_inet_address_copy(addr, NULL);
		pip = lua_newuserdata(L, sizeof(struct rspamd_lua_ip *));
		rspamd_lua_setclass(L, "rspamd{ip}", -1);
		*pip = ip;
	}
	else {
		lua_pushnil(L);
	}
}

void rspamd_lua_ip_push_fromstring(lua_State *L, const gchar *ip_str)
{
	struct rspamd_lua_ip *ip, **pip;

	if (ip_str == NULL) {
		lua_pushnil(L);
	}
	else {
		ip = g_malloc0(sizeof(struct rspamd_lua_ip));

		if (rspamd_parse_inet_address(&ip->addr,
									  ip_str, strlen(ip_str), RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {

			pip = lua_newuserdata(L, sizeof(struct rspamd_lua_ip *));
			rspamd_lua_setclass(L, "rspamd{ip}", -1);
			*pip = ip;
		}
		else {
			g_free(ip);
			lua_pushnil(L);
		}
	}
}

static gint
lua_load_ip(lua_State *L)
{
	lua_newtable(L);
	luaL_register(L, NULL, iplib_f);

	return 1;
}

void luaopen_ip(lua_State *L)
{
	rspamd_lua_new_class(L, "rspamd{ip}", iplib_m);
	lua_pop(L, 1);
	rspamd_lua_add_preload(L, "rspamd_ip", lua_load_ip);
}