firmware-utils: move bcm_tag.h here
[openwrt/svn-archive/archive.git] / package / libnl-tiny / src / 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 (\link nlmsghdr struct nlmsghdr\endlink) 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 <netlink/msg.h>
167 #include <linux/socket.h>
168
169 static size_t default_msg_size;
170
171 static void __init init_msg_size(void)
172 {
173 default_msg_size = getpagesize();
174 }
175
176 /**
177 * @name Attribute Access
178 * @{
179 */
180
181 //** @} */
182
183 /**
184 * @name Message Parsing
185 * @{
186 */
187
188 /**
189 * check if the netlink message fits into the remaining bytes
190 * @arg nlh netlink message header
191 * @arg remaining number of bytes remaining in message stream
192 */
193 int nlmsg_ok(const struct nlmsghdr *nlh, int remaining)
194 {
195 return (remaining >= sizeof(struct nlmsghdr) &&
196 nlh->nlmsg_len >= sizeof(struct nlmsghdr) &&
197 nlh->nlmsg_len <= remaining);
198 }
199
200 /**
201 * next netlink message in message stream
202 * @arg nlh netlink message header
203 * @arg remaining number of bytes remaining in message stream
204 *
205 * @returns the next netlink message in the message stream and
206 * decrements remaining by the size of the current message.
207 */
208 struct nlmsghdr *nlmsg_next(struct nlmsghdr *nlh, int *remaining)
209 {
210 int totlen = NLMSG_ALIGN(nlh->nlmsg_len);
211
212 *remaining -= totlen;
213
214 return (struct nlmsghdr *) ((unsigned char *) nlh + totlen);
215 }
216
217 /**
218 * parse attributes of a netlink message
219 * @arg nlh netlink message header
220 * @arg hdrlen length of family specific header
221 * @arg tb destination array with maxtype+1 elements
222 * @arg maxtype maximum attribute type to be expected
223 * @arg policy validation policy
224 *
225 * See nla_parse()
226 */
227 int nlmsg_parse(struct nlmsghdr *nlh, int hdrlen, struct nlattr *tb[],
228 int maxtype, struct nla_policy *policy)
229 {
230 if (!nlmsg_valid_hdr(nlh, hdrlen))
231 return -NLE_MSG_TOOSHORT;
232
233 return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen),
234 nlmsg_attrlen(nlh, hdrlen), policy);
235 }
236
237 /**
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
243 */
244 int nlmsg_validate(struct nlmsghdr *nlh, int hdrlen, int maxtype,
245 struct nla_policy *policy)
246 {
247 if (!nlmsg_valid_hdr(nlh, hdrlen))
248 return -NLE_MSG_TOOSHORT;
249
250 return nla_validate(nlmsg_attrdata(nlh, hdrlen),
251 nlmsg_attrlen(nlh, hdrlen), maxtype, policy);
252 }
253
254 /** @} */
255
256 /**
257 * @name Message Building/Access
258 * @{
259 */
260
261 static struct nl_msg *__nlmsg_alloc(size_t len)
262 {
263 struct nl_msg *nm;
264
265 nm = calloc(1, sizeof(*nm));
266 if (!nm)
267 goto errout;
268
269 nm->nm_refcnt = 1;
270
271 nm->nm_nlh = malloc(len);
272 if (!nm->nm_nlh)
273 goto errout;
274
275 memset(nm->nm_nlh, 0, sizeof(struct nlmsghdr));
276
277 nm->nm_protocol = -1;
278 nm->nm_size = len;
279 nm->nm_nlh->nlmsg_len = nlmsg_total_size(0);
280
281 NL_DBG(2, "msg %p: Allocated new message, maxlen=%zu\n", nm, len);
282
283 return nm;
284 errout:
285 free(nm);
286 return NULL;
287 }
288
289 /**
290 * Allocate a new netlink message with the default maximum payload size.
291 *
292 * Allocates a new netlink message without any further payload. The
293 * maximum payload size defaults to PAGESIZE or as otherwise specified
294 * with nlmsg_set_default_size().
295 *
296 * @return Newly allocated netlink message or NULL.
297 */
298 struct nl_msg *nlmsg_alloc(void)
299 {
300 return __nlmsg_alloc(default_msg_size);
301 }
302
303 /**
304 * Allocate a new netlink message with maximum payload size specified.
305 */
306 struct nl_msg *nlmsg_alloc_size(size_t max)
307 {
308 return __nlmsg_alloc(max);
309 }
310
311 /**
312 * Allocate a new netlink message and inherit netlink message header
313 * @arg hdr Netlink message header template
314 *
315 * Allocates a new netlink message and inherits the original message
316 * header. If \a hdr is not NULL it will be used as a template for
317 * the netlink message header, otherwise the header is left blank.
318 *
319 * @return Newly allocated netlink message or NULL
320 */
321 struct nl_msg *nlmsg_inherit(struct nlmsghdr *hdr)
322 {
323 struct nl_msg *nm;
324
325 nm = nlmsg_alloc();
326 if (nm && hdr) {
327 struct nlmsghdr *new = nm->nm_nlh;
328
329 new->nlmsg_type = hdr->nlmsg_type;
330 new->nlmsg_flags = hdr->nlmsg_flags;
331 new->nlmsg_seq = hdr->nlmsg_seq;
332 new->nlmsg_pid = hdr->nlmsg_pid;
333 }
334
335 return nm;
336 }
337
338 /**
339 * Allocate a new netlink message
340 * @arg nlmsgtype Netlink message type
341 * @arg flags Message flags.
342 *
343 * @return Newly allocated netlink message or NULL.
344 */
345 struct nl_msg *nlmsg_alloc_simple(int nlmsgtype, int flags)
346 {
347 struct nl_msg *msg;
348 struct nlmsghdr nlh = {
349 .nlmsg_type = nlmsgtype,
350 .nlmsg_flags = flags,
351 };
352
353 msg = nlmsg_inherit(&nlh);
354 if (msg)
355 NL_DBG(2, "msg %p: Allocated new simple message\n", msg);
356
357 return msg;
358 }
359
360 /**
361 * Set the default maximum message payload size for allocated messages
362 * @arg max Size of payload in bytes.
363 */
364 void nlmsg_set_default_size(size_t max)
365 {
366 if (max < nlmsg_total_size(0))
367 max = nlmsg_total_size(0);
368
369 default_msg_size = max;
370 }
371
372 /**
373 * Convert a netlink message received from a netlink socket to a nl_msg
374 * @arg hdr Netlink message received from netlink socket.
375 *
376 * Allocates a new netlink message and copies all of the data pointed to
377 * by \a hdr into the new message object.
378 *
379 * @return Newly allocated netlink message or NULL.
380 */
381 struct nl_msg *nlmsg_convert(struct nlmsghdr *hdr)
382 {
383 struct nl_msg *nm;
384
385 nm = __nlmsg_alloc(NLMSG_ALIGN(hdr->nlmsg_len));
386 if (!nm)
387 goto errout;
388
389 memcpy(nm->nm_nlh, hdr, hdr->nlmsg_len);
390
391 return nm;
392 errout:
393 nlmsg_free(nm);
394 return NULL;
395 }
396
397 /**
398 * Reserve room for additional data in a netlink message
399 * @arg n netlink message
400 * @arg len length of additional data to reserve room for
401 * @arg pad number of bytes to align data to
402 *
403 * Reserves room for additional data at the tail of the an
404 * existing netlink message. Eventual padding required will
405 * be zeroed out.
406 *
407 * @return Pointer to start of additional data tailroom or NULL.
408 */
409 void *nlmsg_reserve(struct nl_msg *n, size_t len, int pad)
410 {
411 void *buf = n->nm_nlh;
412 size_t nlmsg_len = n->nm_nlh->nlmsg_len;
413 size_t tlen;
414
415 tlen = pad ? ((len + (pad - 1)) & ~(pad - 1)) : len;
416
417 if ((tlen + nlmsg_len) > n->nm_size)
418 return NULL;
419
420 buf += nlmsg_len;
421 n->nm_nlh->nlmsg_len += tlen;
422
423 if (tlen > len)
424 memset(buf + len, 0, tlen - len);
425
426 NL_DBG(2, "msg %p: Reserved %zu bytes, pad=%d, nlmsg_len=%d\n",
427 n, len, pad, n->nm_nlh->nlmsg_len);
428
429 return buf;
430 }
431
432 /**
433 * Append data to tail of a netlink message
434 * @arg n netlink message
435 * @arg data data to add
436 * @arg len length of data
437 * @arg pad Number of bytes to align data to.
438 *
439 * Extends the netlink message as needed and appends the data of given
440 * length to the message.
441 *
442 * @return 0 on success or a negative error code
443 */
444 int nlmsg_append(struct nl_msg *n, void *data, size_t len, int pad)
445 {
446 void *tmp;
447
448 tmp = nlmsg_reserve(n, len, pad);
449 if (tmp == NULL)
450 return -NLE_NOMEM;
451
452 memcpy(tmp, data, len);
453 NL_DBG(2, "msg %p: Appended %zu bytes with padding %d\n", n, len, pad);
454
455 return 0;
456 }
457
458 /**
459 * Add a netlink message header to a netlink message
460 * @arg n netlink message
461 * @arg pid netlink process id or NL_AUTO_PID
462 * @arg seq sequence number of message or NL_AUTO_SEQ
463 * @arg type message type
464 * @arg payload length of message payload
465 * @arg flags message flags
466 *
467 * Adds or overwrites the netlink message header in an existing message
468 * object. If \a payload is greater-than zero additional room will be
469 * reserved, f.e. for family specific headers. It can be accesed via
470 * nlmsg_data().
471 *
472 * @return A pointer to the netlink message header or NULL.
473 */
474 struct nlmsghdr *nlmsg_put(struct nl_msg *n, uint32_t pid, uint32_t seq,
475 int type, int payload, int flags)
476 {
477 struct nlmsghdr *nlh;
478
479 if (n->nm_nlh->nlmsg_len < NLMSG_HDRLEN)
480 BUG();
481
482 nlh = (struct nlmsghdr *) n->nm_nlh;
483 nlh->nlmsg_type = type;
484 nlh->nlmsg_flags = flags;
485 nlh->nlmsg_pid = pid;
486 nlh->nlmsg_seq = seq;
487
488 NL_DBG(2, "msg %p: Added netlink header type=%d, flags=%d, pid=%d, "
489 "seq=%d\n", n, type, flags, pid, seq);
490
491 if (payload > 0 &&
492 nlmsg_reserve(n, payload, NLMSG_ALIGNTO) == NULL)
493 return NULL;
494
495 return nlh;
496 }
497
498 /**
499 * Release a reference from an netlink message
500 * @arg msg message to release reference from
501 *
502 * Frees memory after the last reference has been released.
503 */
504 void nlmsg_free(struct nl_msg *msg)
505 {
506 if (!msg)
507 return;
508
509 msg->nm_refcnt--;
510 NL_DBG(4, "Returned message reference %p, %d remaining\n",
511 msg, msg->nm_refcnt);
512
513 if (msg->nm_refcnt < 0)
514 BUG();
515
516 if (msg->nm_refcnt <= 0) {
517 free(msg->nm_nlh);
518 free(msg);
519 NL_DBG(2, "msg %p: Freed\n", msg);
520 }
521 }
522
523 /** @} */
524
525 /**
526 * @name Direct Parsing
527 * @{
528 */
529
530 /** @cond SKIP */
531 struct dp_xdata {
532 void (*cb)(struct nl_object *, void *);
533 void *arg;
534 };
535 /** @endcond */
536
537 static int parse_cb(struct nl_object *obj, struct nl_parser_param *p)
538 {
539 struct dp_xdata *x = p->pp_arg;
540
541 x->cb(obj, x->arg);
542 return 0;
543 }
544
545 int nl_msg_parse(struct nl_msg *msg, void (*cb)(struct nl_object *, void *),
546 void *arg)
547 {
548 struct nl_cache_ops *ops;
549 struct nl_parser_param p = {
550 .pp_cb = parse_cb
551 };
552 struct dp_xdata x = {
553 .cb = cb,
554 .arg = arg,
555 };
556
557 ops = nl_cache_ops_associate(nlmsg_get_proto(msg),
558 nlmsg_hdr(msg)->nlmsg_type);
559 if (ops == NULL)
560 return -NLE_MSGTYPE_NOSUPPORT;
561 p.pp_arg = &x;
562
563 return nl_cache_parse(ops, NULL, nlmsg_hdr(msg), &p);
564 }
565
566 /** @} */