socket.c revision 69bc179b203c17380ba0b4fda7cf99af65cc5324
1/*
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;
37	struct timeval tv;
38	struct nl_cb *cb;
39
40	sk = (struct nl_sock *) malloc(sizeof(struct nl_sock));
41	if (!sk)
42		goto fail;
43	memset(sk, 0, sizeof(*sk));
44
45	/* Get current time */
46
47	if (gettimeofday(&tv, NULL))
48		return NULL;
49	else
50		sk->s_seq_next = (int) tv.tv_sec;
51
52	/* Create local socket */
53	sk->s_local.nl_family = AF_NETLINK;
54	sk->s_local.nl_pid = 0; /* Kernel fills in pid */
55	sk->s_local.nl_groups = 0; /* No groups */
56
57	/* Create peer socket */
58	sk->s_peer.nl_family = AF_NETLINK;
59	sk->s_peer.nl_pid = 0; /* Kernel */
60	sk->s_peer.nl_groups = 0; /* No groups */
61
62	cb = (struct nl_cb *) malloc(sizeof(struct nl_cb));
63	if (!cb)
64		goto cb_fail;
65	memset(cb, 0, sizeof(*cb));
66	sk->s_cb = nl_cb_alloc(NL_CB_DEFAULT);
67
68
69	return sk;
70cb_fail:
71	free(sk);
72fail:
73	return NULL;
74}
75
76/* Allocate new socket with custom callbacks. */
77struct nl_sock *nl_socket_alloc_cb(struct nl_cb *cb)
78{
79	struct nl_sock *sk = nl_socket_alloc();
80	if (!sk)
81		return NULL;
82
83	sk->s_cb = cb;
84	nl_cb_get(cb);
85
86	return sk;
87
88}
89
90/* Free a netlink socket. */
91void nl_socket_free(struct nl_sock *sk)
92{
93	nl_cb_put(sk->s_cb);
94	close(sk->s_fd);
95	free(sk);
96}
97
98/* Sets socket buffer size of netlink socket */
99int nl_socket_set_buffer_size(struct nl_sock *sk, int rxbuf, int txbuf)
100{
101	if (setsockopt(sk->s_fd, SOL_SOCKET, SO_SNDBUF, \
102			&rxbuf, (socklen_t) sizeof(rxbuf)))
103		goto error;
104
105	if (setsockopt(sk->s_fd, SOL_SOCKET, SO_RCVBUF, \
106			&txbuf, (socklen_t) sizeof(txbuf)))
107		goto error;
108
109	return 0;
110error:
111	return -errno;
112
113}
114
115int nl_socket_get_fd(struct nl_sock *sk)
116{
117	return sk->s_fd;
118}
119
120
121