Nat464Xlat.java revision e21a26b3ba78b0238f4ed4a09b43319a2320fbaa
1/*
2 * Copyright (C) 2012 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
17package com.android.server.connectivity;
18
19import static android.net.ConnectivityManager.TYPE_MOBILE;
20import static android.net.ConnectivityManager.TYPE_WIFI;
21
22import java.net.Inet4Address;
23
24import android.content.Context;
25import android.net.IConnectivityManager;
26import android.net.InterfaceConfiguration;
27import android.net.LinkAddress;
28import android.net.LinkProperties;
29import android.net.NetworkAgent;
30import android.net.NetworkUtils;
31import android.net.RouteInfo;
32import android.os.Handler;
33import android.os.Message;
34import android.os.Messenger;
35import android.os.INetworkManagementService;
36import android.os.RemoteException;
37import android.util.Slog;
38
39import com.android.server.net.BaseNetworkObserver;
40
41/**
42 * @hide
43 *
44 * Class to manage a 464xlat CLAT daemon.
45 */
46public class Nat464Xlat extends BaseNetworkObserver {
47    private static final String TAG = "Nat464Xlat";
48
49    // This must match the interface prefix in clatd.c.
50    private static final String CLAT_PREFIX = "v4-";
51
52    private final INetworkManagementService mNMService;
53
54    // ConnectivityService Handler for LinkProperties updates.
55    private final Handler mHandler;
56
57    // The network we're running on, and its type.
58    private final NetworkAgentInfo mNetwork;
59
60    // Internal state variables.
61    //
62    // The possible states are:
63    //  - Idle: start() not called. Everything is null.
64    //  - Starting: start() called. Interfaces are non-null. isStarted() returns true.
65    //    mIsRunning is false.
66    //  - Running: start() called, and interfaceAdded() told us that mIface is up. Clat IP address
67    //    is non-null. mIsRunning is true.
68    //
69    // Once mIface is non-null and isStarted() is true, methods called by ConnectivityService on
70    // its handler thread must not modify any internal state variables; they are only updated by the
71    // interface observers, called on the notification threads.
72    private String mBaseIface;
73    private String mIface;
74    private boolean mIsRunning;
75
76    public Nat464Xlat(
77            Context context, INetworkManagementService nmService,
78            Handler handler, NetworkAgentInfo nai) {
79        mNMService = nmService;
80        mHandler = handler;
81        mNetwork = nai;
82    }
83
84    /**
85     * Determines whether a network requires clat.
86     * @param network the NetworkAgentInfo corresponding to the network.
87     * @return true if the network requires clat, false otherwise.
88     */
89    public static boolean requiresClat(NetworkAgentInfo nai) {
90        final int netType = nai.networkInfo.getType();
91        final boolean connected = nai.networkInfo.isConnected();
92        final boolean hasIPv4Address =
93                (nai.linkProperties != null) ? nai.linkProperties.hasIPv4Address() : false;
94        // Only support clat on mobile for now.
95        return netType == TYPE_MOBILE && connected && !hasIPv4Address;
96    }
97
98    /**
99     * Determines whether clatd is started. Always true, except a) if start has not yet been called,
100     * or b) if our interface was removed.
101     */
102    public boolean isStarted() {
103        return mIface != null;
104    }
105
106    /**
107     * Clears internal state. Must not be called by ConnectivityService.
108     */
109    private void clear() {
110        mIface = null;
111        mBaseIface = null;
112        mIsRunning = false;
113    }
114
115    /**
116     * Starts the clat daemon. Called by ConnectivityService on the handler thread.
117     */
118    public void start() {
119        if (isStarted()) {
120            Slog.e(TAG, "startClat: already started");
121            return;
122        }
123
124        if (mNetwork.linkProperties == null) {
125            Slog.e(TAG, "startClat: Can't start clat with null LinkProperties");
126            return;
127        }
128
129        try {
130            mNMService.registerObserver(this);
131        } catch(RemoteException e) {
132            Slog.e(TAG, "startClat: Can't register interface observer for clat on " + mNetwork);
133            return;
134        }
135
136        mBaseIface = mNetwork.linkProperties.getInterfaceName();
137        if (mBaseIface == null) {
138            Slog.e(TAG, "startClat: Can't start clat on null interface");
139            return;
140        }
141        mIface = CLAT_PREFIX + mBaseIface;
142        // From now on, isStarted() will return true.
143
144        Slog.i(TAG, "Starting clatd on " + mBaseIface);
145        try {
146            mNMService.startClatd(mBaseIface);
147        } catch(RemoteException|IllegalStateException e) {
148            Slog.e(TAG, "Error starting clatd: " + e);
149        }
150    }
151
152    /**
153     * Stops the clat daemon. Called by ConnectivityService on the handler thread.
154     */
155    public void stop() {
156        if (isStarted()) {
157            Slog.i(TAG, "Stopping clatd");
158            try {
159                mNMService.stopClatd(mBaseIface);
160            } catch(RemoteException|IllegalStateException e) {
161                Slog.e(TAG, "Error stopping clatd: " + e);
162            }
163            // When clatd stops and its interface is deleted, interfaceRemoved() will notify
164            // ConnectivityService and call clear().
165        } else {
166            Slog.e(TAG, "clatd: already stopped");
167        }
168    }
169
170    private void updateConnectivityService(LinkProperties lp) {
171        Message msg = mHandler.obtainMessage(NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED, lp);
172        msg.replyTo = mNetwork.messenger;
173        Slog.i(TAG, "sending message to ConnectivityService: " + msg);
174        msg.sendToTarget();
175    }
176
177    /**
178     * Copies the stacked clat link in oldLp, if any, to the LinkProperties in mNetwork.
179     * This is necessary because the LinkProperties in mNetwork come from the transport layer, which
180     * has no idea that 464xlat is running on top of it.
181     */
182    public void fixupLinkProperties(LinkProperties oldLp) {
183        if (mNetwork.clatd != null &&
184                mIsRunning &&
185                mNetwork.linkProperties != null &&
186                !mNetwork.linkProperties.getAllInterfaceNames().contains(mIface)) {
187            Slog.d(TAG, "clatd running, updating NAI for " + mIface);
188            for (LinkProperties stacked: oldLp.getStackedLinks()) {
189                if (mIface.equals(stacked.getInterfaceName())) {
190                    mNetwork.linkProperties.addStackedLink(stacked);
191                    break;
192                }
193            }
194        }
195    }
196
197    private LinkProperties makeLinkProperties(LinkAddress clatAddress) {
198        LinkProperties stacked = new LinkProperties();
199        stacked.setInterfaceName(mIface);
200
201        // Although the clat interface is a point-to-point tunnel, we don't
202        // point the route directly at the interface because some apps don't
203        // understand routes without gateways (see, e.g., http://b/9597256
204        // http://b/9597516). Instead, set the next hop of the route to the
205        // clat IPv4 address itself (for those apps, it doesn't matter what
206        // the IP of the gateway is, only that there is one).
207        RouteInfo ipv4Default = new RouteInfo(
208                new LinkAddress(Inet4Address.ANY, 0),
209                clatAddress.getAddress(), mIface);
210        stacked.addRoute(ipv4Default);
211        stacked.addLinkAddress(clatAddress);
212        return stacked;
213    }
214
215    private LinkAddress getLinkAddress(String iface) {
216        try {
217            InterfaceConfiguration config = mNMService.getInterfaceConfig(iface);
218            return config.getLinkAddress();
219        } catch(RemoteException|IllegalStateException e) {
220            Slog.e(TAG, "Error getting link properties: " + e);
221            return null;
222        }
223    }
224
225    private void maybeSetIpv6NdOffload(String iface, boolean on) {
226        if (mNetwork.networkInfo.getType() != TYPE_WIFI) {
227            return;
228        }
229        try {
230            Slog.d(TAG, (on ? "En" : "Dis") + "abling ND offload on " + iface);
231            mNMService.setInterfaceIpv6NdOffload(iface, on);
232        } catch(RemoteException|IllegalStateException e) {
233            Slog.w(TAG, "Changing IPv6 ND offload on " + iface + "failed: " + e);
234        }
235    }
236
237    @Override
238    public void interfaceAdded(String iface) {
239        // Called by the InterfaceObserver on its own thread, so can race with stop().
240        if (isStarted() && mIface.equals(iface)) {
241            Slog.i(TAG, "interface " + iface + " added, mIsRunning " + mIsRunning + "->true");
242
243            if (!mIsRunning) {
244                LinkAddress clatAddress = getLinkAddress(iface);
245                if (clatAddress == null) {
246                    return;
247                }
248                mIsRunning = true;
249                maybeSetIpv6NdOffload(mBaseIface, false);
250                LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
251                lp.addStackedLink(makeLinkProperties(clatAddress));
252                Slog.i(TAG, "Adding stacked link " + mIface + " on top of " + mBaseIface);
253                updateConnectivityService(lp);
254            }
255        }
256    }
257
258    @Override
259    public void interfaceRemoved(String iface) {
260        if (isStarted() && mIface.equals(iface)) {
261            Slog.i(TAG, "interface " + iface + " removed, mIsRunning " + mIsRunning + "->false");
262
263            if (mIsRunning) {
264                // The interface going away likely means clatd has crashed. Ask netd to stop it,
265                // because otherwise when we try to start it again on the same base interface netd
266                // will complain that it's already started.
267                //
268                // Note that this method can be called by the interface observer at the same time
269                // that ConnectivityService calls stop(). In this case, the second call to
270                // stopClatd() will just throw IllegalStateException, which we'll ignore.
271                try {
272                    mNMService.unregisterObserver(this);
273                    mNMService.stopClatd(mBaseIface);
274                } catch (RemoteException|IllegalStateException e) {
275                    // Well, we tried.
276                }
277                maybeSetIpv6NdOffload(mBaseIface, true);
278                LinkProperties lp = new LinkProperties(mNetwork.linkProperties);
279                lp.removeStackedLink(mIface);
280                clear();
281                updateConnectivityService(lp);
282            }
283        }
284    }
285}
286