2 * lib/msg.c Netlink Messages Interface
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation version 2.1
9 * Copyright (c) 2003-2012 Thomas Graf <tgraf@suug.ch>
14 * @defgroup msg Message Construction & Parsing
15 * Netlink Message Construction/Parsing Interface
17 * Related sections in the development guide:
18 * - @core_doc{_message_parsing_amp_construction,Message Parsing & Construction}
25 * #include <netlink/msg.h>
29 #include <netlink-private/netlink.h>
30 #include <netlink/netlink.h>
31 #include <netlink/utils.h>
32 #include <netlink/cache.h>
33 #include <netlink/attr.h>
34 #include <linux/socket.h>
36 static size_t default_msg_size;
38 static void __init init_msg_size(void)
40 default_msg_size = getpagesize();
44 * @name Size Calculations
49 * Calculates size of netlink message based on payload length.
50 * @arg payload Length of payload
52 * @return size of netlink message without padding.
54 int nlmsg_size(int payload)
56 return NLMSG_HDRLEN + payload;
59 static int nlmsg_msg_size(int payload)
61 return nlmsg_size(payload);
65 * Calculates size of netlink message including padding based on payload length
66 * @arg payload Length of payload
68 * This function is idential to nlmsg_size() + nlmsg_padlen().
70 * @return Size of netlink message including padding.
72 int nlmsg_total_size(int payload)
74 return NLMSG_ALIGN(nlmsg_msg_size(payload));
78 * Size of padding that needs to be added at end of message
79 * @arg payload Length of payload
81 * Calculates the number of bytes of padding which is required to be added to
82 * the end of the message to ensure that the next netlink message header begins
83 * properly aligned to NLMSG_ALIGNTO.
85 * @return Number of bytes of padding needed.
87 int nlmsg_padlen(int payload)
89 return nlmsg_total_size(payload) - nlmsg_msg_size(payload);
95 * @name Access to Message Payload
100 * Return pointer to message payload
101 * @arg nlh Netlink message header
103 * @return Pointer to start of message payload.
105 void *nlmsg_data(const struct nlmsghdr *nlh)
107 return (unsigned char *) nlh + NLMSG_HDRLEN;
110 void *nlmsg_tail(const struct nlmsghdr *nlh)
112 return (unsigned char *) nlh + NLMSG_ALIGN(nlh->nlmsg_len);
116 * Return length of message payload
117 * @arg nlh Netlink message header
119 * @return Length of message payload in bytes.
121 int nlmsg_datalen(const struct nlmsghdr *nlh)
123 return nlh->nlmsg_len - NLMSG_HDRLEN;
126 static int nlmsg_len(const struct nlmsghdr *nlh)
128 return nlmsg_datalen(nlh);
134 * @name Attribute Access
139 * head of attributes data
140 * @arg nlh netlink message header
141 * @arg hdrlen length of family specific header
143 struct nlattr *nlmsg_attrdata(const struct nlmsghdr *nlh, int hdrlen)
145 unsigned char *data = nlmsg_data(nlh);
146 return (struct nlattr *) (data + NLMSG_ALIGN(hdrlen));
150 * length of attributes data
151 * @arg nlh netlink message header
152 * @arg hdrlen length of family specific header
154 int nlmsg_attrlen(const struct nlmsghdr *nlh, int hdrlen)
156 return nlmsg_len(nlh) - NLMSG_ALIGN(hdrlen);
162 * @name Message Parsing
166 int nlmsg_valid_hdr(const struct nlmsghdr *nlh, int hdrlen)
168 if (nlh->nlmsg_len < nlmsg_msg_size(hdrlen))
175 * check if the netlink message fits into the remaining bytes
176 * @arg nlh netlink message header
177 * @arg remaining number of bytes remaining in message stream
179 int nlmsg_ok(const struct nlmsghdr *nlh, int remaining)
181 return (remaining >= (int)sizeof(struct nlmsghdr) &&
182 nlh->nlmsg_len >= sizeof(struct nlmsghdr) &&
183 nlh->nlmsg_len <= remaining);
187 * next netlink message in message stream
188 * @arg nlh netlink message header
189 * @arg remaining number of bytes remaining in message stream
191 * @returns the next netlink message in the message stream and
192 * decrements remaining by the size of the current message.
194 struct nlmsghdr *nlmsg_next(struct nlmsghdr *nlh, int *remaining)
196 int totlen = NLMSG_ALIGN(nlh->nlmsg_len);
198 *remaining -= totlen;
200 return (struct nlmsghdr *) ((unsigned char *) nlh + totlen);
204 * parse attributes of a netlink message
205 * @arg nlh netlink message header
206 * @arg hdrlen length of family specific header
207 * @arg tb destination array with maxtype+1 elements
208 * @arg maxtype maximum attribute type to be expected
209 * @arg policy validation policy
213 int nlmsg_parse(struct nlmsghdr *nlh, int hdrlen, struct nlattr *tb[],
214 int maxtype, struct nla_policy *policy)
216 if (!nlmsg_valid_hdr(nlh, hdrlen))
217 return -NLE_MSG_TOOSHORT;
219 return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen),
220 nlmsg_attrlen(nlh, hdrlen), policy);
224 * nlmsg_find_attr - find a specific attribute in a netlink message
225 * @arg nlh netlink message header
226 * @arg hdrlen length of familiy specific header
227 * @arg attrtype type of attribute to look for
229 * Returns the first attribute which matches the specified type.
231 struct nlattr *nlmsg_find_attr(struct nlmsghdr *nlh, int hdrlen, int attrtype)
233 return nla_find(nlmsg_attrdata(nlh, hdrlen),
234 nlmsg_attrlen(nlh, hdrlen), attrtype);
238 * nlmsg_validate - validate a netlink message including attributes
239 * @arg nlh netlinket message header
240 * @arg hdrlen length of familiy specific header
241 * @arg maxtype maximum attribute type to be expected
242 * @arg policy validation policy
244 int nlmsg_validate(struct nlmsghdr *nlh, int hdrlen, int maxtype,
245 struct nla_policy *policy)
247 if (!nlmsg_valid_hdr(nlh, hdrlen))
248 return -NLE_MSG_TOOSHORT;
250 return nla_validate(nlmsg_attrdata(nlh, hdrlen),
251 nlmsg_attrlen(nlh, hdrlen), maxtype, policy);
257 * @name Message Building/Access
261 static struct nl_msg *__nlmsg_alloc(size_t len)
265 if (len < sizeof(struct nlmsghdr))
266 len = sizeof(struct nlmsghdr);
268 nm = calloc(1, sizeof(*nm));
274 nm->nm_nlh = calloc(1, len);
278 memset(nm->nm_nlh, 0, sizeof(struct nlmsghdr));
280 nm->nm_protocol = -1;
282 nm->nm_nlh->nlmsg_len = nlmsg_total_size(0);
284 NL_DBG(2, "msg %p: Allocated new message, maxlen=%zu\n", nm, len);
293 * Allocate a new netlink message with the default maximum payload size.
295 * Allocates a new netlink message without any further payload. The
296 * maximum payload size defaults to PAGESIZE or as otherwise specified
297 * with nlmsg_set_default_size().
299 * @return Newly allocated netlink message or NULL.
301 struct nl_msg *nlmsg_alloc(void)
303 return __nlmsg_alloc(default_msg_size);
307 * Allocate a new netlink message with maximum payload size specified.
309 struct nl_msg *nlmsg_alloc_size(size_t max)
311 return __nlmsg_alloc(max);
315 * Allocate a new netlink message and inherit netlink message header
316 * @arg hdr Netlink message header template
318 * Allocates a new netlink message and inherits the original message
319 * header. If \a hdr is not NULL it will be used as a template for
320 * the netlink message header, otherwise the header is left blank.
322 * @return Newly allocated netlink message or NULL
324 struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr)
330 struct nlmsghdr *new = nm->nm_nlh;
332 new->nlmsg_type = hdr->nlmsg_type;
333 new->nlmsg_flags = hdr->nlmsg_flags;
334 new->nlmsg_seq = hdr->nlmsg_seq;
335 new->nlmsg_pid = hdr->nlmsg_pid;
342 * Allocate a new netlink message
343 * @arg nlmsgtype Netlink message type
344 * @arg flags Message flags.
346 * @return Newly allocated netlink message or NULL.
348 struct nl_msg *nlmsg_alloc_simple(int nlmsgtype, int flags)
351 struct nlmsghdr nlh = {
352 .nlmsg_type = nlmsgtype,
353 .nlmsg_flags = flags,
356 msg = nlmsg_inherit(&nlh);
358 NL_DBG(2, "msg %p: Allocated new simple message\n", msg);
364 * Set the default maximum message payload size for allocated messages
365 * @arg max Size of payload in bytes.
367 void nlmsg_set_default_size(size_t max)
369 if (max < nlmsg_total_size(0))
370 max = nlmsg_total_size(0);
372 default_msg_size = max;
376 * Convert a netlink message received from a netlink socket to a nl_msg
377 * @arg hdr Netlink message received from netlink socket.
379 * Allocates a new netlink message and copies all of the data pointed to
380 * by \a hdr into the new message object.
382 * @return Newly allocated netlink message or NULL.
384 struct nl_msg *nlmsg_convert(struct nlmsghdr *hdr)
388 nm = __nlmsg_alloc(NLMSG_ALIGN(hdr->nlmsg_len));
392 memcpy(nm->nm_nlh, hdr, hdr->nlmsg_len);
401 * Reserve room for additional data in a netlink message
402 * @arg n netlink message
403 * @arg len length of additional data to reserve room for
404 * @arg pad number of bytes to align data to
406 * Reserves room for additional data at the tail of the an
407 * existing netlink message. Eventual padding required will
410 * @return Pointer to start of additional data tailroom or NULL.
412 void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
414 void *buf = n->nm_nlh;
415 size_t nlmsg_len = n->nm_nlh->nlmsg_len;
418 tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
420 if ((tlen + nlmsg_len) > n->nm_size)
424 n->nm_nlh->nlmsg_len += tlen;
427 memset(buf + len, 0, tlen - len);
429 NL_DBG(2, "msg %p: Reserved %zu (%zu) bytes, pad=%d, nlmsg_len=%d\n",
430 n, tlen, len, pad, n->nm_nlh->nlmsg_len);
436 * Append data to tail of a netlink message
437 * @arg n netlink message
438 * @arg data data to add
439 * @arg len length of data
440 * @arg pad Number of bytes to align data to.
442 * Extends the netlink message as needed and appends the data of given
443 * length to the message.
445 * @return 0 on success or a negative error code
447 int nlmsg_append(struct nl_msg *n, void *data, size_t len, int pad)
451 tmp = nlmsg_reserve(n, len, pad);
455 memcpy(tmp, data, len);
456 NL_DBG(2, "msg %p: Appended %zu bytes with padding %d\n", n, len, pad);
462 * Expand maximum payload size of a netlink message
463 * @arg n Netlink message.
464 * @arg newlen New maximum payload size.
466 * Reallocates the payload section of a netlink message and increases
467 * the maximum payload size of the message.
469 * @note Any pointers pointing to old payload block will be stale and
470 * need to be refetched. Therfore, do not expand while constructing
471 * nested attributes or while reserved data blocks are held.
473 * @return 0 on success or a negative error code.
475 int nlmsg_expand(struct nl_msg *n, size_t newlen)
479 if (newlen <= n->nm_size)
482 tmp = realloc(n->nm_nlh, newlen);
493 * Add a netlink message header to a netlink message
494 * @arg n netlink message
495 * @arg pid netlink process id or NL_AUTO_PID
496 * @arg seq sequence number of message or NL_AUTO_SEQ
497 * @arg type message type
498 * @arg payload length of message payload
499 * @arg flags message flags
501 * Adds or overwrites the netlink message header in an existing message
502 * object. If \a payload is greater-than zero additional room will be
503 * reserved, f.e. for family specific headers. It can be accesed via
506 * @return A pointer to the netlink message header or NULL.
508 struct nlmsghdr *nlmsg_put(struct nl_msg *n, uint32_t pid, uint32_t seq,
509 int type, int payload, int flags)
511 struct nlmsghdr *nlh;
513 if (n->nm_nlh->nlmsg_len < NLMSG_HDRLEN)
516 nlh = (struct nlmsghdr *) n->nm_nlh;
517 nlh->nlmsg_type = type;
518 nlh->nlmsg_flags = flags;
519 nlh->nlmsg_pid = pid;
520 nlh->nlmsg_seq = seq;
522 NL_DBG(2, "msg %p: Added netlink header type=%d, flags=%d, pid=%d, "
523 "seq=%d\n", n, type, flags, pid, seq);
526 nlmsg_reserve(n, payload, NLMSG_ALIGNTO) == NULL)
533 * Return actual netlink message
534 * @arg n netlink message
536 * Returns the actual netlink message casted to the type of the netlink
539 * @return A pointer to the netlink message.
541 struct nlmsghdr *nlmsg_hdr(struct nl_msg *n)
547 * Acquire a reference on a netlink message
548 * @arg msg message to acquire reference from
550 void nlmsg_get(struct nl_msg *msg)
553 NL_DBG(4, "New reference to message %p, total %d\n",
554 msg, msg->nm_refcnt);
558 * Release a reference from an netlink message
559 * @arg msg message to release reference from
561 * Frees memory after the last reference has been released.
563 void nlmsg_free(struct nl_msg *msg)
569 NL_DBG(4, "Returned message reference %p, %d remaining\n",
570 msg, msg->nm_refcnt);
572 if (msg->nm_refcnt < 0)
575 if (msg->nm_refcnt <= 0) {
578 NL_DBG(2, "msg %p: Freed\n", msg);
589 void nlmsg_set_proto(struct nl_msg *msg, int protocol)
591 msg->nm_protocol = protocol;
594 int nlmsg_get_proto(struct nl_msg *msg)
596 return msg->nm_protocol;
599 size_t nlmsg_get_max_size(struct nl_msg *msg)
604 void nlmsg_set_src(struct nl_msg *msg, struct sockaddr_nl *addr)
606 memcpy(&msg->nm_src, addr, sizeof(*addr));
609 struct sockaddr_nl *nlmsg_get_src(struct nl_msg *msg)
614 void nlmsg_set_dst(struct nl_msg *msg, struct sockaddr_nl *addr)
616 memcpy(&msg->nm_dst, addr, sizeof(*addr));
619 struct sockaddr_nl *nlmsg_get_dst(struct nl_msg *msg)
624 void nlmsg_set_creds(struct nl_msg *msg, struct ucred *creds)
626 memcpy(&msg->nm_creds, creds, sizeof(*creds));
627 msg->nm_flags |= NL_MSG_CRED_PRESENT;
630 struct ucred *nlmsg_get_creds(struct nl_msg *msg)
632 if (msg->nm_flags & NL_MSG_CRED_PRESENT)
633 return &msg->nm_creds;
640 * @name Netlink Message Type Translations
644 static const struct trans_tbl nl_msgtypes[] = {
645 __ADD(NLMSG_NOOP,NOOP)
646 __ADD(NLMSG_ERROR,ERROR)
647 __ADD(NLMSG_DONE,DONE)
648 __ADD(NLMSG_OVERRUN,OVERRUN)
651 char *nl_nlmsgtype2str(int type, char *buf, size_t size)
653 return __type2str(type, buf, size, nl_msgtypes,
654 ARRAY_SIZE(nl_msgtypes));
657 int nl_str2nlmsgtype(const char *name)
659 return __str2type(name, nl_msgtypes, ARRAY_SIZE(nl_msgtypes));
665 * @name Netlink Message Flags Translations
669 char *nl_nlmsg_flags2str(int flags, char *buf, size_t len)
673 #define PRINT_FLAG(f) \
674 if (flags & NLM_F_##f) { \
675 flags &= ~NLM_F_##f; \
676 strncat(buf, #f, len - strlen(buf) - 1); \
678 strncat(buf, ",", len - strlen(buf) - 1); \
695 snprintf(s, sizeof(s), "0x%x", flags);
696 strncat(buf, s, len - strlen(buf) - 1);
706 * @name Direct Parsing
712 void (*cb)(struct nl_object *, void *);
717 static int parse_cb(struct nl_object *obj, struct nl_parser_param *p)
719 struct dp_xdata *x = p->pp_arg;
725 int nl_msg_parse(struct nl_msg *msg, void (*cb)(struct nl_object *, void *),
728 struct nl_cache_ops *ops;
729 struct nl_parser_param p = {
732 struct dp_xdata x = {
738 ops = nl_cache_ops_associate_safe(nlmsg_get_proto(msg),
739 nlmsg_hdr(msg)->nlmsg_type);
741 return -NLE_MSGTYPE_NOSUPPORT;
744 err = nl_cache_parse(ops, NULL, nlmsg_hdr(msg), &p);
745 nl_cache_ops_put(ops);
757 static void prefix_line(FILE *ofd, int prefix)
761 for (i = 0; i < prefix; i++)
765 static inline void dump_hex(FILE *ofd, char *start, int len, int prefix)
768 char ascii[21] = {0};
770 limit = 16 - (prefix * 2);
771 prefix_line(ofd, prefix);
774 for (i = 0, a = 0, c = 0; i < len; i++) {
775 int v = *(uint8_t *) (start + i);
777 fprintf(ofd, "%02x ", v);
778 ascii[a++] = isprint(v) ? v : '.';
781 fprintf(ofd, "%s\n", ascii);
783 prefix_line(ofd, prefix);
787 memset(ascii, 0, sizeof(ascii));
792 for (i = 0; i < (limit - c); i++)
794 fprintf(ofd, "%s\n", ascii);
798 static void print_hdr(FILE *ofd, struct nl_msg *msg)
800 struct nlmsghdr *nlh = nlmsg_hdr(msg);
801 struct nl_cache_ops *ops;
802 struct nl_msgtype *mt;
805 fprintf(ofd, " .nlmsg_len = %d\n", nlh->nlmsg_len);
807 ops = nl_cache_ops_associate_safe(nlmsg_get_proto(msg), nlh->nlmsg_type);
809 mt = nl_msgtype_lookup(ops, nlh->nlmsg_type);
813 snprintf(buf, sizeof(buf), "%s::%s", ops->co_name, mt->mt_name);
814 nl_cache_ops_put(ops);
816 nl_nlmsgtype2str(nlh->nlmsg_type, buf, sizeof(buf));
818 fprintf(ofd, " .type = %d <%s>\n", nlh->nlmsg_type, buf);
819 fprintf(ofd, " .flags = %d <%s>\n", nlh->nlmsg_flags,
820 nl_nlmsg_flags2str(nlh->nlmsg_flags, buf, sizeof(buf)));
821 fprintf(ofd, " .seq = %d\n", nlh->nlmsg_seq);
822 fprintf(ofd, " .port = %d\n", nlh->nlmsg_pid);
826 static void print_genl_hdr(FILE *ofd, void *start)
828 struct genlmsghdr *ghdr = start;
830 fprintf(ofd, " [GENERIC NETLINK HEADER] %zu octets\n", GENL_HDRLEN);
831 fprintf(ofd, " .cmd = %u\n", ghdr->cmd);
832 fprintf(ofd, " .version = %u\n", ghdr->version);
833 fprintf(ofd, " .unused = %#x\n", ghdr->reserved);
836 static void *print_genl_msg(struct nl_msg *msg, FILE *ofd, struct nlmsghdr *hdr,
837 struct nl_cache_ops *ops, int *payloadlen)
839 void *data = nlmsg_data(hdr);
841 if (*payloadlen < GENL_HDRLEN)
844 print_genl_hdr(ofd, data);
846 *payloadlen -= GENL_HDRLEN;
850 int hdrsize = ops->co_hdrsize - GENL_HDRLEN;
853 if (*payloadlen < hdrsize)
856 fprintf(ofd, " [HEADER] %d octets\n", hdrsize);
857 dump_hex(ofd, data, hdrsize, 0);
859 *payloadlen -= hdrsize;
867 static void dump_attr(FILE *ofd, struct nlattr *attr, int prefix)
869 int len = nla_len(attr);
871 dump_hex(ofd, nla_data(attr), len, prefix);
874 static void dump_attrs(FILE *ofd, struct nlattr *attrs, int attrlen,
880 nla_for_each_attr(nla, attrs, attrlen, rem) {
881 int padlen, alen = nla_len(nla);
883 prefix_line(ofd, prefix);
885 if (nla->nla_type == 0)
886 fprintf(ofd, " [ATTR PADDING] %d octets\n", alen);
888 fprintf(ofd, " [ATTR %02d%s] %d octets\n", nla_type(nla),
889 nla_is_nested(nla) ? " NESTED" : "",
892 if (nla_is_nested(nla))
893 dump_attrs(ofd, nla_data(nla), alen, prefix+1);
895 dump_attr(ofd, nla, prefix);
897 padlen = nla_padlen(alen);
899 prefix_line(ofd, prefix);
900 fprintf(ofd, " [PADDING] %d octets\n",
902 dump_hex(ofd, nla_data(nla) + alen,
908 prefix_line(ofd, prefix);
909 fprintf(ofd, " [LEFTOVER] %d octets\n", rem);
913 static void dump_error_msg(struct nl_msg *msg, FILE *ofd)
915 struct nlmsghdr *hdr = nlmsg_hdr(msg);
916 struct nlmsgerr *err = nlmsg_data(hdr);
918 fprintf(ofd, " [ERRORMSG] %zu octets\n", sizeof(*err));
920 if (nlmsg_len(hdr) >= sizeof(*err)) {
922 struct nl_msg *errmsg;
924 fprintf(ofd, " .error = %d \"%s\"\n", err->error,
925 strerror_r(-err->error, buf, sizeof(buf)));
926 fprintf(ofd, " [ORIGINAL MESSAGE] %zu octets\n", sizeof(*hdr));
928 errmsg = nlmsg_inherit(&err->msg);
929 print_hdr(ofd, errmsg);
934 static void print_msg(struct nl_msg *msg, FILE *ofd, struct nlmsghdr *hdr)
936 struct nl_cache_ops *ops;
937 int payloadlen = nlmsg_len(hdr);
941 data = nlmsg_data(hdr);
942 ops = nl_cache_ops_associate_safe(nlmsg_get_proto(msg),
945 attrlen = nlmsg_attrlen(hdr, ops->co_hdrsize);
946 payloadlen -= attrlen;
949 if (msg->nm_protocol == NETLINK_GENERIC)
950 data = print_genl_msg(msg, ofd, hdr, ops, &payloadlen);
953 fprintf(ofd, " [PAYLOAD] %d octets\n", payloadlen);
954 dump_hex(ofd, data, payloadlen, 0);
958 struct nlattr *attrs;
961 attrs = nlmsg_attrdata(hdr, ops->co_hdrsize);
962 attrlen = nlmsg_attrlen(hdr, ops->co_hdrsize);
963 dump_attrs(ofd, attrs, attrlen, 0);
967 nl_cache_ops_put(ops);
971 * Dump message in human readable format to file descriptor
972 * @arg msg Message to print
973 * @arg ofd File descriptor.
975 void nl_msg_dump(struct nl_msg *msg, FILE *ofd)
977 struct nlmsghdr *hdr = nlmsg_hdr(msg);
980 "-------------------------- BEGIN NETLINK MESSAGE ---------------------------\n");
982 fprintf(ofd, " [NETLINK HEADER] %zu octets\n", sizeof(struct nlmsghdr));
985 if (hdr->nlmsg_type == NLMSG_ERROR)
986 dump_error_msg(msg, ofd);
987 else if (nlmsg_len(hdr) > 0)
988 print_msg(msg, ofd, hdr);
991 "--------------------------- END NETLINK MESSAGE ---------------------------\n");