• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: LGPL-2.1-only */
2 /*
3  * Copyright (c) 2003-2012 Thomas Graf <tgraf@suug.ch>
4  */
5 
6 /**
7  * @ingroup core
8  * @defgroup msg Message Construction & Parsing
9  * Netlink Message Construction/Parsing Interface
10  *
11  * Related sections in the development guide:
12  * - @core_doc{_message_parsing_amp_construction,Message Parsing & Construction}
13  *
14  * @{
15  *
16  * Header
17  * ------
18  * ~~~~{.c}
19  * #include <netlink/msg.h>
20  * ~~~~
21  */
22 
23 #include <netlink-private/netlink.h>
24 #include <netlink-private/utils.h>
25 #include <netlink/netlink.h>
26 #include <netlink/utils.h>
27 #include <netlink/cache.h>
28 #include <netlink/attr.h>
29 #include <linux/socket.h>
30 
31 static size_t default_msg_size;
32 
init_msg_size(void)33 static void __init init_msg_size(void)
34 {
35 	default_msg_size = getpagesize();
36 }
37 
38 /**
39  * @name Size Calculations
40  * @{
41  */
42 
43 /**
44  * Calculates size of netlink message based on payload length.
45  * @arg payload		Length of payload
46  *
47  * @return size of netlink message without padding.
48  */
nlmsg_size(int payload)49 int nlmsg_size(int payload)
50 {
51 	return NLMSG_HDRLEN + payload;
52 }
53 
nlmsg_msg_size(int payload)54 static int nlmsg_msg_size(int payload)
55 {
56 	return nlmsg_size(payload);
57 }
58 
59 /**
60  * Calculates size of netlink message including padding based on payload length
61  * @arg payload		Length of payload
62  *
63  * This function is idential to nlmsg_size() + nlmsg_padlen().
64  *
65  * @return Size of netlink message including padding.
66  */
nlmsg_total_size(int payload)67 int nlmsg_total_size(int payload)
68 {
69 	return NLMSG_ALIGN(nlmsg_msg_size(payload));
70 }
71 
72 /**
73  * Size of padding that needs to be added at end of message
74  * @arg payload		Length of payload
75  *
76  * Calculates the number of bytes of padding which is required to be added to
77  * the end of the message to ensure that the next netlink message header begins
78  * properly aligned to NLMSG_ALIGNTO.
79  *
80  * @return Number of bytes of padding needed.
81  */
nlmsg_padlen(int payload)82 int nlmsg_padlen(int payload)
83 {
84 	return nlmsg_total_size(payload) - nlmsg_msg_size(payload);
85 }
86 
87 /** @} */
88 
89 /**
90  * @name Access to Message Payload
91  * @{
92  */
93 
94 /**
95  * Return pointer to message payload
96  * @arg nlh		Netlink message header
97  *
98  * @return Pointer to start of message payload.
99  */
nlmsg_data(const struct nlmsghdr * nlh)100 void *nlmsg_data(const struct nlmsghdr *nlh)
101 {
102 	return (unsigned char *) nlh + NLMSG_HDRLEN;
103 }
104 
nlmsg_tail(const struct nlmsghdr * nlh)105 void *nlmsg_tail(const struct nlmsghdr *nlh)
106 {
107 	return (unsigned char *) nlh + NLMSG_ALIGN(nlh->nlmsg_len);
108 }
109 
110 /**
111  * Return length of message payload
112  * @arg nlh		Netlink message header
113  *
114  * @return Length of message payload in bytes.
115  */
nlmsg_datalen(const struct nlmsghdr * nlh)116 int nlmsg_datalen(const struct nlmsghdr *nlh)
117 {
118 	return nlh->nlmsg_len - NLMSG_HDRLEN;
119 }
120 
nlmsg_len(const struct nlmsghdr * nlh)121 static int nlmsg_len(const struct nlmsghdr *nlh)
122 {
123 	return nlmsg_datalen(nlh);
124 }
125 
126 /** @} */
127 
128 /**
129  * @name Attribute Access
130  * @{
131  */
132 
133 /**
134  * head of attributes data
135  * @arg nlh		netlink message header
136  * @arg hdrlen		length of family specific header
137  */
nlmsg_attrdata(const struct nlmsghdr * nlh,int hdrlen)138 struct nlattr *nlmsg_attrdata(const struct nlmsghdr *nlh, int hdrlen)
139 {
140 	unsigned char *data = nlmsg_data(nlh);
141 	return (struct nlattr *) (data + NLMSG_ALIGN(hdrlen));
142 }
143 
144 /**
145  * length of attributes data
146  * @arg nlh		netlink message header
147  * @arg hdrlen		length of family specific header
148  */
nlmsg_attrlen(const struct nlmsghdr * nlh,int hdrlen)149 int nlmsg_attrlen(const struct nlmsghdr *nlh, int hdrlen)
150 {
151 	return max_t(int, nlmsg_len(nlh) - NLMSG_ALIGN(hdrlen), 0);
152 }
153 
154 /** @} */
155 
156 /**
157  * @name Message Parsing
158  * @{
159  */
160 
nlmsg_valid_hdr(const struct nlmsghdr * nlh,int hdrlen)161 int nlmsg_valid_hdr(const struct nlmsghdr *nlh, int hdrlen)
162 {
163 	if (nlh->nlmsg_len < nlmsg_msg_size(hdrlen))
164 		return 0;
165 
166 	return 1;
167 }
168 
169 /**
170  * check if the netlink message fits into the remaining bytes
171  * @arg nlh		netlink message header
172  * @arg remaining	number of bytes remaining in message stream
173  */
nlmsg_ok(const struct nlmsghdr * nlh,int remaining)174 int nlmsg_ok(const struct nlmsghdr *nlh, int remaining)
175 {
176 	return (remaining >= (int)sizeof(struct nlmsghdr) &&
177 		nlh->nlmsg_len >= sizeof(struct nlmsghdr) &&
178 		nlh->nlmsg_len <= remaining);
179 }
180 
181 /**
182  * next netlink message in message stream
183  * @arg nlh		netlink message header
184  * @arg remaining	number of bytes remaining in message stream
185  *
186  * @returns the next netlink message in the message stream and
187  * decrements remaining by the size of the current message.
188  */
nlmsg_next(struct nlmsghdr * nlh,int * remaining)189 struct nlmsghdr *nlmsg_next(struct nlmsghdr *nlh, int *remaining)
190 {
191 	int totlen = NLMSG_ALIGN(nlh->nlmsg_len);
192 
193 	*remaining -= totlen;
194 
195 	return (struct nlmsghdr *) ((unsigned char *) nlh + totlen);
196 }
197 
198 /**
199  * parse attributes of a netlink message
200  * @arg nlh		netlink message header
201  * @arg hdrlen		length of family specific header
202  * @arg tb		destination array with maxtype+1 elements
203  * @arg maxtype		maximum attribute type to be expected
204  * @arg policy		validation policy
205  *
206  * See nla_parse()
207  */
nlmsg_parse(struct nlmsghdr * nlh,int hdrlen,struct nlattr * tb[],int maxtype,const struct nla_policy * policy)208 int nlmsg_parse(struct nlmsghdr *nlh, int hdrlen, struct nlattr *tb[],
209 		int maxtype, const struct nla_policy *policy)
210 {
211 	if (!nlmsg_valid_hdr(nlh, hdrlen))
212 		return -NLE_MSG_TOOSHORT;
213 
214 	return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen),
215 			 nlmsg_attrlen(nlh, hdrlen), policy);
216 }
217 
218 /**
219  * nlmsg_find_attr - find a specific attribute in a netlink message
220  * @arg nlh		netlink message header
221  * @arg hdrlen		length of familiy specific header
222  * @arg attrtype	type of attribute to look for
223  *
224  * Returns the first attribute which matches the specified type.
225  */
nlmsg_find_attr(struct nlmsghdr * nlh,int hdrlen,int attrtype)226 struct nlattr *nlmsg_find_attr(struct nlmsghdr *nlh, int hdrlen, int attrtype)
227 {
228 	return nla_find(nlmsg_attrdata(nlh, hdrlen),
229 			nlmsg_attrlen(nlh, hdrlen), attrtype);
230 }
231 
232 /**
233  * nlmsg_validate - validate a netlink message including attributes
234  * @arg nlh		netlinket message header
235  * @arg hdrlen		length of familiy specific header
236  * @arg maxtype		maximum attribute type to be expected
237  * @arg policy		validation policy
238  */
nlmsg_validate(struct nlmsghdr * nlh,int hdrlen,int maxtype,const struct nla_policy * policy)239 int nlmsg_validate(struct nlmsghdr *nlh, int hdrlen, int maxtype,
240 		   const struct nla_policy *policy)
241 {
242 	if (!nlmsg_valid_hdr(nlh, hdrlen))
243 		return -NLE_MSG_TOOSHORT;
244 
245 	return nla_validate(nlmsg_attrdata(nlh, hdrlen),
246 			    nlmsg_attrlen(nlh, hdrlen), maxtype, policy);
247 }
248 
249 /** @} */
250 
251 /**
252  * @name Message Building/Access
253  * @{
254  */
255 
__nlmsg_alloc(size_t len)256 static struct nl_msg *__nlmsg_alloc(size_t len)
257 {
258 	struct nl_msg *nm;
259 
260 	if (len < sizeof(struct nlmsghdr))
261 		len = sizeof(struct nlmsghdr);
262 
263 	nm = calloc(1, sizeof(*nm));
264 	if (!nm)
265 		goto errout;
266 
267 	nm->nm_refcnt = 1;
268 
269 	nm->nm_nlh = calloc(1, len);
270 	if (!nm->nm_nlh)
271 		goto errout;
272 
273 	nm->nm_protocol = -1;
274 	nm->nm_size = len;
275 	nm->nm_nlh->nlmsg_len = nlmsg_total_size(0);
276 
277 	NL_DBG(2, "msg %p: Allocated new message, maxlen=%zu\n", nm, len);
278 
279 	return nm;
280 errout:
281 	free(nm);
282 	return NULL;
283 }
284 
285 /**
286  * Allocate a new netlink message with the default maximum payload size.
287  *
288  * Allocates a new netlink message without any further payload. The
289  * maximum payload size defaults to PAGESIZE or as otherwise specified
290  * with nlmsg_set_default_size().
291  *
292  * @return Newly allocated netlink message or NULL.
293  */
nlmsg_alloc(void)294 struct nl_msg *nlmsg_alloc(void)
295 {
296 	return __nlmsg_alloc(default_msg_size);
297 }
298 
299 /**
300  * Allocate a new netlink message with maximum payload size specified.
301  */
nlmsg_alloc_size(size_t max)302 struct nl_msg *nlmsg_alloc_size(size_t max)
303 {
304 	return __nlmsg_alloc(max);
305 }
306 
307 /**
308  * Allocate a new netlink message and inherit netlink message header
309  * @arg hdr		Netlink message header template
310  *
311  * Allocates a new netlink message and inherits the original message
312  * header. If \a hdr is not NULL it will be used as a template for
313  * the netlink message header, otherwise the header is left blank.
314  *
315  * @return Newly allocated netlink message or NULL
316  */
nlmsg_inherit(struct nlmsghdr * hdr)317 struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr)
318 {
319 	struct nl_msg *nm;
320 
321 	nm = nlmsg_alloc();
322 	if (nm && hdr) {
323 		struct nlmsghdr *new = nm->nm_nlh;
324 
325 		new->nlmsg_type = hdr->nlmsg_type;
326 		new->nlmsg_flags = hdr->nlmsg_flags;
327 		new->nlmsg_seq = hdr->nlmsg_seq;
328 		new->nlmsg_pid = hdr->nlmsg_pid;
329 	}
330 
331 	return nm;
332 }
333 
334 /**
335  * Allocate a new netlink message
336  * @arg nlmsgtype	Netlink message type
337  * @arg flags		Message flags.
338  *
339  * @return Newly allocated netlink message or NULL.
340  */
nlmsg_alloc_simple(int nlmsgtype,int flags)341 struct nl_msg *nlmsg_alloc_simple(int nlmsgtype, int flags)
342 {
343 	struct nl_msg *msg;
344 	struct nlmsghdr nlh = {
345 		.nlmsg_type = nlmsgtype,
346 		.nlmsg_flags = flags,
347 		.nlmsg_seq = NL_AUTO_SEQ,
348 		.nlmsg_pid = NL_AUTO_PID,
349 	};
350 
351 	msg = nlmsg_inherit(&nlh);
352 	if (msg)
353 		NL_DBG(2, "msg %p: Allocated new simple message\n", msg);
354 
355 	return msg;
356 }
357 
358 /**
359  * Set the default maximum message payload size for allocated messages
360  * @arg max		Size of payload in bytes.
361  */
nlmsg_set_default_size(size_t max)362 void nlmsg_set_default_size(size_t max)
363 {
364 	if (max < nlmsg_total_size(0))
365 		max = nlmsg_total_size(0);
366 
367 	default_msg_size = max;
368 }
369 
370 /**
371  * Convert a netlink message received from a netlink socket to a nl_msg
372  * @arg hdr		Netlink message received from netlink socket.
373  *
374  * Allocates a new netlink message and copies all of the data pointed to
375  * by \a hdr into the new message object.
376  *
377  * @return Newly allocated netlink message or NULL.
378  */
nlmsg_convert(struct nlmsghdr * hdr)379 struct nl_msg *nlmsg_convert(struct nlmsghdr *hdr)
380 {
381 	struct nl_msg *nm;
382 
383 	nm = __nlmsg_alloc(NLMSG_ALIGN(hdr->nlmsg_len));
384 	if (!nm)
385 		return NULL;
386 
387 	memcpy(nm->nm_nlh, hdr, hdr->nlmsg_len);
388 
389 	return nm;
390 }
391 
392 /**
393  * Reserve room for additional data in a netlink message
394  * @arg n		netlink message
395  * @arg len		length of additional data to reserve room for
396  * @arg pad		number of bytes to align data to
397  *
398  * Reserves room for additional data at the tail of the an
399  * existing netlink message. Eventual padding required will
400  * be zeroed out.
401  *
402  * @return Pointer to start of additional data tailroom or NULL.
403  */
nlmsg_reserve(struct nl_msg * n,size_t len,int pad)404 void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
405 {
406 	char *buf = (char *) n->nm_nlh;
407 	size_t nlmsg_len = n->nm_nlh->nlmsg_len;
408 	size_t tlen;
409 
410 	if (len > n->nm_size)
411 		return NULL;
412 
413 	tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
414 
415 	if ((tlen + nlmsg_len) > n->nm_size)
416 		return NULL;
417 
418 	buf += nlmsg_len;
419 	n->nm_nlh->nlmsg_len += tlen;
420 
421 	if (tlen > len)
422 		memset(buf + len, 0, tlen - len);
423 
424 	NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
425 		  n, tlen, len, pad, n->nm_nlh->nlmsg_len);
426 
427 	return buf;
428 }
429 
430 /**
431  * Append data to tail of a netlink message
432  * @arg n		netlink message
433  * @arg data		data to add
434  * @arg len		length of data
435  * @arg pad		Number of bytes to align data to.
436  *
437  * Extends the netlink message as needed and appends the data of given
438  * length to the message.
439  *
440  * @return 0 on success or a negative error code
441  */
nlmsg_append(struct nl_msg * n,void * data,size_t len,int pad)442 int nlmsg_append(struct nl_msg *n, void *data, size_t len, int pad)
443 {
444 	void *tmp;
445 
446 	tmp = nlmsg_reserve(n, len, pad);
447 	if (tmp == NULL)
448 		return -NLE_NOMEM;
449 
450 	memcpy(tmp, data, len);
451 	NL_DBG(2, "msg %p: Appended %zu bytes with padding %d\n", n, len, pad);
452 
453 	return 0;
454 }
455 
456 /**
457  * Expand maximum payload size of a netlink message
458  * @arg n		Netlink message.
459  * @arg newlen		New maximum payload size.
460  *
461  * Reallocates the payload section of a netlink message and increases
462  * the maximum payload size of the message.
463  *
464  * @note Any pointers pointing to old payload block will be stale and
465  *       need to be refetched. Therfore, do not expand while constructing
466  *       nested attributes or while reserved data blocks are held.
467  *
468  * @return 0 on success or a negative error code.
469  */
nlmsg_expand(struct nl_msg * n,size_t newlen)470 int nlmsg_expand(struct nl_msg *n, size_t newlen)
471 {
472 	void *tmp;
473 
474 	if (newlen <= n->nm_size)
475 		return -NLE_INVAL;
476 
477 	tmp = realloc(n->nm_nlh, newlen);
478 	if (tmp == NULL)
479 		return -NLE_NOMEM;
480 
481 	n->nm_nlh = tmp;
482 	n->nm_size = newlen;
483 
484 	return 0;
485 }
486 
487 /**
488  * Add a netlink message header to a netlink message
489  * @arg n		netlink message
490  * @arg pid		netlink process id or NL_AUTO_PID
491  * @arg seq		sequence number of message or NL_AUTO_SEQ
492  * @arg type		message type
493  * @arg payload		length of message payload
494  * @arg flags		message flags
495  *
496  * Adds or overwrites the netlink message header in an existing message
497  * object. If \a payload is greater-than zero additional room will be
498  * reserved, f.e. for family specific headers. It can be accesed via
499  * nlmsg_data().
500  *
501  * @return A pointer to the netlink message header or NULL.
502  */
nlmsg_put(struct nl_msg * n,uint32_t pid,uint32_t seq,int type,int payload,int flags)503 struct nlmsghdr *nlmsg_put(struct nl_msg *n, uint32_t pid, uint32_t seq,
504 			   int type, int payload, int flags)
505 {
506 	struct nlmsghdr *nlh;
507 
508 	if (n->nm_nlh->nlmsg_len < NLMSG_HDRLEN)
509 		BUG();
510 
511 	nlh = (struct nlmsghdr *) n->nm_nlh;
512 	nlh->nlmsg_type = type;
513 	nlh->nlmsg_flags = flags;
514 	nlh->nlmsg_pid = pid;
515 	nlh->nlmsg_seq = seq;
516 
517 	NL_DBG(2, "msg %p: Added netlink header type=%d, flags=%d, pid=%d, "
518 		  "seq=%d\n", n, type, flags, pid, seq);
519 
520 	if (payload > 0 &&
521 	    nlmsg_reserve(n, payload, NLMSG_ALIGNTO) == NULL)
522 		return NULL;
523 
524 	return nlh;
525 }
526 
527 /**
528  * Return actual netlink message
529  * @arg n		netlink message
530  *
531  * Returns the actual netlink message casted to the type of the netlink
532  * message header.
533  *
534  * @return A pointer to the netlink message.
535  */
nlmsg_hdr(struct nl_msg * n)536 struct nlmsghdr *nlmsg_hdr(struct nl_msg *n)
537 {
538 	return n->nm_nlh;
539 }
540 
541 /**
542  * Acquire a reference on a netlink message
543  * @arg msg		message to acquire reference from
544  */
nlmsg_get(struct nl_msg * msg)545 void nlmsg_get(struct nl_msg *msg)
546 {
547 	msg->nm_refcnt++;
548 	NL_DBG(4, "New reference to message %p, total %d\n",
549 	       msg, msg->nm_refcnt);
550 }
551 
552 /**
553  * Release a reference from an netlink message
554  * @arg msg		message to release reference from
555  *
556  * Frees memory after the last reference has been released.
557  */
nlmsg_free(struct nl_msg * msg)558 void nlmsg_free(struct nl_msg *msg)
559 {
560 	if (!msg)
561 		return;
562 
563 	msg->nm_refcnt--;
564 	NL_DBG(4, "Returned message reference %p, %d remaining\n",
565 	       msg, msg->nm_refcnt);
566 
567 	if (msg->nm_refcnt < 0)
568 		BUG();
569 
570 	if (msg->nm_refcnt <= 0) {
571 		free(msg->nm_nlh);
572 		NL_DBG(2, "msg %p: Freed\n", msg);
573 		free(msg);
574 	}
575 }
576 
577 /** @} */
578 
579 /**
580  * @name Attributes
581  * @{
582  */
583 
nlmsg_set_proto(struct nl_msg * msg,int protocol)584 void nlmsg_set_proto(struct nl_msg *msg, int protocol)
585 {
586 	msg->nm_protocol = protocol;
587 }
588 
nlmsg_get_proto(struct nl_msg * msg)589 int nlmsg_get_proto(struct nl_msg *msg)
590 {
591 	return msg->nm_protocol;
592 }
593 
nlmsg_get_max_size(struct nl_msg * msg)594 size_t nlmsg_get_max_size(struct nl_msg *msg)
595 {
596 	return msg->nm_size;
597 }
598 
nlmsg_set_src(struct nl_msg * msg,struct sockaddr_nl * addr)599 void nlmsg_set_src(struct nl_msg *msg, struct sockaddr_nl *addr)
600 {
601 	memcpy(&msg->nm_src, addr, sizeof(*addr));
602 }
603 
nlmsg_get_src(struct nl_msg * msg)604 struct sockaddr_nl *nlmsg_get_src(struct nl_msg *msg)
605 {
606 	return &msg->nm_src;
607 }
608 
nlmsg_set_dst(struct nl_msg * msg,struct sockaddr_nl * addr)609 void nlmsg_set_dst(struct nl_msg *msg, struct sockaddr_nl *addr)
610 {
611 	memcpy(&msg->nm_dst, addr, sizeof(*addr));
612 }
613 
nlmsg_get_dst(struct nl_msg * msg)614 struct sockaddr_nl *nlmsg_get_dst(struct nl_msg *msg)
615 {
616 	return &msg->nm_dst;
617 }
618 
nlmsg_set_creds(struct nl_msg * msg,struct ucred * creds)619 void nlmsg_set_creds(struct nl_msg *msg, struct ucred *creds)
620 {
621 	memcpy(&msg->nm_creds, creds, sizeof(*creds));
622 	msg->nm_flags |= NL_MSG_CRED_PRESENT;
623 }
624 
nlmsg_get_creds(struct nl_msg * msg)625 struct ucred *nlmsg_get_creds(struct nl_msg *msg)
626 {
627 	if (msg->nm_flags & NL_MSG_CRED_PRESENT)
628 		return &msg->nm_creds;
629 	return NULL;
630 }
631 
632 /** @} */
633 
634 /**
635  * @name Netlink Message Type Translations
636  * @{
637  */
638 
639 static const struct trans_tbl nl_msgtypes[] = {
640 	__ADD(NLMSG_NOOP,NOOP),
641 	__ADD(NLMSG_ERROR,ERROR),
642 	__ADD(NLMSG_DONE,DONE),
643 	__ADD(NLMSG_OVERRUN,OVERRUN),
644 };
645 
nl_nlmsgtype2str(int type,char * buf,size_t size)646 char *nl_nlmsgtype2str(int type, char *buf, size_t size)
647 {
648 	return __type2str(type, buf, size, nl_msgtypes,
649 			  ARRAY_SIZE(nl_msgtypes));
650 }
651 
nl_str2nlmsgtype(const char * name)652 int nl_str2nlmsgtype(const char *name)
653 {
654 	return __str2type(name, nl_msgtypes, ARRAY_SIZE(nl_msgtypes));
655 }
656 
657 /** @} */
658 
659 /**
660  * @name Netlink Message Flags Translations
661  * @{
662  */
663 
nl_nlmsg_flags2str(int flags,char * buf,size_t len)664 char *nl_nlmsg_flags2str(int flags, char *buf, size_t len)
665 {
666 	memset(buf, 0, len);
667 
668 #define PRINT_FLAG(f) \
669 	if (flags & NLM_F_##f) { \
670 		flags &= ~NLM_F_##f; \
671 		strncat(buf, #f, len - strlen(buf) - 1); \
672 		if (flags) \
673 			strncat(buf, ",", len - strlen(buf) - 1); \
674 	}
675 
676 	PRINT_FLAG(REQUEST);
677 	PRINT_FLAG(MULTI);
678 	PRINT_FLAG(ACK);
679 	PRINT_FLAG(ECHO);
680 	PRINT_FLAG(ROOT);
681 	PRINT_FLAG(MATCH);
682 	PRINT_FLAG(ATOMIC);
683 	PRINT_FLAG(REPLACE);
684 	PRINT_FLAG(EXCL);
685 	PRINT_FLAG(CREATE);
686 	PRINT_FLAG(APPEND);
687 
688 	if (flags) {
689 		char s[32];
690 		snprintf(s, sizeof(s), "0x%x", flags);
691 		strncat(buf, s, len - strlen(buf) - 1);
692 	}
693 #undef PRINT_FLAG
694 
695 	return buf;
696 }
697 
698 /** @} */
699 
700 /**
701  * @name Direct Parsing
702  * @{
703  */
704 
705 /** @cond SKIP */
706 struct dp_xdata {
707 	void (*cb)(struct nl_object *, void *);
708 	void *arg;
709 };
710 /** @endcond */
711 
parse_cb(struct nl_object * obj,struct nl_parser_param * p)712 static int parse_cb(struct nl_object *obj, struct nl_parser_param *p)
713 {
714 	struct dp_xdata *x = p->pp_arg;
715 
716 	x->cb(obj, x->arg);
717 	return 0;
718 }
719 
nl_msg_parse(struct nl_msg * msg,void (* cb)(struct nl_object *,void *),void * arg)720 int nl_msg_parse(struct nl_msg *msg, void (*cb)(struct nl_object *, void *),
721 		 void *arg)
722 {
723 	struct nl_cache_ops *ops;
724 	struct nl_parser_param p = {
725 		.pp_cb = parse_cb
726 	};
727 	struct dp_xdata x = {
728 		.cb = cb,
729 		.arg = arg,
730 	};
731 	int err;
732 
733 	ops = nl_cache_ops_associate_safe(nlmsg_get_proto(msg),
734 					  nlmsg_hdr(msg)->nlmsg_type);
735 	if (ops == NULL)
736 		return -NLE_MSGTYPE_NOSUPPORT;
737 	p.pp_arg = &x;
738 
739 	err = nl_cache_parse(ops, NULL, nlmsg_hdr(msg), &p);
740 	nl_cache_ops_put(ops);
741 
742 	return err;
743 }
744 
745 /** @} */
746 
747 /**
748  * @name Dumping
749  * @{
750  */
751 
prefix_line(FILE * ofd,int prefix)752 static void prefix_line(FILE *ofd, int prefix)
753 {
754 	int i;
755 
756 	for (i = 0; i < prefix; i++)
757 		fprintf(ofd, "  ");
758 }
759 
dump_hex(FILE * ofd,char * start,int len,int prefix)760 static inline void dump_hex(FILE *ofd, char *start, int len, int prefix)
761 {
762 	int i, a, c, limit;
763 	char ascii[21] = {0};
764 
765 	limit = 16 - (prefix * 2);
766 	prefix_line(ofd, prefix);
767 	fprintf(ofd, "    ");
768 
769 	for (i = 0, a = 0, c = 0; i < len; i++) {
770 		int v = *(uint8_t *) (start + i);
771 
772 		fprintf(ofd, "%02x ", v);
773 		ascii[a++] = isprint(v) ? v : '.';
774 
775 		if (++c >= limit) {
776 			fprintf(ofd, "%s\n", ascii);
777 			if (i < (len - 1)) {
778 				prefix_line(ofd, prefix);
779 				fprintf(ofd, "    ");
780 			}
781 			a = c = 0;
782 			memset(ascii, 0, sizeof(ascii));
783 		}
784 	}
785 
786 	if (c != 0) {
787 		for (i = 0; i < (limit - c); i++)
788 			fprintf(ofd, "   ");
789 		fprintf(ofd, "%s\n", ascii);
790 	}
791 }
792 
print_hdr(FILE * ofd,struct nl_msg * msg)793 static void print_hdr(FILE *ofd, struct nl_msg *msg)
794 {
795 	struct nlmsghdr *nlh = nlmsg_hdr(msg);
796 	struct nl_cache_ops *ops;
797 	struct nl_msgtype *mt;
798 	char buf[128];
799 
800 	fprintf(ofd, "    .nlmsg_len = %d\n", nlh->nlmsg_len);
801 
802 	ops = nl_cache_ops_associate_safe(nlmsg_get_proto(msg), nlh->nlmsg_type);
803 	if (ops) {
804 		mt = nl_msgtype_lookup(ops, nlh->nlmsg_type);
805 		if (!mt)
806 			BUG();
807 
808 		snprintf(buf, sizeof(buf), "%s::%s", ops->co_name, mt->mt_name);
809 		nl_cache_ops_put(ops);
810 	} else
811 		nl_nlmsgtype2str(nlh->nlmsg_type, buf, sizeof(buf));
812 
813 	fprintf(ofd, "    .type = %d <%s>\n", nlh->nlmsg_type, buf);
814 	fprintf(ofd, "    .flags = %d <%s>\n", nlh->nlmsg_flags,
815 		nl_nlmsg_flags2str(nlh->nlmsg_flags, buf, sizeof(buf)));
816 	fprintf(ofd, "    .seq = %d\n", nlh->nlmsg_seq);
817 	fprintf(ofd, "    .port = %d\n", nlh->nlmsg_pid);
818 
819 }
820 
print_genl_hdr(FILE * ofd,void * start)821 static void print_genl_hdr(FILE *ofd, void *start)
822 {
823 	struct genlmsghdr *ghdr = start;
824 
825 	fprintf(ofd, "  [GENERIC NETLINK HEADER] %zu octets\n", GENL_HDRLEN);
826 	fprintf(ofd, "    .cmd = %u\n", ghdr->cmd);
827 	fprintf(ofd, "    .version = %u\n", ghdr->version);
828 	fprintf(ofd, "    .unused = %#x\n", ghdr->reserved);
829 }
830 
print_genl_msg(struct nl_msg * msg,FILE * ofd,struct nlmsghdr * hdr,struct nl_cache_ops * ops,int * payloadlen)831 static void *print_genl_msg(struct nl_msg *msg, FILE *ofd, struct nlmsghdr *hdr,
832 			    struct nl_cache_ops *ops, int *payloadlen)
833 {
834 	char *data = nlmsg_data(hdr);
835 
836 	if (*payloadlen < GENL_HDRLEN)
837 		return data;
838 
839 	print_genl_hdr(ofd, data);
840 
841 	*payloadlen -= GENL_HDRLEN;
842 	data += GENL_HDRLEN;
843 
844 	if (ops) {
845 		int hdrsize = ops->co_hdrsize - GENL_HDRLEN;
846 
847 		if (hdrsize > 0) {
848 			if (*payloadlen < hdrsize)
849 				return data;
850 
851 			fprintf(ofd, "  [HEADER] %d octets\n", hdrsize);
852 			dump_hex(ofd, data, hdrsize, 0);
853 
854 			*payloadlen -= hdrsize;
855 			data += hdrsize;
856 		}
857 	}
858 
859 	return data;
860 }
861 
dump_attr(FILE * ofd,struct nlattr * attr,int prefix)862 static void dump_attr(FILE *ofd, struct nlattr *attr, int prefix)
863 {
864 	int len = nla_len(attr);
865 
866 	dump_hex(ofd, nla_data(attr), len, prefix);
867 }
868 
dump_attrs(FILE * ofd,struct nlattr * attrs,int attrlen,int prefix)869 static void dump_attrs(FILE *ofd, struct nlattr *attrs, int attrlen,
870 		       int prefix)
871 {
872 	int rem;
873 	struct nlattr *nla;
874 
875 	nla_for_each_attr(nla, attrs, attrlen, rem) {
876 		int padlen, alen = nla_len(nla);
877 
878 		prefix_line(ofd, prefix);
879 
880 		if (nla->nla_type == 0)
881 			fprintf(ofd, "  [ATTR PADDING] %d octets\n", alen);
882 		else
883 			fprintf(ofd, "  [ATTR %02d%s] %d octets\n", nla_type(nla),
884 				nla_is_nested(nla) ? " NESTED" : "",
885 				alen);
886 
887 		if (nla_is_nested(nla))
888 			dump_attrs(ofd, nla_data(nla), alen, prefix+1);
889 		else
890 			dump_attr(ofd, nla, prefix);
891 
892 		padlen = nla_padlen(alen);
893 		if (padlen > 0) {
894 			prefix_line(ofd, prefix);
895 			fprintf(ofd, "  [PADDING] %d octets\n",
896 				padlen);
897 			dump_hex(ofd, (char *) nla_data(nla) + alen,
898 				 padlen, prefix);
899 		}
900 	}
901 
902 	if (rem) {
903 		prefix_line(ofd, prefix);
904 		fprintf(ofd, "  [LEFTOVER] %d octets\n", rem);
905 	}
906 }
907 
dump_error_msg(struct nl_msg * msg,FILE * ofd)908 static void dump_error_msg(struct nl_msg *msg, FILE *ofd)
909 {
910 	struct nlmsghdr *hdr = nlmsg_hdr(msg);
911 	struct nlmsgerr *err = nlmsg_data(hdr);
912 
913 	fprintf(ofd, "  [ERRORMSG] %zu octets\n", sizeof(*err));
914 
915 	if (nlmsg_len(hdr) >= sizeof(*err)) {
916 		struct nl_msg *errmsg;
917 
918 		fprintf(ofd, "    .error = %d \"%s\"\n", err->error,
919 			nl_strerror_l(-err->error));
920 		fprintf(ofd, "  [ORIGINAL MESSAGE] %zu octets\n", sizeof(*hdr));
921 
922 		errmsg = nlmsg_inherit(&err->msg);
923 		print_hdr(ofd, errmsg);
924 		nlmsg_free(errmsg);
925 	}
926 }
927 
print_msg(struct nl_msg * msg,FILE * ofd,struct nlmsghdr * hdr)928 static void print_msg(struct nl_msg *msg, FILE *ofd, struct nlmsghdr *hdr)
929 {
930 	struct nl_cache_ops *ops;
931 	int payloadlen = nlmsg_len(hdr);
932 	int attrlen = 0;
933 	void *data;
934 
935 	data = nlmsg_data(hdr);
936 	ops = nl_cache_ops_associate_safe(nlmsg_get_proto(msg),
937 					  hdr->nlmsg_type);
938 	if (ops) {
939 		attrlen = nlmsg_attrlen(hdr, ops->co_hdrsize);
940 		payloadlen -= attrlen;
941 	}
942 
943 	if (msg->nm_protocol == NETLINK_GENERIC)
944 		data = print_genl_msg(msg, ofd, hdr, ops, &payloadlen);
945 
946 	if (payloadlen) {
947 		fprintf(ofd, "  [PAYLOAD] %d octets\n", payloadlen);
948 		dump_hex(ofd, data, payloadlen, 0);
949 	}
950 
951 	if (attrlen) {
952 		struct nlattr *attrs;
953 		int attrlen;
954 
955 		attrs = nlmsg_attrdata(hdr, ops->co_hdrsize);
956 		attrlen = nlmsg_attrlen(hdr, ops->co_hdrsize);
957 		dump_attrs(ofd, attrs, attrlen, 0);
958 	}
959 
960 	if (ops)
961 		nl_cache_ops_put(ops);
962 }
963 
964 /**
965  * Dump message in human readable format to file descriptor
966  * @arg msg		Message to print
967  * @arg ofd		File descriptor.
968  */
nl_msg_dump(struct nl_msg * msg,FILE * ofd)969 void nl_msg_dump(struct nl_msg *msg, FILE *ofd)
970 {
971 	struct nlmsghdr *hdr = nlmsg_hdr(msg);
972 
973 	fprintf(ofd,
974 	"--------------------------   BEGIN NETLINK MESSAGE ---------------------------\n");
975 
976 	fprintf(ofd, "  [NETLINK HEADER] %zu octets\n", sizeof(struct nlmsghdr));
977 	print_hdr(ofd, msg);
978 
979 	if (hdr->nlmsg_type == NLMSG_ERROR)
980 		dump_error_msg(msg, ofd);
981 	else if (nlmsg_len(hdr) > 0)
982 		print_msg(msg, ofd, hdr);
983 
984 	fprintf(ofd,
985 	"---------------------------  END NETLINK MESSAGE   ---------------------------\n");
986 }
987 
988 /** @} */
989 
990 /** @} */
991