VpnService.java revision b2053114562830369a9d060e79f0c9eff4be27e7
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
17package android.net;
18
19import static android.system.OsConstants.AF_INET;
20import static android.system.OsConstants.AF_INET6;
21
22import android.annotation.SystemApi;
23import android.app.Activity;
24import android.app.PendingIntent;
25import android.app.Service;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.IPackageManager;
29import android.content.pm.PackageManager;
30import android.net.Network;
31import android.net.NetworkUtils;
32import android.os.Binder;
33import android.os.IBinder;
34import android.os.Parcel;
35import android.os.ParcelFileDescriptor;
36import android.os.RemoteException;
37import android.os.ServiceManager;
38import android.os.UserHandle;
39
40import com.android.internal.net.VpnConfig;
41
42import java.net.DatagramSocket;
43import java.net.Inet4Address;
44import java.net.Inet6Address;
45import java.net.InetAddress;
46import java.net.Socket;
47import java.util.ArrayList;
48import java.util.List;
49
50/**
51 * VpnService is a base class for applications to extend and build their
52 * own VPN solutions. In general, it creates a virtual network interface,
53 * configures addresses and routing rules, and returns a file descriptor
54 * to the application. Each read from the descriptor retrieves an outgoing
55 * packet which was routed to the interface. Each write to the descriptor
56 * injects an incoming packet just like it was received from the interface.
57 * The interface is running on Internet Protocol (IP), so packets are
58 * always started with IP headers. The application then completes a VPN
59 * connection by processing and exchanging packets with the remote server
60 * over a tunnel.
61 *
62 * <p>Letting applications intercept packets raises huge security concerns.
63 * A VPN application can easily break the network. Besides, two of them may
64 * conflict with each other. The system takes several actions to address
65 * these issues. Here are some key points:
66 * <ul>
67 *   <li>User action is required the first time an application creates a VPN
68 *       connection.</li>
69 *   <li>There can be only one VPN connection running at the same time. The
70 *       existing interface is deactivated when a new one is created.</li>
71 *   <li>A system-managed notification is shown during the lifetime of a
72 *       VPN connection.</li>
73 *   <li>A system-managed dialog gives the information of the current VPN
74 *       connection. It also provides a button to disconnect.</li>
75 *   <li>The network is restored automatically when the file descriptor is
76 *       closed. It also covers the cases when a VPN application is crashed
77 *       or killed by the system.</li>
78 * </ul>
79 *
80 * <p>There are two primary methods in this class: {@link #prepare} and
81 * {@link Builder#establish}. The former deals with user action and stops
82 * the VPN connection created by another application. The latter creates
83 * a VPN interface using the parameters supplied to the {@link Builder}.
84 * An application must call {@link #prepare} to grant the right to use
85 * other methods in this class, and the right can be revoked at any time.
86 * Here are the general steps to create a VPN connection:
87 * <ol>
88 *   <li>When the user presses the button to connect, call {@link #prepare}
89 *       and launch the returned intent, if non-null.</li>
90 *   <li>When the application becomes prepared, start the service.</li>
91 *   <li>Create a tunnel to the remote server and negotiate the network
92 *       parameters for the VPN connection.</li>
93 *   <li>Supply those parameters to a {@link Builder} and create a VPN
94 *       interface by calling {@link Builder#establish}.</li>
95 *   <li>Process and exchange packets between the tunnel and the returned
96 *       file descriptor.</li>
97 *   <li>When {@link #onRevoke} is invoked, close the file descriptor and
98 *       shut down the tunnel gracefully.</li>
99 * </ol>
100 *
101 * <p>Services extended this class need to be declared with appropriate
102 * permission and intent filter. Their access must be secured by
103 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
104 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
105 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
106 * <pre>
107 * &lt;service android:name=".ExampleVpnService"
108 *         android:permission="android.permission.BIND_VPN_SERVICE"&gt;
109 *     &lt;intent-filter&gt;
110 *         &lt;action android:name="android.net.VpnService"/&gt;
111 *     &lt;/intent-filter&gt;
112 * &lt;/service&gt;</pre>
113 *
114 * @see Builder
115 */
116public class VpnService extends Service {
117
118    /**
119     * The action must be matched by the intent filter of this service. It also
120     * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
121     * permission so that other applications cannot abuse it.
122     */
123    public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
124
125    /**
126     * Use IConnectivityManager since those methods are hidden and not
127     * available in ConnectivityManager.
128     */
129    private static IConnectivityManager getService() {
130        return IConnectivityManager.Stub.asInterface(
131                ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
132    }
133
134    /**
135     * Prepare to establish a VPN connection. This method returns {@code null}
136     * if the VPN application is already prepared or if the user has previously
137     * consented to the VPN application. Otherwise, it returns an
138     * {@link Intent} to a system activity. The application should launch the
139     * activity using {@link Activity#startActivityForResult} to get itself
140     * prepared. The activity may pop up a dialog to require user action, and
141     * the result will come back via its {@link Activity#onActivityResult}.
142     * If the result is {@link Activity#RESULT_OK}, the application becomes
143     * prepared and is granted to use other methods in this class.
144     *
145     * <p>Only one application can be granted at the same time. The right
146     * is revoked when another application is granted. The application
147     * losing the right will be notified via its {@link #onRevoke}. Unless
148     * it becomes prepared again, subsequent calls to other methods in this
149     * class will fail.
150     *
151     * <p>The user may disable the VPN at any time while it is activated, in
152     * which case this method will return an intent the next time it is
153     * executed to obtain the user's consent again.
154     *
155     * @see #onRevoke
156     */
157    public static Intent prepare(Context context) {
158        try {
159            if (getService().prepareVpn(context.getPackageName(), null)) {
160                return null;
161            }
162        } catch (RemoteException e) {
163            // ignore
164        }
165        return VpnConfig.getIntentForConfirmation();
166    }
167
168    /**
169     * Version of {@link #prepare(Context)} which does not require user consent.
170     *
171     * <p>Requires {@link android.Manifest.permission#CONTROL_VPN} and should generally not be
172     * used. Only acceptable in situations where user consent has been obtained through other means.
173     *
174     * <p>Once this is run, future preparations may be done with the standard prepare method as this
175     * will authorize the package to prepare the VPN without consent in the future.
176     *
177     * @hide
178     */
179    @SystemApi
180    public static void prepareAndAuthorize(Context context) {
181        IConnectivityManager cm = getService();
182        String packageName = context.getPackageName();
183        try {
184            // Only prepare if we're not already prepared.
185            if (!cm.prepareVpn(packageName, null)) {
186                cm.prepareVpn(null, packageName);
187            }
188            cm.setVpnPackageAuthorization(true);
189        } catch (RemoteException e) {
190            // ignore
191        }
192    }
193
194    /**
195     * Protect a socket from VPN connections. After protecting, data sent
196     * through this socket will go directly to the underlying network,
197     * so its traffic will not be forwarded through the VPN.
198     * This method is useful if some connections need to be kept
199     * outside of VPN. For example, a VPN tunnel should protect itself if its
200     * destination is covered by VPN routes. Otherwise its outgoing packets
201     * will be sent back to the VPN interface and cause an infinite loop. This
202     * method will fail if the application is not prepared or is revoked.
203     *
204     * <p class="note">The socket is NOT closed by this method.
205     *
206     * @return {@code true} on success.
207     */
208    public boolean protect(int socket) {
209        return NetworkUtils.protectFromVpn(socket);
210    }
211
212    /**
213     * Convenience method to protect a {@link Socket} from VPN connections.
214     *
215     * @return {@code true} on success.
216     * @see #protect(int)
217     */
218    public boolean protect(Socket socket) {
219        return protect(socket.getFileDescriptor$().getInt$());
220    }
221
222    /**
223     * Convenience method to protect a {@link DatagramSocket} from VPN
224     * connections.
225     *
226     * @return {@code true} on success.
227     * @see #protect(int)
228     */
229    public boolean protect(DatagramSocket socket) {
230        return protect(socket.getFileDescriptor$().getInt$());
231    }
232
233    /**
234     * Adds a network address to the VPN interface.
235     *
236     * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
237     * address is already in use or cannot be assigned to the interface for any other reason.
238     *
239     * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
240     * be routed over the VPN. @see Builder#allowFamily
241     *
242     * @throws {@link IllegalArgumentException} if the address is invalid.
243     *
244     * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
245     * @param prefixLength The prefix length of the address.
246     *
247     * @return {@code true} on success.
248     * @see Builder#addAddress
249     *
250     * @hide
251     */
252    public boolean addAddress(InetAddress address, int prefixLength) {
253        check(address, prefixLength);
254        try {
255            return getService().addVpnAddress(address.getHostAddress(), prefixLength);
256        } catch (RemoteException e) {
257            throw new IllegalStateException(e);
258        }
259    }
260
261    /**
262     * Removes a network address from the VPN interface.
263     *
264     * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
265     * address is not assigned to the VPN interface, or if it is the only address assigned (thus
266     * cannot be removed), or if the address cannot be removed for any other reason.
267     *
268     * After removing an address, if there are no addresses, routes or DNS servers of a particular
269     * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
270     * family from being routed. In other words, once an address family has been allowed, it stays
271     * allowed for the rest of the VPN's session. @see Builder#allowFamily
272     *
273     * @throws {@link IllegalArgumentException} if the address is invalid.
274     *
275     * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
276     * @param prefixLength The prefix length of the address.
277     *
278     * @return {@code true} on success.
279     *
280     * @hide
281     */
282    public boolean removeAddress(InetAddress address, int prefixLength) {
283        check(address, prefixLength);
284        try {
285            return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
286        } catch (RemoteException e) {
287            throw new IllegalStateException(e);
288        }
289    }
290
291    /**
292     * Sets the underlying networks used by the VPN for its upstream connections.
293     *
294     * <p>Used by the system to know the actual networks that carry traffic for apps affected by
295     * this VPN in order to present this information to the user (e.g., via status bar icons).
296     *
297     * <p>This method only needs to be called if the VPN has explicitly bound its underlying
298     * communications channels &mdash; such as the socket(s) passed to {@link #protect(int)} &mdash;
299     * to a {@code Network} using APIs such as {@link Network#bindSocket(Socket)} or
300     * {@link Network#bindSocket(DatagramSocket)}. The VPN should call this method every time
301     * the set of {@code Network}s it is using changes.
302     *
303     * <p>{@code networks} is one of the following:
304     * <ul>
305     * <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in
306     * decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
307     * networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
308     * first in the array.</li>
309     * <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no
310     * underlying network connection, and thus, app traffic will not be sent or received.</li>
311     * <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's
312     * default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket}
313     * APIs mentioned above to send traffic over specific channels.</li>
314     * </ul>
315     *
316     * <p>This call will succeed only if the VPN is currently established. For setting this value
317     * when the VPN has not yet been established, see {@link Builder#setUnderlyingNetworks}.
318     *
319     * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
320     *
321     * @return {@code true} on success.
322     */
323    public boolean setUnderlyingNetworks(Network[] networks) {
324        try {
325            return getService().setUnderlyingNetworksForVpn(networks);
326        } catch (RemoteException e) {
327            throw new IllegalStateException(e);
328        }
329    }
330
331    /**
332     * Return the communication interface to the service. This method returns
333     * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
334     * action. Applications overriding this method must identify the intent
335     * and return the corresponding interface accordingly.
336     *
337     * @see Service#onBind
338     */
339    @Override
340    public IBinder onBind(Intent intent) {
341        if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
342            return new Callback();
343        }
344        return null;
345    }
346
347    /**
348     * Invoked when the application is revoked. At this moment, the VPN
349     * interface is already deactivated by the system. The application should
350     * close the file descriptor and shut down gracefully. The default
351     * implementation of this method is calling {@link Service#stopSelf()}.
352     *
353     * <p class="note">Calls to this method may not happen on the main thread
354     * of the process.
355     *
356     * @see #prepare
357     */
358    public void onRevoke() {
359        stopSelf();
360    }
361
362    /**
363     * Use raw Binder instead of AIDL since now there is only one usage.
364     */
365    private class Callback extends Binder {
366        @Override
367        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
368            if (code == IBinder.LAST_CALL_TRANSACTION) {
369                onRevoke();
370                return true;
371            }
372            return false;
373        }
374    }
375
376    /**
377     * Private method to validate address and prefixLength.
378     */
379    private static void check(InetAddress address, int prefixLength) {
380        if (address.isLoopbackAddress()) {
381            throw new IllegalArgumentException("Bad address");
382        }
383        if (address instanceof Inet4Address) {
384            if (prefixLength < 0 || prefixLength > 32) {
385                throw new IllegalArgumentException("Bad prefixLength");
386            }
387        } else if (address instanceof Inet6Address) {
388            if (prefixLength < 0 || prefixLength > 128) {
389                throw new IllegalArgumentException("Bad prefixLength");
390            }
391        } else {
392            throw new IllegalArgumentException("Unsupported family");
393        }
394    }
395
396    /**
397     * Helper class to create a VPN interface. This class should be always
398     * used within the scope of the outer {@link VpnService}.
399     *
400     * @see VpnService
401     */
402    public class Builder {
403
404        private final VpnConfig mConfig = new VpnConfig();
405        private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
406        private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
407
408        public Builder() {
409            mConfig.user = VpnService.this.getClass().getName();
410        }
411
412        /**
413         * Set the name of this session. It will be displayed in
414         * system-managed dialogs and notifications. This is recommended
415         * not required.
416         */
417        public Builder setSession(String session) {
418            mConfig.session = session;
419            return this;
420        }
421
422        /**
423         * Set the {@link PendingIntent} to an activity for users to
424         * configure the VPN connection. If it is not set, the button
425         * to configure will not be shown in system-managed dialogs.
426         */
427        public Builder setConfigureIntent(PendingIntent intent) {
428            mConfig.configureIntent = intent;
429            return this;
430        }
431
432        /**
433         * Set the maximum transmission unit (MTU) of the VPN interface. If
434         * it is not set, the default value in the operating system will be
435         * used.
436         *
437         * @throws IllegalArgumentException if the value is not positive.
438         */
439        public Builder setMtu(int mtu) {
440            if (mtu <= 0) {
441                throw new IllegalArgumentException("Bad mtu");
442            }
443            mConfig.mtu = mtu;
444            return this;
445        }
446
447        /**
448         * Add a network address to the VPN interface. Both IPv4 and IPv6
449         * addresses are supported. At least one address must be set before
450         * calling {@link #establish}.
451         *
452         * Adding an address implicitly allows traffic from that address family
453         * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
454         *
455         * @throws IllegalArgumentException if the address is invalid.
456         */
457        public Builder addAddress(InetAddress address, int prefixLength) {
458            check(address, prefixLength);
459
460            if (address.isAnyLocalAddress()) {
461                throw new IllegalArgumentException("Bad address");
462            }
463            mAddresses.add(new LinkAddress(address, prefixLength));
464            mConfig.updateAllowedFamilies(address);
465            return this;
466        }
467
468        /**
469         * Convenience method to add a network address to the VPN interface
470         * using a numeric address string. See {@link InetAddress} for the
471         * definitions of numeric address formats.
472         *
473         * Adding an address implicitly allows traffic from that address family
474         * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
475         *
476         * @throws IllegalArgumentException if the address is invalid.
477         * @see #addAddress(InetAddress, int)
478         */
479        public Builder addAddress(String address, int prefixLength) {
480            return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
481        }
482
483        /**
484         * Add a network route to the VPN interface. Both IPv4 and IPv6
485         * routes are supported.
486         *
487         * Adding a route implicitly allows traffic from that address family
488         * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
489         *
490         * @throws IllegalArgumentException if the route is invalid.
491         */
492        public Builder addRoute(InetAddress address, int prefixLength) {
493            check(address, prefixLength);
494
495            int offset = prefixLength / 8;
496            byte[] bytes = address.getAddress();
497            if (offset < bytes.length) {
498                for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
499                    if (bytes[offset] != 0) {
500                        throw new IllegalArgumentException("Bad address");
501                    }
502                }
503            }
504            mRoutes.add(new RouteInfo(new IpPrefix(address, prefixLength), null));
505            mConfig.updateAllowedFamilies(address);
506            return this;
507        }
508
509        /**
510         * Convenience method to add a network route to the VPN interface
511         * using a numeric address string. See {@link InetAddress} for the
512         * definitions of numeric address formats.
513         *
514         * Adding a route implicitly allows traffic from that address family
515         * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
516         *
517         * @throws IllegalArgumentException if the route is invalid.
518         * @see #addRoute(InetAddress, int)
519         */
520        public Builder addRoute(String address, int prefixLength) {
521            return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
522        }
523
524        /**
525         * Add a DNS server to the VPN connection. Both IPv4 and IPv6
526         * addresses are supported. If none is set, the DNS servers of
527         * the default network will be used.
528         *
529         * Adding a server implicitly allows traffic from that address family
530         * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
531         *
532         * @throws IllegalArgumentException if the address is invalid.
533         */
534        public Builder addDnsServer(InetAddress address) {
535            if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
536                throw new IllegalArgumentException("Bad address");
537            }
538            if (mConfig.dnsServers == null) {
539                mConfig.dnsServers = new ArrayList<String>();
540            }
541            mConfig.dnsServers.add(address.getHostAddress());
542            return this;
543        }
544
545        /**
546         * Convenience method to add a DNS server to the VPN connection
547         * using a numeric address string. See {@link InetAddress} for the
548         * definitions of numeric address formats.
549         *
550         * Adding a server implicitly allows traffic from that address family
551         * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
552         *
553         * @throws IllegalArgumentException if the address is invalid.
554         * @see #addDnsServer(InetAddress)
555         */
556        public Builder addDnsServer(String address) {
557            return addDnsServer(InetAddress.parseNumericAddress(address));
558        }
559
560        /**
561         * Add a search domain to the DNS resolver.
562         */
563        public Builder addSearchDomain(String domain) {
564            if (mConfig.searchDomains == null) {
565                mConfig.searchDomains = new ArrayList<String>();
566            }
567            mConfig.searchDomains.add(domain);
568            return this;
569        }
570
571        /**
572         * Allows traffic from the specified address family.
573         *
574         * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
575         * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
576         * route or DNS server is added, that family is allowed.
577         *
578         * This method allows an address family to be unblocked even without adding an address,
579         * route or DNS server of that family. Traffic of that family will then typically
580         * fall-through to the underlying network if it's supported.
581         *
582         * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
583         * {@link IllegalArgumentException} is thrown if it's neither.
584         *
585         * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
586         *
587         * @return this {@link Builder} object to facilitate chaining of method calls.
588         */
589        public Builder allowFamily(int family) {
590            if (family == AF_INET) {
591                mConfig.allowIPv4 = true;
592            } else if (family == AF_INET6) {
593                mConfig.allowIPv6 = true;
594            } else {
595                throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
596                        AF_INET6);
597            }
598            return this;
599        }
600
601        private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
602            IPackageManager pm = IPackageManager.Stub.asInterface(
603                    ServiceManager.getService("package"));
604            try {
605                pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
606            } catch (RemoteException e) {
607                throw new IllegalStateException(e);
608            }
609        }
610
611        /**
612         * Adds an application that's allowed to access the VPN connection.
613         *
614         * If this method is called at least once, only applications added through this method (and
615         * no others) are allowed access. Else (if this method is never called), all applications
616         * are allowed by default.  If some applications are added, other, un-added applications
617         * will use networking as if the VPN wasn't running.
618         *
619         * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
620         * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
621         * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
622         *
623         * {@code packageName} must be the canonical name of a currently installed application.
624         * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
625         *
626         * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
627         *
628         * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
629         *
630         * @return this {@link Builder} object to facilitate chaining method calls.
631         */
632        public Builder addAllowedApplication(String packageName)
633                throws PackageManager.NameNotFoundException {
634            if (mConfig.disallowedApplications != null) {
635                throw new UnsupportedOperationException("addDisallowedApplication already called");
636            }
637            verifyApp(packageName);
638            if (mConfig.allowedApplications == null) {
639                mConfig.allowedApplications = new ArrayList<String>();
640            }
641            mConfig.allowedApplications.add(packageName);
642            return this;
643        }
644
645        /**
646         * Adds an application that's denied access to the VPN connection.
647         *
648         * By default, all applications are allowed access, except for those denied through this
649         * method.  Denied applications will use networking as if the VPN wasn't running.
650         *
651         * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
652         * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
653         * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
654         *
655         * {@code packageName} must be the canonical name of a currently installed application.
656         * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
657         *
658         * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
659         *
660         * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
661         *
662         * @return this {@link Builder} object to facilitate chaining method calls.
663         */
664        public Builder addDisallowedApplication(String packageName)
665                throws PackageManager.NameNotFoundException {
666            if (mConfig.allowedApplications != null) {
667                throw new UnsupportedOperationException("addAllowedApplication already called");
668            }
669            verifyApp(packageName);
670            if (mConfig.disallowedApplications == null) {
671                mConfig.disallowedApplications = new ArrayList<String>();
672            }
673            mConfig.disallowedApplications.add(packageName);
674            return this;
675        }
676
677        /**
678         * Allows all apps to bypass this VPN connection.
679         *
680         * By default, all traffic from apps is forwarded through the VPN interface and it is not
681         * possible for apps to side-step the VPN. If this method is called, apps may use methods
682         * such as {@link ConnectivityManager#setProcessDefaultNetwork} to instead send/receive
683         * directly over the underlying network or any other network they have permissions for.
684         *
685         * @return this {@link Builder} object to facilitate chaining of method calls.
686         */
687        public Builder allowBypass() {
688            mConfig.allowBypass = true;
689            return this;
690        }
691
692        /**
693         * Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
694         *
695         * By default, the file descriptor returned by {@link #establish} is non-blocking.
696         *
697         * @param blocking True to put the descriptor into blocking mode; false for non-blocking.
698         *
699         * @return this {@link Builder} object to facilitate chaining method calls.
700         */
701        public Builder setBlocking(boolean blocking) {
702            mConfig.blocking = blocking;
703            return this;
704        }
705
706        /**
707         * Sets the underlying networks used by the VPN for its upstream connections.
708         *
709         * @see VpnService#setUnderlyingNetworks
710         *
711         * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
712         *
713         * @return this {@link Builder} object to facilitate chaining method calls.
714         */
715        public Builder setUnderlyingNetworks(Network[] networks) {
716            mConfig.underlyingNetworks = networks != null ? networks.clone() : null;
717            return this;
718        }
719
720        /**
721         * Create a VPN interface using the parameters supplied to this
722         * builder. The interface works on IP packets, and a file descriptor
723         * is returned for the application to access them. Each read
724         * retrieves an outgoing packet which was routed to the interface.
725         * Each write injects an incoming packet just like it was received
726         * from the interface. The file descriptor is put into non-blocking
727         * mode by default to avoid blocking Java threads. To use the file
728         * descriptor completely in native space, see
729         * {@link ParcelFileDescriptor#detachFd()}. The application MUST
730         * close the file descriptor when the VPN connection is terminated.
731         * The VPN interface will be removed and the network will be
732         * restored by the system automatically.
733         *
734         * <p>To avoid conflicts, there can be only one active VPN interface
735         * at the same time. Usually network parameters are never changed
736         * during the lifetime of a VPN connection. It is also common for an
737         * application to create a new file descriptor after closing the
738         * previous one. However, it is rare but not impossible to have two
739         * interfaces while performing a seamless handover. In this case, the
740         * old interface will be deactivated when the new one is created
741         * successfully. Both file descriptors are valid but now outgoing
742         * packets will be routed to the new interface. Therefore, after
743         * draining the old file descriptor, the application MUST close it
744         * and start using the new file descriptor. If the new interface
745         * cannot be created, the existing interface and its file descriptor
746         * remain untouched.
747         *
748         * <p>An exception will be thrown if the interface cannot be created
749         * for any reason. However, this method returns {@code null} if the
750         * application is not prepared or is revoked. This helps solve
751         * possible race conditions between other VPN applications.
752         *
753         * @return {@link ParcelFileDescriptor} of the VPN interface, or
754         *         {@code null} if the application is not prepared.
755         * @throws IllegalArgumentException if a parameter is not accepted
756         *         by the operating system.
757         * @throws IllegalStateException if a parameter cannot be applied
758         *         by the operating system.
759         * @throws SecurityException if the service is not properly declared
760         *         in {@code AndroidManifest.xml}.
761         * @see VpnService
762         */
763        public ParcelFileDescriptor establish() {
764            mConfig.addresses = mAddresses;
765            mConfig.routes = mRoutes;
766
767            try {
768                return getService().establishVpn(mConfig);
769            } catch (RemoteException e) {
770                throw new IllegalStateException(e);
771            }
772        }
773    }
774}
775