1/*
2 * Copyright (C) 2008 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#include <errno.h>
17
18#include <sys/types.h>
19#include <sys/socket.h>
20#include <linux/netlink.h>
21#include <string.h>
22
23#define LOG_TAG "NetlinkListener"
24#include <cutils/log.h>
25
26#include <sysutils/NetlinkListener.h>
27#include <sysutils/NetlinkEvent.h>
28
29NetlinkListener::NetlinkListener(int socket) :
30                            SocketListener(socket, false) {
31}
32
33bool NetlinkListener::onDataAvailable(SocketClient *cli)
34{
35    int socket = cli->getSocket();
36    ssize_t count;
37    char cred_msg[CMSG_SPACE(sizeof(struct ucred))];
38    struct sockaddr_nl snl;
39    struct iovec iov = {mBuffer, sizeof(mBuffer)};
40    struct msghdr hdr = {&snl, sizeof(snl), &iov, 1, cred_msg, sizeof(cred_msg), 0};
41
42    if ((count = recvmsg(socket, &hdr, 0)) < 0) {
43        SLOGE("recvmsg failed (%s)", strerror(errno));
44        return false;
45    }
46
47    if ((snl.nl_groups != 1) || (snl.nl_pid != 0)) {
48        SLOGE("ignoring non-kernel netlink multicast message");
49        return false;
50    }
51
52    struct cmsghdr * cmsg = CMSG_FIRSTHDR(&hdr);
53
54    if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
55        SLOGE("ignoring message with no sender credentials");
56        return false;
57    }
58
59    struct ucred * cred = (struct ucred *)CMSG_DATA(cmsg);
60    if (cred->uid != 0) {
61        SLOGE("ignoring message from non-root UID %d", cred->uid);
62        return false;
63    }
64
65    NetlinkEvent *evt = new NetlinkEvent();
66    if (!evt->decode(mBuffer, count)) {
67        SLOGE("Error decoding NetlinkEvent");
68        goto out;
69    }
70
71    onEvent(evt);
72out:
73    delete evt;
74    return true;
75}
76