summaryrefslogtreecommitdiffstats
path: root/src/libnfnetlink.c
blob: 756893b7a9c180e35cc1114070bf35d171da6708 (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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
/* libnfnetlink.c: generic library for communication with netfilter
 *
 * (C) 2002-2006 by Harald Welte <laforge@gnumonks.org>
 *
 * Based on some original ideas from Jay Schulist <jschlst@samba.org>
 *
 * Development of this code funded by Astaro AG (http://www.astaro.com)
 *
 * this software may be used and distributed according to the terms
 * of the gnu general public license, incorporated herein by reference.
 *
 * 2005-09-14 Pablo Neira Ayuso <pablo@netfilter.org>: 
 * 	Define structure nfnlhdr
 * 	Added __be64_to_cpu function
 *	Use NFA_TYPE macro to get the attribute type
 *
 * 2006-01-14 Harald Welte <laforge@netfilter.org>:
 * 	introduce nfnl_subsys_handle
 *
 * 2006-01-15 Pablo Neira Ayuso <pablo@netfilter.org>:
 * 	set missing subsys_id in nfnl_subsys_open
 * 	set missing nfnlh->local.nl_pid in nfnl_open
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <netinet/in.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <libnfnetlink/libnfnetlink.h>

#define nfnl_error(format, args...) \
	fprintf(stderr, "%s: " format "\n", __FUNCTION__, ## args)

#ifdef _NFNL_DEBUG
#define nfnl_debug_dump_packet nfnl_dump_packet
#else
#define nfnl_debug_dump_packet(a, b, ...)
#endif

struct nfnl_subsys_handle {
	struct nfnl_handle 	*nfnlh;
	u_int32_t		subscriptions;
	u_int8_t		subsys_id;
	u_int8_t		cb_count;
	struct nfnl_callback 	*cb;	/* array of callbacks */
};

#define		NFNL_MAX_SUBSYS			16 /* enough for now */
struct nfnl_handle {
	int			fd;
	struct sockaddr_nl	local;
	struct sockaddr_nl	peer;
	u_int32_t		subscriptions;
	u_int32_t		seq;
	u_int32_t		dump;
	struct nlmsghdr 	*last_nlhdr;
	struct nfnl_subsys_handle subsys[NFNL_MAX_SUBSYS+1];
};

void nfnl_dump_packet(struct nlmsghdr *nlh, int received_len, char *desc)
{
	void *nlmsg_data = NLMSG_DATA(nlh);
	struct nfattr *nfa = NFM_NFA(NLMSG_DATA(nlh));
	int len = NFM_PAYLOAD(nlh);

	printf("%s called from %s\n", __FUNCTION__, desc);
	printf("  nlmsghdr = %p, received_len = %u\n", nlh, received_len);
	printf("  NLMSG_DATA(nlh) = %p (+%td bytes)\n", nlmsg_data,
	       (nlmsg_data - (void *)nlh));
	printf("  NFM_NFA(NLMSG_DATA(nlh)) = %p (+%td bytes)\n",
		nfa, ((void *)nfa - (void *)nlh));
	printf("  NFM_PAYLOAD(nlh) = %u\n", len);
	printf("  nlmsg_type = %u, nlmsg_len = %u, nlmsg_seq = %u "
		"nlmsg_flags = 0x%x\n", nlh->nlmsg_type, nlh->nlmsg_len,
		nlh->nlmsg_seq, nlh->nlmsg_flags);

	while (NFA_OK(nfa, len)) {
		printf("    nfa@%p: nfa_type=%u, nfa_len=%u\n",
			nfa, NFA_TYPE(nfa), nfa->nfa_len);
		nfa = NFA_NEXT(nfa,len);
	}
}

int nfnl_fd(struct nfnl_handle *h)
{
	return h->fd;
}

static int recalc_rebind_subscriptions(struct nfnl_handle *nfnlh)
{
	int i;
	u_int32_t new_subscriptions = 0;

	for (i = 0; i < NFNL_MAX_SUBSYS; i++)
		new_subscriptions |= nfnlh->subsys[i].subscriptions;

	if (nfnlh->subscriptions != new_subscriptions) {
		int err;

		nfnlh->local.nl_groups = new_subscriptions;
		err = bind(nfnlh->fd, (struct sockaddr *)&nfnlh->local,
			   sizeof(nfnlh->local));
		if (err < 0) {
			nfnl_error("bind(netlink): %s", strerror(errno));
			return err;
		}
		nfnlh->subscriptions = new_subscriptions;
	}

	return 0;
}

/**
 * nfnl_open - open a netlink socket
 *
 * nfnlh: libnfnetlink handle to be allocated by user
 *
 */
struct nfnl_handle *nfnl_open(void)
{
	struct nfnl_handle *nfnlh;
	unsigned int addr_len;
	int err;

	nfnlh = malloc(sizeof(*nfnlh));
	if (!nfnlh)
		return NULL;

	memset(nfnlh, 0, sizeof(*nfnlh));
	nfnlh->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_NETFILTER);
	if (nfnlh->fd < 0) {
		nfnl_error("socket(netlink): %s", strerror(errno));
		goto err_free;
	}

	nfnlh->local.nl_family = AF_NETLINK;
	nfnlh->peer.nl_family = AF_NETLINK;

	addr_len = sizeof(nfnlh->local);
	err = getsockname(nfnlh->fd, (struct sockaddr *)&nfnlh->local, 
			  &addr_len);
	if (addr_len != sizeof(nfnlh->local)) {
		nfnl_error("Bad address length (%u != %zd)", addr_len,
			   sizeof(nfnlh->local));
		goto err_close;
	}
	if (nfnlh->local.nl_family != AF_NETLINK) {
		nfnl_error("Bad address family %d", nfnlh->local.nl_family);
		goto err_close;
	}
	nfnlh->seq = time(NULL);
	/*
	 * nfnl_talk checks: h->nlmsg_pid != nfnlh->local.nl_pid
	 */
	nfnlh->local.nl_pid = getpid();

	return nfnlh;

err_close:
	close(nfnlh->fd);
err_free:
	free(nfnlh);
	return NULL;
}

/**
 * nfnl_subsys_open - open a netlink subsystem
 *
 * nfnlh: libnfnetlink handle
 * subsys_id: which nfnetlink subsystem we are interested in
 * cb_count: number of callbacks that are used maximum.
 * subscriptions: netlink groups we want to be subscribed to
 */
struct nfnl_subsys_handle *
nfnl_subsys_open(struct nfnl_handle *nfnlh, u_int8_t subsys_id,
		 u_int8_t cb_count, u_int32_t subscriptions)
{
	struct nfnl_subsys_handle *ssh;

	if (subsys_id > NFNL_MAX_SUBSYS) { 

		return NULL;
	}

	ssh = &nfnlh->subsys[subsys_id];
	if (ssh->cb) {

		return NULL;
	}

	ssh->cb = malloc(sizeof(*(ssh->cb)) * cb_count);
	if (!ssh->cb) {
		
		return NULL;
	}

	ssh->nfnlh = nfnlh;
	ssh->cb_count = cb_count;
	ssh->subscriptions = subscriptions;
	ssh->subsys_id = subsys_id;

	if (recalc_rebind_subscriptions(nfnlh) < 0) {
		free(ssh->cb);
		ssh->cb = NULL;
		return NULL;
	}
	
	return ssh;
}

void nfnl_subsys_close(struct nfnl_subsys_handle *ssh)
{
	ssh->subscriptions = 0;
	ssh->cb_count = 0;
	if (ssh->cb) {
		free(ssh->cb);
		ssh->cb = NULL;
	}
}

/**
 * nfnl_close - close netlink socket
 *
 * nfnlh: libnfnetlink handle
 *
 */
int nfnl_close(struct nfnl_handle *nfnlh)
{
	int i, ret;

	for (i = 0; i < NFNL_MAX_SUBSYS; i++)
		nfnl_subsys_close(&nfnlh->subsys[i]);

	ret = close(nfnlh->fd);
	if (ret < 0)
		return ret;

	free(nfnlh);

	return 0;
}

/**
 * nfnl_send - send a nfnetlink message through netlink socket
 *
 * nfnlh: libnfnetlink handle
 * n: netlink message
 */
int nfnl_send(struct nfnl_handle *nfnlh, struct nlmsghdr *n)
{
	nfnl_debug_dump_packet(n, n->nlmsg_len+sizeof(*n), "nfnl_send");

	return sendto(nfnlh->fd, n, n->nlmsg_len, 0, 
		      (struct sockaddr *)&nfnlh->peer, sizeof(nfnlh->peer));
}

int nfnl_sendmsg(const struct nfnl_handle *nfnlh, const struct msghdr *msg,
		 unsigned int flags)
{
	return sendmsg(nfnlh->fd, msg, flags);
}

int nfnl_sendiov(const struct nfnl_handle *nfnlh, const struct iovec *iov,
		 unsigned int num, unsigned int flags)
{
	struct msghdr msg;

	msg.msg_name = (struct sockaddr *) &nfnlh->peer;
	msg.msg_namelen = sizeof(nfnlh->peer);
	msg.msg_iov = (struct iovec *) iov;
	msg.msg_iovlen = num;
	msg.msg_control = NULL;
	msg.msg_controllen = 0;
	msg.msg_flags = 0;

	return nfnl_sendmsg(nfnlh, &msg, flags);
}

/**
 * nfnl_fill_hdr - fill in netlink and nfnetlink header
 *
 * nfnlh: libnfnetlink handle
 * nlh: netlink header to be filled in
 * len: length of _payload_ bytes (not including nfgenmsg)
 * family: AF_INET / ...
 * res_id: resource id
 * msg_type: nfnetlink message type (without subsystem)
 * msg_flags: netlink message flags
 *
 * NOTE: the nlmsghdr must point to a memory region of at least
 * the size of struct nlmsghdr + struct nfgenmsg
 *
 */
void nfnl_fill_hdr(struct nfnl_subsys_handle *ssh,
		    struct nlmsghdr *nlh, unsigned int len, 
		    u_int8_t family,
		    u_int16_t res_id,
		    u_int16_t msg_type,
		    u_int16_t msg_flags)
{
	struct nfgenmsg *nfg = (struct nfgenmsg *) 
					((void *)nlh + sizeof(*nlh));

	nlh->nlmsg_len = NLMSG_LENGTH(len+sizeof(*nfg));
	nlh->nlmsg_type = (ssh->subsys_id<<8)|msg_type;
	nlh->nlmsg_flags = msg_flags;
	nlh->nlmsg_pid = 0;
	nlh->nlmsg_seq = ++ssh->nfnlh->seq;

	nfg->nfgen_family = family;
	nfg->version = NFNETLINK_V0;
	nfg->res_id = htons(res_id);
}

struct nfattr *
nfnl_parse_hdr(const struct nfnl_handle *nfnlh,
		const struct nlmsghdr *nlh,
		struct nfgenmsg **genmsg)
{
	if (nlh->nlmsg_len < NLMSG_LENGTH(sizeof(struct nfgenmsg)))
		return NULL;

	if (nlh->nlmsg_len == NLMSG_LENGTH(sizeof(struct nfgenmsg))) {
		if (genmsg)
			*genmsg = (struct nfgenmsg *)((void *)nlh+sizeof(nlh));
		return NULL;
	}

	if (genmsg)
		*genmsg = (struct nfgenmsg *)((void *)nlh + sizeof(nlh));

	return ((void *)nlh + NLMSG_LENGTH(sizeof(struct nfgenmsg)));
}

ssize_t 
nfnl_recv(const struct nfnl_handle *h, unsigned char *buf, size_t len)
{
	socklen_t addrlen;
	int status;
	struct nlmsghdr *nlh;
	struct sockaddr_nl peer;
	
	if (len < sizeof(struct nlmsgerr)
	    || len < sizeof(struct nlmsghdr))
		return -1; 

	addrlen = sizeof(h->peer);
	status = recvfrom(h->fd, buf, len, 0, (struct sockaddr *)&peer,	
			&addrlen);
	if (status <= 0)
		return status;

	if (addrlen != sizeof(peer))
		return -1;

	if (peer.nl_pid != 0)
		return -1;

	nlh = (struct nlmsghdr *)buf;
	if (nlh->nlmsg_flags & MSG_TRUNC || status > len)
		return -1;

	return status;
}
/**
 * nfnl_listen: listen for one or more netlink messages
 *
 * nfnhl: libnfnetlink handle
 * handler: callback function to be called for every netlink message
 *          - the callback handler should normally return 0
 *          - but may return a negative error code which will cause
 *            nfnl_listen to return immediately with the same error code
 *          - or return a postivie error code which will cause 
 *            nfnl_listen to return after it has finished processing all
 *            the netlink messages in the current packet
 *          Thus a positive error code will terminate nfnl_listen "soon"
 *          without any loss of data, a negative error code will terminate
 *          nfnl_listen "very soon" and throw away data already read from
 *          the netlink socket.
 * jarg: opaque argument passed on to callback
 *
 */
int nfnl_listen(struct nfnl_handle *nfnlh,
		int (*handler)(struct sockaddr_nl *, struct nlmsghdr *n,
			       void *), void *jarg)
{
	struct sockaddr_nl nladdr;
	char buf[NFNL_BUFFSIZE];
	struct iovec iov;
	int remain;
	struct nlmsghdr *h;
	struct nlmsgerr *msgerr;
	int quit=0;

	struct msghdr msg = {
		(void *)&nladdr, sizeof(nladdr),
		&iov, 1,
		NULL, 0,
		0
	};

	memset(&nladdr, 0, sizeof(nladdr));
	nladdr.nl_family = AF_NETLINK;
	iov.iov_base = buf;
	iov.iov_len = sizeof(buf);

	while (! quit) {
		remain = recvmsg(nfnlh->fd, &msg, 0);
		if (remain < 0) {
			if (errno == EINTR)
				continue;
			/* Bad file descriptor */
			else if (errno == EBADF)
				break;
			else if (errno == EAGAIN)
				break;
			nfnl_error("recvmsg overrun: %s", strerror(errno));
			continue;
		}
		if (remain == 0) {
			nfnl_error("EOF on netlink");
			return -1;
		}
		if (msg.msg_namelen != sizeof(nladdr)) {
			nfnl_error("Bad sender address len (%d)",
				   msg.msg_namelen);
			return -1;
		}

		for (h = (struct nlmsghdr *)buf; remain >= sizeof(*h);) {
			int err;
			int len = h->nlmsg_len;
			int l = len - sizeof(*h);

			if (l < 0 || len > remain) {
				if (msg.msg_flags & MSG_TRUNC) {
					nfnl_error("MSG_TRUNC");
					return -1;
				}
				nfnl_error("Malformed msg (len=%d)", len);
				return -1;
			}

			/* end of messages reached, let's return */
			if (h->nlmsg_type == NLMSG_DONE)
				return 0;

			/* Break the loop if success is explicitely
			 * reported via NLM_F_ACK flag set */
			if (h->nlmsg_type == NLMSG_ERROR) {
				msgerr = NLMSG_DATA(h);
				return msgerr->error;
			}

			err = handler(&nladdr, h, jarg);
			if (err < 0)
				return err;
			quit |= err;
		
			/* FIXME: why not _NEXT macros, etc.? */
			//h = NLMSG_NEXT(h, remain);
			remain -= NLMSG_ALIGN(len);
			h = (struct nlmsghdr *)((char *)h + NLMSG_ALIGN(len));
		}
		if (msg.msg_flags & MSG_TRUNC) {
			nfnl_error("MSG_TRUNC");
			continue;
		}
		if (remain) {
			nfnl_error("remnant size %d", remain);
			return -1;
		}
	}

	return quit;
}

int nfnl_talk(struct nfnl_handle *nfnlh, struct nlmsghdr *n, pid_t peer,
	      unsigned groups, struct nlmsghdr *answer,
	      int (*junk)(struct sockaddr_nl *, struct nlmsghdr *n, void *),
	      void *jarg)
{
	char buf[NFNL_BUFFSIZE];
	struct sockaddr_nl nladdr;
	struct nlmsghdr *h;
	unsigned int seq;
	int status;
	struct iovec iov = {
		(void *)n, n->nlmsg_len
	};
	struct msghdr msg = {
		(void *)&nladdr, sizeof(nladdr),
		&iov, 1,
		NULL, 0,
		0
	};

	memset(&nladdr, 0, sizeof(nladdr));
	nladdr.nl_family = AF_NETLINK;
	nladdr.nl_pid = peer;
	nladdr.nl_groups = groups;

	n->nlmsg_seq = seq = ++nfnlh->seq;
	/* FIXME: why ? */
	if (!answer)
		n->nlmsg_flags |= NLM_F_ACK;

	status = sendmsg(nfnlh->fd, &msg, 0);
	if (status < 0) {
		nfnl_error("sendmsg(netlink) %s", strerror(errno));
		return -1;
	}
	iov.iov_base = buf;
	iov.iov_len = sizeof(buf);

	while (1) {
		status = recvmsg(nfnlh->fd, &msg, 0);
		if (status < 0) {
			if (errno == EINTR)
				continue;
			nfnl_error("recvmsg over-run");
			continue;
		}
		if (status == 0) {
			nfnl_error("EOF on netlink");
			return -1;
		}
		if (msg.msg_namelen != sizeof(nladdr)) {
			nfnl_error("Bad sender address len %d",
				   msg.msg_namelen);
			return -1;
		}

		for (h = (struct nlmsghdr *)buf; status >= sizeof(*h); ) {
			int len = h->nlmsg_len;
			int l = len - sizeof(*h);
			int err;

			if (l < 0 || len > status) {
				if (msg.msg_flags & MSG_TRUNC) {
					nfnl_error("Truncated message\n");
					return -1;
				}
				nfnl_error("Malformed message: len=%d\n", len);
				return -1; /* FIXME: libnetlink exits here */
			}

			if (h->nlmsg_pid != nfnlh->local.nl_pid ||
			    h->nlmsg_seq != seq) {
				if (junk) {
					err = junk(&nladdr, h, jarg);
					if (err < 0)
						return err;
				}
				goto cont;
			}

			if (h->nlmsg_type == NLMSG_ERROR) {
				struct nlmsgerr *err = NLMSG_DATA(h);
				if (l < sizeof(struct nlmsgerr))
					nfnl_error("ERROR truncated\n");
				else {
					errno = -err->error;
					if (errno == 0) {
						if (answer)
							memcpy(answer, h, h->nlmsg_len);
						return 0;
					}
					perror("NFNETLINK answers");
				}
				return err->error;
			}
			if (answer) {
				memcpy(answer, h, h->nlmsg_len);
				return 0;
			}

			nfnl_error("Unexpected reply!\n");
cont:
			status -= NLMSG_ALIGN(len);
			h = (struct nlmsghdr *)((char *)h + NLMSG_ALIGN(len));
		}
		if (msg.msg_flags & MSG_TRUNC) {
			nfnl_error("Messages truncated\n");
			continue;
		}
		if (status) {
			nfnl_error("Remnant of size %d\n", status);
			exit(1);
		}
	}
}

/**
 * nfnl_addattr_l - Add variable length attribute to nlmsghdr
 *
 * n: netlink message header to which attribute is to be added
 * maxlen: maximum length of netlink message header
 * type: type of new attribute
 * data: content of new attribute
 * alen: attribute length
 *
 */
int nfnl_addattr_l(struct nlmsghdr *n, int maxlen, int type, void *data,
		   int alen)
{
	int len = NFA_LENGTH(alen);
	struct nfattr *nfa;

	if ((NLMSG_ALIGN(n->nlmsg_len) + len) > maxlen) {
		nfnl_error("%d greater than maxlen (%d)\n",
			   NLMSG_ALIGN(n->nlmsg_len) + len, maxlen);
		return -1;
	}

	nfa = NLMSG_TAIL(n);
	nfa->nfa_type = type;
	nfa->nfa_len = len;
	memcpy(NFA_DATA(nfa), data, alen);
	n->nlmsg_len = (NLMSG_ALIGN(n->nlmsg_len) + NFA_ALIGN(len));
	return 0;
}

/**
 * nfnl_nfa_addattr_l - Add variable length attribute to struct nfattr 
 *
 * nfa: struct nfattr
 * maxlen: maximal length of nfattr buffer
 * type: type for new attribute
 * data: content of new attribute
 * alen: length of new attribute
 *
 */
int nfnl_nfa_addattr_l(struct nfattr *nfa, int maxlen, int type, void *data,
		       int alen)
{
	struct nfattr *subnfa;
	int len = NFA_LENGTH(alen);

	if ((NFA_OK(nfa, nfa->nfa_len) + len) > maxlen)
		return -1;

	subnfa = (struct nfattr *)(((char *)nfa) + NFA_OK(nfa, nfa->nfa_len));
	subnfa->nfa_type = type;
	subnfa->nfa_len = len;
	memcpy(NFA_DATA(subnfa), data, alen);
	nfa->nfa_len = (NLMSG_ALIGN(nfa->nfa_len) + len);

	return 0;
}


/**
 * nfnl_nfa_addattr32 - Add u_int32_t attribute to struct nfattr 
 *
 * nfa: struct nfattr
 * maxlen: maximal length of nfattr buffer
 * type: type for new attribute
 * data: content of new attribute
 *
 */
int nfnl_nfa_addattr32(struct nfattr *nfa, int maxlen, int type, 
		       u_int32_t data)
{

	return nfnl_nfa_addattr_l(nfa, maxlen, type, &data, sizeof(data));
}

/**
 * nfnl_addattr32 - Add u_int32_t attribute to nlmsghdr
 *
 * n: netlink message header to which attribute is to be added
 * maxlen: maximum length of netlink message header
 * type: type of new attribute
 * data: content of new attribute
 *
 */
int nfnl_addattr32(struct nlmsghdr *n, int maxlen, int type,
		   u_int32_t data)
{
	return nfnl_addattr_l(n, maxlen, type, &data, sizeof(data));
}

/**
 * nfnl_parse_attr - Parse a list of nfattrs into a pointer array
 *
 * tb: pointer array, will be filled in (output)
 * max: size of pointer array
 * nfa: pointer to list of nfattrs
 * len: length of 'nfa'
 *
 */
int nfnl_parse_attr(struct nfattr *tb[], int max, struct nfattr *nfa, int len)
{
	memset(tb, 0, sizeof(struct nfattr *) * max);

	while (NFA_OK(nfa, len)) {
		if (NFA_TYPE(nfa) <= max)
			tb[NFA_TYPE(nfa)-1] = nfa;
                nfa = NFA_NEXT(nfa,len);
	}
	if (len)
		nfnl_error("deficit (%d) len (%d).\n", len, nfa->nfa_len);

	return 0;
}

/**
 * nfnl_build_nfa_iovec - Build two iovec's from tag, length and value
 *
 * iov: pointer to array of two 'struct iovec' (caller-allocated)
 * nfa: pointer to 'struct nfattr' (caller-allocated)
 * type: type (tag) of attribute
 * len: length of value
 * val: pointer to buffer containing 'value'
 *
 */ 
void nfnl_build_nfa_iovec(struct iovec *iov, struct nfattr *nfa, 
			  u_int16_t type, u_int32_t len, unsigned char *val)
{
	iov[0].iov_base = nfa;
	iov[0].iov_len = sizeof(*nfa);
	iov[1].iov_base = val;
	iov[1].iov_len = NFA_ALIGN(len);
}

#ifndef SO_RCVBUFFORCE
#define SO_RCVBUFFORCE	(33)
#endif

unsigned int nfnl_rcvbufsiz(struct nfnl_handle *h, unsigned int size)
{
	int status;
	socklen_t socklen = sizeof(size);
	unsigned int read_size = 0;

	/* first we try the FORCE option, which is introduced in kernel
	 * 2.6.14 to give "root" the ability to override the system wide
	 * maximum */
	status = setsockopt(h->fd, SOL_SOCKET, SO_RCVBUFFORCE, &size, socklen);
	if (status < 0) {
		/* if this didn't work, we try at least to get the system
		 * wide maximum (or whatever the user requested) */
		setsockopt(h->fd, SOL_SOCKET, SO_RCVBUF, &size, socklen);
	}
	getsockopt(h->fd, SOL_SOCKET, SO_RCVBUF, &read_size, &socklen);

	return read_size;
}


struct nlmsghdr *nfnl_get_msg_first(struct nfnl_handle *h,
				    const unsigned char *buf,
				    size_t len)
{
	struct nlmsghdr *nlh;

	/* first message in buffer */
	nlh = (struct nlmsghdr *)buf;
	if (!NLMSG_OK(nlh, len))
		return NULL;
	h->last_nlhdr = nlh;

	return nlh;
}

struct nlmsghdr *nfnl_get_msg_next(struct nfnl_handle *h,
				   const unsigned char *buf,
				   size_t len)
{
	struct nlmsghdr *nlh;
	size_t remain_len;

	/* if last header in handle not inside this buffer, 
	 * drop reference to last header */
	if (!h->last_nlhdr ||
	    (unsigned char *)h->last_nlhdr >= (buf + len)  ||
	    (unsigned char *)h->last_nlhdr < buf) {
		h->last_nlhdr = NULL;
		return NULL;
	}

	/* n-th part of multipart message */
	if (h->last_nlhdr->nlmsg_type == NLMSG_DONE ||
	    h->last_nlhdr->nlmsg_flags & NLM_F_MULTI) {
		/* if last part in multipart message or no
		 * multipart message at all, return */
		h->last_nlhdr = NULL;
		return NULL;
	}

	remain_len = (len - ((unsigned char *)h->last_nlhdr - buf));
	nlh = NLMSG_NEXT(h->last_nlhdr, remain_len);

	h->last_nlhdr = nlh;

	return nlh;
}

int nfnl_callback_register(struct nfnl_subsys_handle *ssh,
			   u_int8_t type, struct nfnl_callback *cb)
{
	if (type >= ssh->cb_count)
		return -EINVAL;

	memcpy(&ssh->cb[type], cb, sizeof(*cb));

	return 0;
}

int nfnl_callback_unregister(struct nfnl_subsys_handle *ssh, u_int8_t type)
{
	if (type >= ssh->cb_count)
		return -EINVAL;

	ssh->cb[type].call = NULL;

	return 0;
}

int nfnl_check_attributes(const struct nfnl_handle *h,
			 const struct nlmsghdr *nlh,
			 struct nfattr *nfa[])
{
	int min_len;
	u_int8_t type = NFNL_MSG_TYPE(nlh->nlmsg_type);
	u_int8_t subsys_id = NFNL_SUBSYS_ID(nlh->nlmsg_type);
	const struct nfnl_subsys_handle *ssh;
	struct nfnl_callback *cb;

	if (subsys_id > NFNL_MAX_SUBSYS)
		return -EINVAL;

	ssh = &h->subsys[subsys_id];
 	cb = &ssh->cb[type];

#if 1
	/* checks need to be enabled as soon as this is called from
	 * somebody else than __nfnl_handle_msg */
	if (type >= ssh->cb_count)
		return -EINVAL;

	min_len = NLMSG_ALIGN(sizeof(struct nfgenmsg));
	if (nlh->nlmsg_len < min_len)
		return -EINVAL;
#endif
	memset(nfa, 0, sizeof(struct nfattr *) * cb->attr_count);

	if (nlh->nlmsg_len > min_len) {
		struct nfattr *attr = NFM_NFA(NLMSG_DATA(nlh));
		int attrlen = nlh->nlmsg_len - NLMSG_ALIGN(min_len);

		while (NFA_OK(attr, attrlen)) {
			unsigned int flavor = NFA_TYPE(attr);
			if (flavor) {
				if (flavor > cb->attr_count)
					return -EINVAL;
				nfa[flavor - 1] = attr;
			}
			attr = NFA_NEXT(attr, attrlen);
		}
	}

	return 0;
}

static int __nfnl_handle_msg(struct nfnl_handle *h, struct nlmsghdr *nlh,
			     int len)
{
	struct nfnl_subsys_handle *ssh;
	u_int8_t type = NFNL_MSG_TYPE(nlh->nlmsg_type);
	u_int8_t subsys_id = NFNL_SUBSYS_ID(nlh->nlmsg_type);
	int err = 0;

	if (subsys_id > NFNL_MAX_SUBSYS)
		return -1;

	ssh = &h->subsys[subsys_id];

	if (nlh->nlmsg_len < NLMSG_LENGTH(NLMSG_ALIGN(sizeof(struct nfgenmsg))))
		return -1;

	if (type >= ssh->cb_count)
		return -1;

	if (ssh->cb[type].attr_count) {
		struct nfattr *nfa[ssh->cb[type].attr_count];

		err = nfnl_check_attributes(h, nlh, nfa);
		if (err < 0)
			return err;
		if (ssh->cb[type].call)
			return ssh->cb[type].call(nlh, nfa, ssh->cb[type].data);
	}
	return 0;
}

int nfnl_handle_packet(struct nfnl_handle *h, char *buf, int len)
{

	while (len >= NLMSG_SPACE(0)) {
		u_int32_t rlen;
		struct nlmsghdr *nlh = (struct nlmsghdr *)buf;

		if (nlh->nlmsg_len < sizeof(struct nlmsghdr)
		    || len < nlh->nlmsg_len)
			return -1;

		rlen = NLMSG_ALIGN(nlh->nlmsg_len);
		if (rlen > len)
			rlen = len;

		if (__nfnl_handle_msg(h, nlh, rlen) < 0)
			return -1;

		len -= rlen;
	}
	return 0;
}