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