blob: 1a2255e0e08b9c41ae96701a5ca425668dedb5cb [file] [log] [blame]
Frank Makered6b39c2011-05-23 21:14:58 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* NOTICE: This is a clean room re-implementation of libnl */
18
19#include <errno.h>
20#include <unistd.h>
21#include <malloc.h>
22#include <sys/time.h>
23#include <sys/socket.h>
24#include "netlink-types.h"
25
26/* Join group */
27int nl_socket_add_membership(struct nl_sock *sk, int group)
28{
29 return setsockopt(sk->s_fd, SOL_NETLINK,
30 NETLINK_ADD_MEMBERSHIP, &group, sizeof(group));
31}
32
33/* Allocate new netlink socket. */
34struct nl_sock *nl_socket_alloc(void)
35{
36 struct nl_sock *sk = (struct nl_sock *) malloc(sizeof(struct nl_sock));
37 struct timeval tv;
38 struct nl_cb *cb;
39
40 if (!sk)
41 goto fail;
42
43 /* Get current time */
44
45 if (gettimeofday(&tv, NULL))
46 return NULL;
47 else
48 sk->s_seq_next = (int) tv.tv_sec;
49
50 /* Create local socket */
51 sk->s_local.nl_family = AF_NETLINK;
52 sk->s_local.nl_pid = getpid();
53 sk->s_local.nl_groups = 0; /* No groups */
54
55 /* Create peer socket */
56 sk->s_peer.nl_family = AF_NETLINK;
57 sk->s_peer.nl_pid = 0; /* Kernel */
58 sk->s_peer.nl_groups = 0; /* No groups */
59
60 cb = (struct nl_cb *) malloc(sizeof(struct nl_cb));
61 if (!cb)
62 goto cb_fail;
63 memset(cb, 0, sizeof(*cb));
64 sk->s_cb = nl_cb_alloc(NL_CB_DEFAULT);
65
66
67 return sk;
68cb_fail:
69 free(sk);
70fail:
71 return NULL;
72}
73
74/* Allocate new socket with custom callbacks. */
75struct nl_sock *nl_socket_alloc_cb(struct nl_cb *cb)
76{
77 struct nl_sock *sk = nl_socket_alloc();
78 if (!sk)
79 goto fail;
80
81 sk->s_cb = cb;
82 nl_cb_get(cb);
83
84 return sk;
85fail:
86 return NULL;
87}
88
89/* Free a netlink socket. */
90void nl_socket_free(struct nl_sock *sk)
91{
92 nl_cb_put(sk->s_cb);
93 free(sk);
94}
95
96/* Sets socket buffer size of netlink socket */
97int nl_socket_set_buffer_size(struct nl_sock *sk, int rxbuf, int txbuf)
98{
99 if (setsockopt(sk->s_fd, SOL_SOCKET, SO_SNDBUF, \
100 &rxbuf, (socklen_t) sizeof(rxbuf)))
101 goto error;
102
103 if (setsockopt(sk->s_fd, SOL_SOCKET, SO_RCVBUF, \
104 &txbuf, (socklen_t) sizeof(txbuf)))
105 goto error;
106
107 return 0;
108error:
109 return -errno;
110
111}
112
113int nl_socket_get_fd(struct nl_sock *sk)
114{
115 return sk->s_fd;
116}
117
118