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