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
17#include <stdio.h>
18#include <stdlib.h>
19#include <errno.h>
20
21#define LOG_TAG "Netd"
22
23#include <cutils/log.h>
24
25#include <sysutils/NetlinkEvent.h>
26#include "NetlinkHandler.h"
27#include "NetlinkManager.h"
28#include "ResponseCode.h"
29
30NetlinkHandler::NetlinkHandler(NetlinkManager *nm, int listenerSocket) :
31                NetlinkListener(listenerSocket) {
32    mNm = nm;
33}
34
35NetlinkHandler::~NetlinkHandler() {
36}
37
38int NetlinkHandler::start() {
39    return this->startListener();
40}
41
42int NetlinkHandler::stop() {
43    return this->stopListener();
44}
45
46void NetlinkHandler::onEvent(NetlinkEvent *evt) {
47    const char *subsys = evt->getSubsystem();
48    if (!subsys) {
49        LOGW("No subsystem found in netlink event");
50        return;
51    }
52    if (!strcmp(subsys, "net")) {
53        int action = evt->getAction();
54        if (action == evt->NlActionAdd) {
55            const char *iface = evt->findParam("INTERFACE");
56            notifyInterfaceAdded(iface);
57        } else if (action == evt->NlActionRemove) {
58            const char *iface = evt->findParam("INTERFACE");
59            notifyInterfaceRemoved(iface);
60        } else if (action == evt->NlActionChange) {
61            evt->dump();
62            const char *iface = evt->findParam("INTERFACE");
63            notifyInterfaceChanged("nana", true);
64        }
65    }
66}
67
68void NetlinkHandler::notifyInterfaceAdded(const char *name) {
69    char msg[255];
70    snprintf(msg, sizeof(msg), "Iface added %s", name);
71
72    mNm->getBroadcaster()->sendBroadcast(ResponseCode::InterfaceChange,
73            msg, false);
74}
75
76void NetlinkHandler::notifyInterfaceRemoved(const char *name) {
77    char msg[255];
78    snprintf(msg, sizeof(msg), "Iface removed %s", name);
79
80    mNm->getBroadcaster()->sendBroadcast(ResponseCode::InterfaceChange,
81            msg, false);
82}
83
84void NetlinkHandler::notifyInterfaceChanged(const char *name, bool isUp) {
85    char msg[255];
86    snprintf(msg, sizeof(msg), "Iface is %s %s", (isUp ? "up" : "down"), name);
87
88    mNm->getBroadcaster()->sendBroadcast(ResponseCode::InterfaceChange,
89            msg, false);
90}
91