oops
[libnl.git] / lib / nl.c
1 /*
2  * lib/nl.c             Core Netlink 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-2006 Thomas Graf <tgraf@suug.ch>
10  */
11
12 /**
13  * @defgroup nl Core Netlink API
14  * @brief
15  *
16  * @par 1) Creating the netlink handle
17  * @code
18  * struct nl_handle *handle;
19  *
20  * // Allocate and initialize a new netlink handle
21  * handle = nl_handle_new();
22  *
23  * // Are multiple handles being allocated? You have to provide a unique
24  * // netlink process id and overwrite the default local process id.
25  * nl_handle_set_pid(handle, MY_UNIQUE_PID);
26  *
27  * // Is this socket used for event processing? You need to disable sequence
28  * // number checking in order to be able to receive messages not explicitely
29  * // requested.
30  * nl_disable_sequence_check(handle);
31  *
32  * // Use nl_handle_get_fd() to fetch the file description, for example to
33  * // put a socket into non-blocking i/o mode.
34  * fcntl(nl_handle_get_fd(handle), F_SETFL, O_NONBLOCK);
35  * @endcode
36  *
37  * @par 2) Joining Groups
38  * @code
39  * // You may join/subscribe to as many groups as you want, don't forget
40  * // to eventually disable sequence number checking. Note: Joining must
41  * // be done before connecting/binding the socket.
42  * nl_join_groups(handle, GROUP_ID1 | GROUP_ID2);
43  * @endcode
44  *
45  * @par 3) Connecting the socket
46  * @code
47  * // Bind and connect the socket to a protocol, NETLINK_ROUTE in this example.
48  * nl_connect(handle, NETLINK_ROUTE);
49  * @endcode
50  *
51  * @par 4) Sending data
52  * @code
53  * // The most rudimentary method is to use nl_sendto() simply pushing
54  * // a piece of data to the other netlink peer. This method is not
55  * // recommended.
56  * const char buf[] = { 0x01, 0x02, 0x03, 0x04 };
57  * nl_sendto(handle, buf, sizeof(buf));
58  *
59  * // A more comfortable interface is nl_send() taking a pointer to
60  * // a netlink message.
61  * struct nl_msg *msg = my_msg_builder();
62  * nl_send(handle, nlmsg_hdr(msg));
63  *
64  * // nl_sendmsg() provides additional control over the sendmsg() message
65  * // header in order to allow more specific addressing of multiple peers etc.
66  * struct msghdr hdr = { ... };
67  * nl_sendmsg(handle, nlmsg_hdr(msg), &hdr);
68  *
69  * // You're probably too lazy to fill out the netlink pid, sequence number
70  * // and message flags all the time. nl_send_auto_complete() automatically
71  * // extends your message header as needed with an appropriate sequence
72  * // number, the netlink pid stored in the netlink handle and the message
73  * // flags NLM_F_REQUEST and NLM_F_ACK
74  * nl_send_auto_complete(handle, nlmsg_hdr(msg));
75  *
76  * // Simple protocols don't require the complex message construction interface
77  * // and may favour nl_send_simple() to easly send a bunch of payload
78  * // encapsulated in a netlink message header.
79  * nl_send_simple(handle, MY_MSG_TYPE, 0, buf, sizeof(buf));
80  * @endcode
81  *
82  * @par 5) Receiving data
83  * @code
84  * // nl_recv() receives a single message allocating a buffer for the message
85  * // content and gives back the pointer to you.
86  * struct sockaddr_nl peer;
87  * unsigned char *msg;
88  * nl_recv(handle, &peer, &msg);
89  *
90  * // nl_recvmsgs() receives a bunch of messages until the callback system
91  * // orders it to state, usually after receving a compolete multi part
92  * // message series.
93  * nl_recvmsgs(handle, my_callback_configuration);
94  *
95  * // nl_recvmsgs_def() acts just like nl_recvmsg() but uses the callback
96  * // configuration stored in the handle.
97  * nl_recvmsgs_def(handle);
98  *
99  * // In case you want to wait for the ACK to be recieved that you requested
100  * // with your latest message, you can call nl_wait_for_ack()
101  * nl_wait_for_ack(handle);
102  * @endcode
103  *
104  * @par 6) Cleaning up
105  * @code
106  * // Close the socket first to release kernel memory
107  * nl_close(handle);
108  *
109  * // Finally destroy the netlink handle
110  * nl_handle_destroy(handle);
111  * @endcode
112  * 
113  * @{
114  */
115
116 #include <netlink-local.h>
117 #include <netlink/netlink.h>
118 #include <netlink/utils.h>
119 #include <netlink/handlers.h>
120 #include <netlink/msg.h>
121 #include <netlink/attr.h>
122
123 /**
124  * @name Handle Management
125  * @{
126  */
127
128 /**
129  * Allocate and initialize new non-default netlink handle.
130  * @arg kind            Kind of callback handler to use per default.
131  *
132  * Allocates and initializes a new netlink handle, the netlink process id
133  * is set to the local process id which may conflict if multiple handles
134  * are created, therefore you may have to overwrite it using
135  * nl_handle_set_pid(). The initial sequence number is initialized to the
136  * current UNIX time.
137  *
138  * @return Newly allocated netlink handle or NULL.
139  */
140 struct nl_handle *nl_handle_alloc_nondefault(enum nl_cb_kind kind)
141 {
142         struct nl_handle *handle;
143         
144         handle = calloc(1, sizeof(*handle));
145         if (!handle)
146                 goto errout;
147
148         handle->h_cb = nl_cb_new(kind);
149         if (!handle->h_cb)
150                 goto errout;
151         
152         handle->h_local.nl_family = AF_NETLINK;
153         handle->h_peer.nl_family = AF_NETLINK;
154         handle->h_local.nl_pid = getpid();
155         handle->h_seq_expect = handle->h_seq_next = time(0);
156
157         return handle;
158 errout:
159         nl_handle_destroy(handle);
160         nl_errno(ENOMEM);
161         return NULL;
162 }
163
164 /**
165  * Allocate and initialize new netlink handle.
166  *
167  * Allocates and initializes a new netlink handle, the netlink process id
168  * is set to the local process id which may conflict if multiple handles
169  * are created, therefore you may have to overwrite it using
170  * nl_handle_set_pid(). The initial sequence number is initialized to the
171  * current UNIX time. The default callback (NL_CB_DEFAULT) handlers are
172  * being used.
173  *
174  * @return Newly allocated netlink handle or NULL.
175  */
176 struct nl_handle *nl_handle_alloc(void)
177 {
178         return nl_handle_alloc_nondefault(NL_CB_DEFAULT);
179 }
180
181 /**
182  * Destroy netlink handle.
183  * @arg handle          Netlink handle.
184  */
185 void nl_handle_destroy(struct nl_handle *handle)
186 {
187         if (!handle)
188                 return;
189
190         nl_cb_destroy(handle->h_cb);
191         free(handle);
192 }
193
194 /** @} */
195
196 /**
197  * @name Utilities
198  * @{
199  */
200
201 /**
202  * Set socket buffer size of netlink handle.
203  * @arg handle          Netlink handle.
204  * @arg rxbuf           New receive socket buffer size in bytes.
205  * @arg txbuf           New transmit socket buffer size in bytes.
206  *
207  * Sets the socket buffer size of a netlink handle to the specified
208  * values \c rxbuf and \c txbuf. Providing a value of \c 0 assumes a
209  * good default value.
210  *
211  * @note It is not required to call this function prior to nl_connect().
212  * @return 0 on sucess or a negative error code.
213  */
214 int nl_set_buffer_size(struct nl_handle *handle, int rxbuf, int txbuf)
215 {
216         int err;
217
218         if (rxbuf <= 0)
219                 rxbuf = 32768;
220
221         if (txbuf <= 0)
222                 txbuf = 32768;
223         
224         err = setsockopt(handle->h_fd, SOL_SOCKET, SO_SNDBUF,
225                          &txbuf, sizeof(txbuf));
226         if (err < 0)
227                 return nl_error(errno, "setsockopt(SO_SNDBUF) failed");
228
229         err = setsockopt(handle->h_fd, SOL_SOCKET, SO_RCVBUF,
230                          &rxbuf, sizeof(rxbuf));
231         if (err < 0)
232                 return nl_error(errno, "setsockopt(SO_RCVBUF) failed");
233
234         handle->h_flags |= NL_SOCK_BUFSIZE_SET;
235
236         return 0;
237 }
238
239 /**
240  * Enable/disable credential passing on netlink handle.
241  * @arg handle          Netlink handle
242  * @arg state           New state (0 - disabled, 1 - enabled)
243  */
244 int nl_set_passcred(struct nl_handle *handle, int state)
245 {
246         int err;
247
248         err = setsockopt(handle->h_fd, SOL_SOCKET, SO_PASSCRED,
249                          &state, sizeof(state));
250         if (err < 0)
251                 return nl_error(errno, "setsockopt(SO_PASSCRED) failed");
252
253         if (state)
254                 handle->h_flags |= NL_SOCK_PASSCRED;
255         else
256                 handle->h_flags &= ~NL_SOCK_PASSCRED;
257
258         return 0;
259 }
260
261 /**
262  * Join multicast groups.
263  * @arg handle          Netlink handle.
264  * @arg groups          Bitmask of groups to join.
265  *
266  * @note Joining of groups must be done prior to connecting/binding
267  *       the socket (nl_connect()).
268  */
269 void nl_join_groups(struct nl_handle *handle, int groups)
270 {
271         handle->h_local.nl_groups |= groups;
272 }
273
274 #ifndef SOL_NETLINK
275 #define SOL_NETLINK 270
276 #endif
277
278 int nl_join_group(struct nl_handle *handle, int group)
279 {
280         int err;
281
282         err = setsockopt(handle->h_fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
283                          &group, sizeof(group));
284         if (err < 0)
285                 return nl_error(errno, "setsockopt(NETLINK_ADD_MEMBERSHIP) "
286                                        "failed");
287
288         return 0;
289 }
290
291 static int noop_seq_check(struct nl_msg *msg, void *arg)
292 {
293         return NL_PROCEED;
294 }
295
296 /**
297  * Disable sequence number checking.
298  * @arg handle          Netlink handle.
299  *
300  * Disables checking of sequence numbers on the netlink handle. This is
301  * required to allow messages to be processed which were not requested by
302  * a preceding request message, e.g. netlink events.
303  */
304 void nl_disable_sequence_check(struct nl_handle *handle)
305 {
306         nl_cb_set(nl_handle_get_cb(handle), NL_CB_SEQ_CHECK,
307                   NL_CB_CUSTOM, noop_seq_check, NULL);
308 }
309
310 /** @} */
311
312 /**
313  * @name Acccess Functions
314  * @{
315  */
316
317 /**
318  * Get netlink process identifier of netlink handle.
319  * @arg handle          Netlink handle.
320  * @return Netlink process identifier.
321  */
322 pid_t nl_handle_get_pid(struct nl_handle *handle)
323 {
324         return handle->h_local.nl_pid;
325 }
326
327 /**
328  * Set netlink process identifier of netlink handle.
329  * @arg handle          Netlink handle.
330  * @arg pid             New netlink process identifier.
331  */
332 void nl_handle_set_pid(struct nl_handle *handle, pid_t pid)
333 {
334         handle->h_local.nl_pid = pid;
335 }
336
337 /**
338  * Get netlink process identifier of peer from netlink handle.
339  * @arg handle          Netlink handle.
340  * @return Netlink process identifier.
341  */
342 pid_t nl_handle_get_peer_pid(struct nl_handle *handle)
343 {
344         return handle->h_peer.nl_pid;
345 }
346
347 /**
348  * Set netlink process identifier of peer in netlink handle.
349  * @arg handle          Netlink handle.
350  * @arg pid             New netlink process identifier.
351  */
352 void nl_handle_set_peer_pid(struct nl_handle *handle, pid_t pid)
353 {
354         handle->h_peer.nl_pid = pid;
355 }
356
357 /**
358  * Get file descriptor of netlink handle.
359  * @arg handle          Netlink handle.
360  * @return File descriptor of netlink socket or -1 if not connected.
361  */
362 int nl_handle_get_fd(struct nl_handle *handle)
363 {
364         return handle->h_fd;
365 }
366
367 /**
368  * Get local netlink address of netlink handle.
369  * @arg handle          Netlink handle.
370  * @return Local netlink address.
371  */
372 struct sockaddr_nl *nl_handle_get_local_addr(struct nl_handle *handle)
373 {
374         return &handle->h_local;
375 }
376
377 /**
378  * Get peer netlink address of netlink handle.
379  * @arg handle          Netlink handle.
380  * @note The peer address is undefined while the socket is unconnected.
381  * @return Netlink address of the peer.
382  */
383 struct sockaddr_nl *nl_handle_get_peer_addr(struct nl_handle *handle)
384 {
385         return &handle->h_peer;
386 }
387
388 /**
389  * Get callback configuration of netlink handle.
390  * @arg handle          Netlink handle.
391  * @return Currently active callback configuration or NULL if not available.
392  */
393 struct nl_cb *nl_handle_get_cb(struct nl_handle *handle)
394 {
395         return handle->h_cb;
396 }
397
398 /** @} */
399
400 /**
401  * @name Connection Management
402  * @{
403  */
404
405 /**
406  * Create and connect netlink socket.
407  * @arg handle          Netlink handle.
408  * @arg protocol        Netlink protocol to use.
409  *
410  * Creates a netlink socket using the specified protocol, binds the socket
411  * and issues a connection attempt.
412  *
413  * @return 0 on success or a negative error code.
414  */
415 int nl_connect(struct nl_handle *handle, int protocol)
416 {
417         int err;
418         socklen_t addrlen;
419
420         handle->h_fd = socket(AF_NETLINK, SOCK_RAW, protocol);
421         if (handle->h_fd < 0)
422                 return nl_error(1, "socket(AF_NETLINK, ...) failed");
423
424         if (!(handle->h_flags & NL_SOCK_BUFSIZE_SET)) {
425                 err = nl_set_buffer_size(handle, 0, 0);
426                 if (err < 0)
427                         return err;
428         }
429
430         err = bind(handle->h_fd, (struct sockaddr*) &handle->h_local,
431                    sizeof(handle->h_local));
432         if (err < 0)
433                 return nl_error(1, "bind() failed");
434
435         addrlen = sizeof(handle->h_local);
436         err = getsockname(handle->h_fd, (struct sockaddr *) &handle->h_local,
437                           &addrlen);
438         if (err < 0)
439                 return nl_error(1, "getsockname failed");
440
441         if (addrlen != sizeof(handle->h_local))
442                 return nl_error(EADDRNOTAVAIL, "Invalid address length");
443
444         if (handle->h_local.nl_family != AF_NETLINK)
445                 return nl_error(EPFNOSUPPORT, "Address format not supported");
446
447         handle->h_proto = protocol;
448
449         return 0;
450 }
451
452 /**
453  * Close/Disconnect netlink socket.
454  * @arg handle          Netlink handle
455  */
456 void nl_close(struct nl_handle *handle)
457 {
458         if (handle->h_fd >= 0) {
459                 close(handle->h_fd);
460                 handle->h_fd = -1;
461         }
462
463         handle->h_proto = 0;
464 }
465
466 /** @} */
467
468 /**
469  * @name Send
470  * @{
471  */
472
473 /**
474  * Send raw data over netlink socket.
475  * @arg handle          Netlink handle.
476  * @arg buf             Data buffer.
477  * @arg size            Size of data buffer.
478  * @return Number of characters written on success or a negative error code.
479  */
480 int nl_sendto(struct nl_handle *handle, void *buf, size_t size)
481 {
482         int ret;
483
484         ret = sendto(handle->h_fd, buf, size, 0, (struct sockaddr *)
485                      &handle->h_peer, sizeof(handle->h_peer));
486         if (ret < 0)
487                 return nl_errno(errno);
488
489         return ret;
490 }
491
492 /**
493  * Send netlink message with control over sendmsg() message header.
494  * @arg handle          Netlink handle.
495  * @arg msg             Netlink message to be sent.
496  * @arg hdr             Sendmsg() message header.
497  * @return Number of characters sent on sucess or a negative error code.
498  */
499 int nl_sendmsg(struct nl_handle *handle, struct nl_msg *msg, struct msghdr *hdr)
500 {
501         struct nl_cb *cb;
502         int ret;
503
504         struct iovec iov = {
505                 .iov_base = (void *) nlmsg_hdr(msg),
506                 .iov_len = nlmsg_hdr(msg)->nlmsg_len,
507         };
508
509         hdr->msg_iov = &iov;
510         hdr->msg_iovlen = 1;
511
512         nlmsg_set_src(msg, &handle->h_local);
513
514         cb = nl_handle_get_cb(handle);
515         if (cb->cb_set[NL_CB_MSG_OUT])
516                 if (nl_cb_call(cb, NL_CB_MSG_OUT, msg) != NL_PROCEED)
517                         return 0;
518
519         ret = sendmsg(handle->h_fd, hdr, 0);
520         if (ret < 0)
521                 return nl_errno(errno);
522
523         return ret;
524 }
525
526
527 /**
528  * Send netlink message.
529  * @arg handle          Netlink handle
530  * @arg msg             Netlink message to be sent.
531  * @see nl_sendmsg()
532  * @return Number of characters sent on success or a negative error code.
533  */
534 int nl_send(struct nl_handle *handle, struct nl_msg *msg)
535 {
536         struct sockaddr_nl *dst;
537         struct ucred *creds;
538         
539         struct msghdr hdr = {
540                 .msg_name = (void *) &handle->h_peer,
541                 .msg_namelen = sizeof(struct sockaddr_nl),
542         };
543
544         /* Overwrite destination if specified in the message itself, defaults
545          * to the peer address of the handle.
546          */
547         dst = nlmsg_get_dst(msg);
548         if (dst->nl_family == AF_NETLINK)
549                 hdr.msg_name = dst;
550
551         /* Add credentials if present. */
552         creds = nlmsg_get_creds(msg);
553         if (creds != NULL) {
554                 char buf[CMSG_SPACE(sizeof(struct ucred))];
555                 struct cmsghdr *cmsg;
556
557                 hdr.msg_control = buf;
558                 hdr.msg_controllen = sizeof(buf);
559
560                 cmsg = CMSG_FIRSTHDR(&hdr);
561                 cmsg->cmsg_level = SOL_SOCKET;
562                 cmsg->cmsg_type = SCM_CREDENTIALS;
563                 cmsg->cmsg_len = CMSG_LEN(sizeof(struct ucred));
564                 memcpy(CMSG_DATA(cmsg), creds, sizeof(struct ucred));
565         }
566
567         return nl_sendmsg(handle, msg, &hdr);
568 }
569
570 /**
571  * Send netlink message and check & extend header values as needed.
572  * @arg handle          Netlink handle.
573  * @arg msg             Netlink message to be sent.
574  *
575  * Checks the netlink message \c nlh for completness and extends it
576  * as required before sending it out. Checked fields include pid,
577  * sequence nr, and flags.
578  *
579  * @see nl_send()
580  * @return Number of characters sent or a negative error code.
581  */
582 int nl_send_auto_complete(struct nl_handle *handle, struct nl_msg *msg)
583 {
584         struct nlmsghdr *nlh;
585
586         nlh = nlmsg_hdr(msg);
587         if (nlh->nlmsg_pid == 0)
588                 nlh->nlmsg_pid = handle->h_local.nl_pid;
589
590         if (nlh->nlmsg_seq == 0)
591                 nlh->nlmsg_seq = handle->h_seq_next++;
592         
593         nlh->nlmsg_flags |= (NLM_F_REQUEST | NLM_F_ACK);
594
595         if (handle->h_cb->cb_send_ow)
596                 return handle->h_cb->cb_send_ow(handle, msg);
597         else
598                 return nl_send(handle, msg);
599 }
600
601 /**
602  * Send simple netlink message using nl_send_auto_complete()
603  * @arg handle          Netlink handle.
604  * @arg type            Netlink message type.
605  * @arg flags           Netlink message flags.
606  * @arg buf             Data buffer.
607  * @arg size            Size of data buffer.
608  *
609  * Builds a netlink message with the specified type and flags and
610  * appends the specified data as payload to the message.
611  *
612  * @see nl_send_auto_complete()
613  * @return Number of characters sent on success or a negative error code.
614  */
615 int nl_send_simple(struct nl_handle *handle, int type, int flags, void *buf,
616                    size_t size)
617 {
618         int err;
619         struct nl_msg *msg;
620         struct nlmsghdr nlh = {
621                 .nlmsg_len = nlmsg_msg_size(0),
622                 .nlmsg_type = type,
623                 .nlmsg_flags = flags,
624         };
625
626         msg = nlmsg_build(&nlh);
627         if (!msg)
628                 return nl_errno(ENOMEM);
629
630         if (buf && size)
631                 nlmsg_append(msg, buf, size, 1);
632
633         err = nl_send_auto_complete(handle, msg);
634         nlmsg_free(msg);
635
636         return err;
637 }
638
639 /** @} */
640
641 /**
642  * @name Receive
643  * @{
644  */
645
646 /**
647  * Receive netlink message from netlink socket.
648  * @arg handle          Netlink handle.
649  * @arg nla             Destination pointer for peer's netlink address.
650  * @arg buf             Destination pointer for message content.
651  * @arg creds           Destination pointer for credentials.
652  *
653  * Receives a netlink message, allocates a buffer in \c *buf and
654  * stores the message content. The peer's netlink address is stored
655  * in \c *nla. The caller is responsible for freeing the buffer allocated
656  * in \c *buf if a positive value is returned.  Interruped system calls
657  * are handled by repeating the read. The input buffer size is determined
658  * by peeking before the actual read is done.
659  *
660  * A non-blocking sockets causes the function to return immediately if
661  * no data is available.
662  *
663  * @return Number of octets read, 0 on EOF or a negative error code.
664  */
665 int nl_recv(struct nl_handle *handle, struct sockaddr_nl *nla,
666             unsigned char **buf, struct ucred **creds)
667 {
668         int n;
669         int flags = MSG_PEEK;
670
671         struct iovec iov = {
672                 .iov_len = 4096,
673         };
674
675         struct msghdr msg = {
676                 .msg_name = (void *) nla,
677                 .msg_namelen = sizeof(sizeof(struct sockaddr_nl)),
678                 .msg_iov = &iov,
679                 .msg_iovlen = 1,
680                 .msg_control = NULL,
681                 .msg_controllen = 0,
682                 .msg_flags = 0,
683         };
684         struct cmsghdr *cmsg;
685
686         iov.iov_base = *buf = calloc(1, iov.iov_len);
687
688         if (handle->h_flags & NL_SOCK_PASSCRED) {
689                 msg.msg_controllen = CMSG_SPACE(sizeof(struct ucred));
690                 msg.msg_control = calloc(1, msg.msg_controllen);
691         }
692 retry:
693
694         if ((n = recvmsg(handle->h_fd, &msg, flags)) <= 0) {
695                 if (!n)
696                         goto abort;
697                 else if (n < 0) {
698                         if (errno == EINTR)
699                                 goto retry;
700                         else if (errno == EAGAIN)
701                                 goto abort;
702                         else {
703                                 free(msg.msg_control);
704                                 free(*buf);
705                                 return nl_error(errno, "recvmsg failed");
706                         }
707                 }
708         }
709         
710         if (iov.iov_len < n) {
711                 /* Provided buffer is not long enough, enlarge it
712                  * and try again. */
713                 iov.iov_len *= 2;
714                 iov.iov_base = *buf = realloc(*buf, iov.iov_len);
715                 goto retry;
716         } else if (msg.msg_flags & MSG_CTRUNC) {
717                 msg.msg_controllen *= 2;
718                 msg.msg_control = realloc(msg.msg_control, msg.msg_controllen);
719                 goto retry;
720         } else if (flags != 0) {
721                 /* Buffer is big enough, do the actual reading */
722                 flags = 0;
723                 goto retry;
724         }
725
726         if (msg.msg_namelen != sizeof(struct sockaddr_nl)) {
727                 free(msg.msg_control);
728                 free(*buf);
729                 return nl_error(EADDRNOTAVAIL, "socket address size mismatch");
730         }
731
732         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
733                 if (cmsg->cmsg_level == SOL_SOCKET &&
734                     cmsg->cmsg_type == SCM_CREDENTIALS) {
735                         *creds = calloc(1, sizeof(struct ucred));
736                         memcpy(*creds, CMSG_DATA(cmsg), sizeof(struct ucred));
737                         break;
738                 }
739         }
740
741         free(msg.msg_control);
742         return n;
743
744 abort:
745         free(msg.msg_control);
746         free(*buf);
747         return 0;
748 }
749
750
751 /**
752  * Receive a set of messages from a netlink socket.
753  * @arg handle          netlink handle
754  * @arg cb              set of callbacks to control the behaviour.
755  *
756  * Repeatedly calls nl_recv() and parses the messages as netlink
757  * messages. Stops reading if one of the callbacks returns
758  * NL_EXIT or nl_recv returns either 0 or a negative error code.
759  *
760  * A non-blocking sockets causes the function to return immediately if
761  * no data is available.
762  *
763  * @return 0 on success or a negative error code from nl_recv().
764  */
765 int nl_recvmsgs(struct nl_handle *handle, struct nl_cb *cb)
766 {
767         int n, err = 0;
768         unsigned char *buf = NULL;
769         struct nlmsghdr *hdr;
770         struct sockaddr_nl nla = {0};
771         struct nl_msg *msg = NULL;
772         struct ucred *creds = NULL;
773
774 continue_reading:
775         if (cb->cb_recv_ow)
776                 n = cb->cb_recv_ow(handle, &nla, &buf, &creds);
777         else
778                 n = nl_recv(handle, &nla, &buf, &creds);
779
780         if (n <= 0)
781                 return n;
782
783         NL_DBG(3, "recvmsgs(%p): Read %d bytes\n", handle, n);
784
785         hdr = (struct nlmsghdr *) buf;
786         while (nlmsg_ok(hdr, n)) {
787                 NL_DBG(3, "recgmsgs(%p): Processing valid message...\n",
788                        handle);
789
790                 nlmsg_free(msg);
791                 msg = nlmsg_convert(hdr);
792                 if (!msg) {
793                         err = nl_errno(ENOMEM);
794                         goto out;
795                 }
796
797                 nlmsg_set_proto(msg, handle->h_proto);
798                 nlmsg_set_src(msg, &nla);
799                 if (creds)
800                         nlmsg_set_creds(msg, creds);
801
802                 /* Raw callback is the first, it gives the most control
803                  * to the user and he can do his very own parsing. */
804                 if (cb->cb_set[NL_CB_MSG_IN]) {
805                         err = nl_cb_call(cb, NL_CB_MSG_IN, msg);
806                         if (err == NL_SKIP)
807                                 goto skip;
808                         else if (err == NL_EXIT || err < 0)
809                                 goto out;
810                 }
811
812                 /* Sequence number checking. The check may be done by
813                  * the user, otherwise a very simple check is applied
814                  * enforcing strict ordering */
815                 if (cb->cb_set[NL_CB_SEQ_CHECK]) {
816                         err = nl_cb_call(cb, NL_CB_SEQ_CHECK, msg);
817                         if (err == NL_SKIP)
818                                 goto skip;
819                         else if (err == NL_EXIT || err < 0)
820                                 goto out;
821                 } else if (hdr->nlmsg_seq != handle->h_seq_expect) {
822                         if (cb->cb_set[NL_CB_INVALID]) {
823                                 err = nl_cb_call(cb, NL_CB_INVALID, msg);
824                                 if (err == NL_SKIP)
825                                         goto skip;
826                                 else if (err == NL_EXIT || err < 0)
827                                         goto out;
828                         } else
829                                 goto out;
830                 }
831
832                 if (hdr->nlmsg_type == NLMSG_DONE ||
833                     hdr->nlmsg_type == NLMSG_ERROR ||
834                     hdr->nlmsg_type == NLMSG_NOOP ||
835                     hdr->nlmsg_type == NLMSG_OVERRUN) {
836                         /* We can't check for !NLM_F_MULTI since some netlink
837                          * users in the kernel are broken. */
838                         handle->h_seq_expect++;
839                         NL_DBG(3, "recvmsgs(%p): Increased expected " \
840                                "sequence number to %d\n",
841                                handle, handle->h_seq_expect);
842                 }
843         
844                 /* Other side wishes to see an ack for this message */
845                 if (hdr->nlmsg_flags & NLM_F_ACK) {
846                         if (cb->cb_set[NL_CB_SEND_ACK]) {
847                                 err = nl_cb_call(cb, NL_CB_SEND_ACK, msg);
848                                 if (err == NL_SKIP)
849                                         goto skip;
850                                 else if (err == NL_EXIT || err < 0)
851                                         goto out;
852                         } else {
853                                 /* FIXME: implement */
854                         }
855                 }
856
857                 /* messages terminates a multpart message, this is
858                  * usually the end of a message and therefore we slip
859                  * out of the loop by default. the user may overrule
860                  * this action by skipping this packet. */
861                 if (hdr->nlmsg_type == NLMSG_DONE) {
862                         if (cb->cb_set[NL_CB_FINISH]) {
863                                 err = nl_cb_call(cb, NL_CB_FINISH, msg);
864                                 if (err == NL_SKIP)
865                                         goto skip;
866                                 else if (err == NL_EXIT || err < 0)
867                                         goto out;
868                         }
869                         err = 0;
870                         goto out;
871                 }
872
873                 /* Message to be ignored, the default action is to
874                  * skip this message if no callback is specified. The
875                  * user may overrule this action by returning
876                  * NL_PROCEED. */
877                 else if (hdr->nlmsg_type == NLMSG_NOOP) {
878                         if (cb->cb_set[NL_CB_SKIPPED]) {
879                                 err = nl_cb_call(cb, NL_CB_SKIPPED, msg);
880                                 if (err == NL_SKIP)
881                                         goto skip;
882                                 else if (err == NL_EXIT || err < 0)
883                                         goto out;
884                         } else
885                                 goto skip;
886                 }
887
888                 /* Data got lost, report back to user. The default action is to
889                  * quit parsing. The user may overrule this action by retuning
890                  * NL_SKIP or NL_PROCEED (dangerous) */
891                 else if (hdr->nlmsg_type == NLMSG_OVERRUN) {
892                         if (cb->cb_set[NL_CB_OVERRUN]) {
893                                 err = nl_cb_call(cb, NL_CB_OVERRUN, msg);
894                                 if (err == NL_SKIP)
895                                         goto skip;
896                                 else if (err == NL_EXIT || err < 0)
897                                         goto out;
898                         } else
899                                 goto out;
900                 }
901
902                 /* Message carries a nlmsgerr */
903                 else if (hdr->nlmsg_type == NLMSG_ERROR) {
904                         struct nlmsgerr *e = nlmsg_data(hdr);
905
906                         if (hdr->nlmsg_len < nlmsg_msg_size(sizeof(*e))) {
907                                 /* Truncated error message, the default action
908                                  * is to stop parsing. The user may overrule
909                                  * this action by returning NL_SKIP or
910                                  * NL_PROCEED (dangerous) */
911                                 if (cb->cb_set[NL_CB_INVALID]) {
912                                         err = nl_cb_call(cb, NL_CB_INVALID,
913                                                          msg);
914                                         if (err == NL_SKIP)
915                                                 goto skip;
916                                         else if (err == NL_EXIT || err < 0)
917                                                 goto out;
918                                 } else
919                                         goto out;
920                         } else if (e->error) {
921                                 /* Error message reported back from kernel. */
922                                 if (cb->cb_err) {
923                                         err = cb->cb_err(&nla, e,
924                                                            cb->cb_err_arg);
925                                         if (err == NL_SKIP)
926                                                 goto skip;
927                                         else if (err == NL_EXIT || err < 0) {
928                                                 nl_error(-e->error,
929                                                          "Netlink Error");
930                                                 err = e->error;
931                                                 goto out;
932                                         }
933                                 } else {
934                                         nl_error(-e->error, "Netlink Error");
935                                         err = e->error;
936                                         goto out;
937                                 }
938                         } else if (cb->cb_set[NL_CB_ACK]) {
939                                 /* ACK */
940                                 err = nl_cb_call(cb, NL_CB_ACK, msg);
941                                 if (err == NL_SKIP)
942                                         goto skip;
943                                 else if (err == NL_EXIT || err < 0)
944                                         goto out;
945                         }
946                 } else {
947                         /* Valid message (not checking for MULTIPART bit to
948                          * get along with broken kernels. NL_SKIP has no
949                          * effect on this.  */
950                         if (cb->cb_set[NL_CB_VALID]) {
951                                 err = nl_cb_call(cb, NL_CB_VALID, msg);
952                                 if (err == NL_SKIP)
953                                         goto skip;
954                                 else if (err == NL_EXIT || err < 0)
955                                         goto out;
956                         }
957                 }
958 skip:
959                 hdr = nlmsg_next(hdr, &n);
960         }
961         
962         nlmsg_free(msg);
963         free(buf);
964         free(creds);
965         buf = NULL;
966         msg = NULL;
967         creds = NULL;
968
969         /* Multipart message not yet complete, continue reading */
970         goto continue_reading;
971
972 out:
973         nlmsg_free(msg);
974         free(buf);
975         free(creds);
976
977         return err;
978 }
979
980 /**
981  * Receive a set of message from a netlink socket using handlers in nl_handle.
982  * @arg handle          netlink handle
983  *
984  * Calls nl_recvmsgs() with the handlers configured in the netlink handle.
985  */
986 int nl_recvmsgs_def(struct nl_handle *handle)
987 {
988         if (handle->h_cb->cb_recvmsgs_ow)
989                 return handle->h_cb->cb_recvmsgs_ow(handle, handle->h_cb);
990         else
991                 return nl_recvmsgs(handle, handle->h_cb);
992 }
993
994 static int ack_wait_handler(struct nl_msg *msg, void *arg)
995 {
996         return NL_EXIT;
997 }
998
999 /**
1000  * Wait for ACK.
1001  * @arg handle          netlink handle
1002  * @pre The netlink socket must be in blocking state.
1003  *
1004  * Waits until an ACK is received for the latest not yet acknowledged
1005  * netlink message.
1006  */
1007 int nl_wait_for_ack(struct nl_handle *handle)
1008 {
1009         int err;
1010         struct nl_cb *cb = nl_cb_clone(nl_handle_get_cb(handle));
1011
1012         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_wait_handler, NULL);
1013
1014         err = nl_recvmsgs(handle, cb);
1015         nl_cb_destroy(cb);
1016
1017         return err;
1018 }
1019
1020 /** @} */
1021
1022 /**
1023  * @name Netlink Family Translations
1024  * @{
1025  */
1026
1027 static struct trans_tbl nlfamilies[] = {
1028         __ADD(NETLINK_ROUTE,route)
1029         __ADD(NETLINK_W1,w1)
1030         __ADD(NETLINK_USERSOCK,usersock)
1031         __ADD(NETLINK_FIREWALL,firewall)
1032         __ADD(NETLINK_INET_DIAG,inetdiag)
1033         __ADD(NETLINK_NFLOG,nflog)
1034         __ADD(NETLINK_XFRM,xfrm)
1035         __ADD(NETLINK_SELINUX,selinux)
1036         __ADD(NETLINK_ISCSI,iscsi)
1037         __ADD(NETLINK_AUDIT,audit)
1038         __ADD(NETLINK_FIB_LOOKUP,fib_lookup)
1039         __ADD(NETLINK_CONNECTOR,connector)
1040         __ADD(NETLINK_NETFILTER,netfilter)
1041         __ADD(NETLINK_IP6_FW,ip6_fw)
1042         __ADD(NETLINK_DNRTMSG,dnrtmsg)
1043         __ADD(NETLINK_KOBJECT_UEVENT,kobject_uevent)
1044         __ADD(NETLINK_GENERIC,generic)
1045 };
1046
1047 /**
1048  * Convert netlink family to character string.
1049  * @arg family          Netlink family.
1050  * @arg buf             Destination buffer.
1051  * @arg size            Size of destination buffer.
1052  *
1053  * Converts a netlink family to a character string and stores it in
1054  * the specified destination buffer.
1055  *
1056  * @return The destination buffer or the family encoded in hexidecimal
1057  *         form if no match was found.
1058  */
1059 char * nl_nlfamily2str(int family, char *buf, size_t size)
1060 {
1061         return __type2str(family, buf, size, nlfamilies,
1062                           ARRAY_SIZE(nlfamilies));
1063 }
1064
1065 /**
1066  * Convert character string to netlink family.
1067  * @arg name            Name of netlink family.
1068  *
1069  * Converts the provided character string specifying a netlink
1070  * family to the corresponding numeric value.
1071  *
1072  * @return Numeric netlink family or a negative value if no match was found.
1073  */
1074 int nl_str2nlfamily(const char *name)
1075 {
1076         return __str2type(name, nlfamilies, ARRAY_SIZE(nlfamilies));
1077 }
1078
1079 /** @} */
1080 /** @} */