blob: e6f5e32e727ffde8af23d519c83077f77277bee6 [file] [log] [blame]
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -07001/*
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
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -070019import static android.system.OsConstants.AF_INET;
20import static android.system.OsConstants.AF_INET6;
21
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070022import android.app.Activity;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070023import android.app.PendingIntent;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070024import android.app.Service;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070025import android.content.Context;
26import android.content.Intent;
Paul Jensen0784eea2014-08-19 16:00:24 -040027import android.content.pm.IPackageManager;
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -070028import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040029import android.net.NetworkUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070030import android.os.Binder;
31import android.os.IBinder;
32import android.os.Parcel;
33import android.os.ParcelFileDescriptor;
34import android.os.RemoteException;
35import android.os.ServiceManager;
Paul Jensen0784eea2014-08-19 16:00:24 -040036import android.os.UserHandle;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070037
38import com.android.internal.net.VpnConfig;
39
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070040import java.net.DatagramSocket;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070041import java.net.Inet4Address;
42import java.net.Inet6Address;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070043import java.net.InetAddress;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070044import java.net.Socket;
45import java.util.ArrayList;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070046import java.util.List;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070047
48/**
49 * VpnService is a base class for applications to extend and build their
50 * own VPN solutions. In general, it creates a virtual network interface,
51 * configures addresses and routing rules, and returns a file descriptor
52 * to the application. Each read from the descriptor retrieves an outgoing
53 * packet which was routed to the interface. Each write to the descriptor
54 * injects an incoming packet just like it was received from the interface.
55 * The interface is running on Internet Protocol (IP), so packets are
56 * always started with IP headers. The application then completes a VPN
57 * connection by processing and exchanging packets with the remote server
58 * over a tunnel.
59 *
60 * <p>Letting applications intercept packets raises huge security concerns.
61 * A VPN application can easily break the network. Besides, two of them may
62 * conflict with each other. The system takes several actions to address
63 * these issues. Here are some key points:
64 * <ul>
65 * <li>User action is required to create a VPN connection.</li>
66 * <li>There can be only one VPN connection running at the same time. The
67 * existing interface is deactivated when a new one is created.</li>
68 * <li>A system-managed notification is shown during the lifetime of a
69 * VPN connection.</li>
70 * <li>A system-managed dialog gives the information of the current VPN
71 * connection. It also provides a button to disconnect.</li>
72 * <li>The network is restored automatically when the file descriptor is
73 * closed. It also covers the cases when a VPN application is crashed
74 * or killed by the system.</li>
75 * </ul>
76 *
77 * <p>There are two primary methods in this class: {@link #prepare} and
78 * {@link Builder#establish}. The former deals with user action and stops
79 * the VPN connection created by another application. The latter creates
80 * a VPN interface using the parameters supplied to the {@link Builder}.
81 * An application must call {@link #prepare} to grant the right to use
82 * other methods in this class, and the right can be revoked at any time.
83 * Here are the general steps to create a VPN connection:
84 * <ol>
85 * <li>When the user press the button to connect, call {@link #prepare}
86 * and launch the returned intent.</li>
87 * <li>When the application becomes prepared, start the service.</li>
88 * <li>Create a tunnel to the remote server and negotiate the network
89 * parameters for the VPN connection.</li>
90 * <li>Supply those parameters to a {@link Builder} and create a VPN
91 * interface by calling {@link Builder#establish}.</li>
92 * <li>Process and exchange packets between the tunnel and the returned
93 * file descriptor.</li>
94 * <li>When {@link #onRevoke} is invoked, close the file descriptor and
95 * shut down the tunnel gracefully.</li>
96 * </ol>
97 *
98 * <p>Services extended this class need to be declared with appropriate
99 * permission and intent filter. Their access must be secured by
100 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
101 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
102 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
103 * <pre>
104 * &lt;service android:name=".ExampleVpnService"
105 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
106 * &lt;intent-filter&gt;
107 * &lt;action android:name="android.net.VpnService"/&gt;
108 * &lt;/intent-filter&gt;
109 * &lt;/service&gt;</pre>
110 *
111 * @see Builder
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700112 */
113public class VpnService extends Service {
114
115 /**
116 * The action must be matched by the intent filter of this service. It also
117 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
118 * permission so that other applications cannot abuse it.
119 */
120 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
121
122 /**
123 * Use IConnectivityManager since those methods are hidden and not
124 * available in ConnectivityManager.
125 */
126 private static IConnectivityManager getService() {
127 return IConnectivityManager.Stub.asInterface(
128 ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
129 }
130
131 /**
132 * Prepare to establish a VPN connection. This method returns {@code null}
133 * if the VPN application is already prepared. Otherwise, it returns an
134 * {@link Intent} to a system activity. The application should launch the
135 * activity using {@link Activity#startActivityForResult} to get itself
136 * prepared. The activity may pop up a dialog to require user action, and
137 * the result will come back via its {@link Activity#onActivityResult}.
138 * If the result is {@link Activity#RESULT_OK}, the application becomes
139 * prepared and is granted to use other methods in this class.
140 *
141 * <p>Only one application can be granted at the same time. The right
142 * is revoked when another application is granted. The application
143 * losing the right will be notified via its {@link #onRevoke}. Unless
144 * it becomes prepared again, subsequent calls to other methods in this
145 * class will fail.
146 *
147 * @see #onRevoke
148 */
149 public static Intent prepare(Context context) {
150 try {
151 if (getService().prepareVpn(context.getPackageName(), null)) {
152 return null;
153 }
154 } catch (RemoteException e) {
155 // ignore
156 }
157 return VpnConfig.getIntentForConfirmation();
158 }
159
160 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800161 * Protect a socket from VPN connections. After protecting, data sent
162 * through this socket will go directly to the underlying network,
163 * so its traffic will not be forwarded through the VPN.
164 * This method is useful if some connections need to be kept
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700165 * outside of VPN. For example, a VPN tunnel should protect itself if its
166 * destination is covered by VPN routes. Otherwise its outgoing packets
167 * will be sent back to the VPN interface and cause an infinite loop. This
168 * method will fail if the application is not prepared or is revoked.
169 *
170 * <p class="note">The socket is NOT closed by this method.
171 *
172 * @return {@code true} on success.
173 */
174 public boolean protect(int socket) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400175 return NetworkUtils.protectFromVpn(socket);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700176 }
177
178 /**
179 * Convenience method to protect a {@link Socket} from VPN connections.
180 *
181 * @return {@code true} on success.
182 * @see #protect(int)
183 */
184 public boolean protect(Socket socket) {
185 return protect(socket.getFileDescriptor$().getInt$());
186 }
187
188 /**
189 * Convenience method to protect a {@link DatagramSocket} from VPN
190 * connections.
191 *
192 * @return {@code true} on success.
193 * @see #protect(int)
194 */
195 public boolean protect(DatagramSocket socket) {
196 return protect(socket.getFileDescriptor$().getInt$());
197 }
198
199 /**
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700200 * Adds a network address to the VPN interface.
201 *
202 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
203 * address is already in use or cannot be assigned to the interface for any other reason.
204 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700205 * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
206 * be routed over the VPN. @see Builder#allowFamily
207 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700208 * @throws {@link IllegalArgumentException} if the address is invalid.
209 *
210 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
211 * @param prefixLength The prefix length of the address.
212 *
213 * @return {@code true} on success.
214 * @see Builder#addAddress
Sreeram Ramachandrana1e06802014-09-11 14:08:25 -0700215 *
216 * @hide
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700217 */
218 public boolean addAddress(InetAddress address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700219 check(address, prefixLength);
220 try {
221 return getService().addVpnAddress(address.getHostAddress(), prefixLength);
222 } catch (RemoteException e) {
223 throw new IllegalStateException(e);
224 }
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700225 }
226
227 /**
228 * Removes a network address from the VPN interface.
229 *
230 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
231 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
232 * cannot be removed), or if the address cannot be removed for any other reason.
233 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700234 * After removing an address, if there are no addresses, routes or DNS servers of a particular
235 * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
236 * family from being routed. In other words, once an address family has been allowed, it stays
237 * allowed for the rest of the VPN's session. @see Builder#allowFamily
238 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700239 * @throws {@link IllegalArgumentException} if the address is invalid.
240 *
241 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
242 * @param prefixLength The prefix length of the address.
243 *
244 * @return {@code true} on success.
Sreeram Ramachandrana1e06802014-09-11 14:08:25 -0700245 *
246 * @hide
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700247 */
248 public boolean removeAddress(InetAddress address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700249 check(address, prefixLength);
250 try {
251 return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
252 } catch (RemoteException e) {
253 throw new IllegalStateException(e);
254 }
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700255 }
256
257 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700258 * Return the communication interface to the service. This method returns
259 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
260 * action. Applications overriding this method must identify the intent
261 * and return the corresponding interface accordingly.
262 *
263 * @see Service#onBind
264 */
265 @Override
266 public IBinder onBind(Intent intent) {
267 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
268 return new Callback();
269 }
270 return null;
271 }
272
273 /**
274 * Invoked when the application is revoked. At this moment, the VPN
275 * interface is already deactivated by the system. The application should
276 * close the file descriptor and shut down gracefully. The default
277 * implementation of this method is calling {@link Service#stopSelf()}.
278 *
279 * <p class="note">Calls to this method may not happen on the main thread
280 * of the process.
281 *
282 * @see #prepare
283 */
284 public void onRevoke() {
285 stopSelf();
286 }
287
288 /**
289 * Use raw Binder instead of AIDL since now there is only one usage.
290 */
291 private class Callback extends Binder {
292 @Override
293 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
294 if (code == IBinder.LAST_CALL_TRANSACTION) {
295 onRevoke();
296 return true;
297 }
298 return false;
299 }
300 }
301
302 /**
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700303 * Private method to validate address and prefixLength.
304 */
305 private static void check(InetAddress address, int prefixLength) {
306 if (address.isLoopbackAddress()) {
307 throw new IllegalArgumentException("Bad address");
308 }
309 if (address instanceof Inet4Address) {
310 if (prefixLength < 0 || prefixLength > 32) {
311 throw new IllegalArgumentException("Bad prefixLength");
312 }
313 } else if (address instanceof Inet6Address) {
314 if (prefixLength < 0 || prefixLength > 128) {
315 throw new IllegalArgumentException("Bad prefixLength");
316 }
317 } else {
318 throw new IllegalArgumentException("Unsupported family");
319 }
320 }
321
322 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700323 * Helper class to create a VPN interface. This class should be always
324 * used within the scope of the outer {@link VpnService}.
325 *
326 * @see VpnService
327 */
328 public class Builder {
329
330 private final VpnConfig mConfig = new VpnConfig();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700331 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
332 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700333
334 public Builder() {
335 mConfig.user = VpnService.this.getClass().getName();
336 }
337
338 /**
339 * Set the name of this session. It will be displayed in
340 * system-managed dialogs and notifications. This is recommended
341 * not required.
342 */
343 public Builder setSession(String session) {
344 mConfig.session = session;
345 return this;
346 }
347
348 /**
349 * Set the {@link PendingIntent} to an activity for users to
350 * configure the VPN connection. If it is not set, the button
351 * to configure will not be shown in system-managed dialogs.
352 */
353 public Builder setConfigureIntent(PendingIntent intent) {
354 mConfig.configureIntent = intent;
355 return this;
356 }
357
358 /**
359 * Set the maximum transmission unit (MTU) of the VPN interface. If
360 * it is not set, the default value in the operating system will be
361 * used.
362 *
363 * @throws IllegalArgumentException if the value is not positive.
364 */
365 public Builder setMtu(int mtu) {
366 if (mtu <= 0) {
367 throw new IllegalArgumentException("Bad mtu");
368 }
369 mConfig.mtu = mtu;
370 return this;
371 }
372
373 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700374 * Add a network address to the VPN interface. Both IPv4 and IPv6
375 * addresses are supported. At least one address must be set before
376 * calling {@link #establish}.
377 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700378 * Adding an address implicitly allows traffic from that address family
379 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
380 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700381 * @throws IllegalArgumentException if the address is invalid.
382 */
383 public Builder addAddress(InetAddress address, int prefixLength) {
384 check(address, prefixLength);
385
386 if (address.isAnyLocalAddress()) {
387 throw new IllegalArgumentException("Bad address");
388 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700389 mAddresses.add(new LinkAddress(address, prefixLength));
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700390 mConfig.updateAllowedFamilies(address);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700391 return this;
392 }
393
394 /**
395 * Convenience method to add a network address to the VPN interface
396 * using a numeric address string. See {@link InetAddress} for the
397 * definitions of numeric address formats.
398 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700399 * Adding an address implicitly allows traffic from that address family
400 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
401 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700402 * @throws IllegalArgumentException if the address is invalid.
403 * @see #addAddress(InetAddress, int)
404 */
405 public Builder addAddress(String address, int prefixLength) {
406 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
407 }
408
409 /**
410 * Add a network route to the VPN interface. Both IPv4 and IPv6
411 * routes are supported.
412 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700413 * Adding a route implicitly allows traffic from that address family
414 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
415 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700416 * @throws IllegalArgumentException if the route is invalid.
417 */
418 public Builder addRoute(InetAddress address, int prefixLength) {
419 check(address, prefixLength);
420
421 int offset = prefixLength / 8;
422 byte[] bytes = address.getAddress();
423 if (offset < bytes.length) {
424 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
425 if (bytes[offset] != 0) {
426 throw new IllegalArgumentException("Bad address");
427 }
428 }
429 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700430 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null));
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700431 mConfig.updateAllowedFamilies(address);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700432 return this;
433 }
434
435 /**
436 * Convenience method to add a network route to the VPN interface
437 * using a numeric address string. See {@link InetAddress} for the
438 * definitions of numeric address formats.
439 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700440 * Adding a route implicitly allows traffic from that address family
441 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
442 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700443 * @throws IllegalArgumentException if the route is invalid.
444 * @see #addRoute(InetAddress, int)
445 */
446 public Builder addRoute(String address, int prefixLength) {
447 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
448 }
449
450 /**
451 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
452 * addresses are supported. If none is set, the DNS servers of
453 * the default network will be used.
454 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700455 * Adding a server implicitly allows traffic from that address family
456 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
457 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700458 * @throws IllegalArgumentException if the address is invalid.
459 */
460 public Builder addDnsServer(InetAddress address) {
461 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
462 throw new IllegalArgumentException("Bad address");
463 }
464 if (mConfig.dnsServers == null) {
465 mConfig.dnsServers = new ArrayList<String>();
466 }
467 mConfig.dnsServers.add(address.getHostAddress());
468 return this;
469 }
470
471 /**
472 * Convenience method to add a DNS server to the VPN connection
473 * using a numeric address string. See {@link InetAddress} for the
474 * definitions of numeric address formats.
475 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700476 * Adding a server implicitly allows traffic from that address family
477 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
478 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700479 * @throws IllegalArgumentException if the address is invalid.
480 * @see #addDnsServer(InetAddress)
481 */
482 public Builder addDnsServer(String address) {
483 return addDnsServer(InetAddress.parseNumericAddress(address));
484 }
485
486 /**
487 * Add a search domain to the DNS resolver.
488 */
489 public Builder addSearchDomain(String domain) {
490 if (mConfig.searchDomains == null) {
491 mConfig.searchDomains = new ArrayList<String>();
492 }
493 mConfig.searchDomains.add(domain);
494 return this;
495 }
496
497 /**
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700498 * Allows traffic from the specified address family.
499 *
500 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
501 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
502 * route or DNS server is added, that family is allowed.
503 *
504 * This method allows an address family to be unblocked even without adding an address,
505 * route or DNS server of that family. Traffic of that family will then typically
506 * fall-through to the underlying network if it's supported.
507 *
508 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
509 * {@link IllegalArgumentException} is thrown if it's neither.
510 *
511 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
512 *
513 * @return this {@link Builder} object to facilitate chaining of method calls.
514 */
515 public Builder allowFamily(int family) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700516 if (family == AF_INET) {
517 mConfig.allowIPv4 = true;
518 } else if (family == AF_INET6) {
519 mConfig.allowIPv6 = true;
520 } else {
521 throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
522 AF_INET6);
523 }
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700524 return this;
525 }
526
Paul Jensen0784eea2014-08-19 16:00:24 -0400527 private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
528 IPackageManager pm = IPackageManager.Stub.asInterface(
529 ServiceManager.getService("package"));
530 try {
531 pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
532 } catch (RemoteException e) {
533 throw new IllegalStateException(e);
534 }
535 }
536
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700537 /**
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700538 * Adds an application that's allowed to access the VPN connection.
539 *
540 * If this method is called at least once, only applications added through this method (and
541 * no others) are allowed access. Else (if this method is never called), all applications
Robert Greenwaltfc4f7212014-08-25 12:41:08 -0700542 * are allowed by default. If some applications are added, other, un-added applications
543 * will use networking as if the VPN wasn't running.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700544 *
545 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
546 * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
547 * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
548 *
549 * {@code packageName} must be the canonical name of a currently installed application.
550 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
551 *
552 * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
553 *
554 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
555 *
556 * @return this {@link Builder} object to facilitate chaining method calls.
557 */
558 public Builder addAllowedApplication(String packageName)
559 throws PackageManager.NameNotFoundException {
Paul Jensen0784eea2014-08-19 16:00:24 -0400560 if (mConfig.disallowedApplications != null) {
561 throw new UnsupportedOperationException("addDisallowedApplication already called");
562 }
563 verifyApp(packageName);
564 if (mConfig.allowedApplications == null) {
565 mConfig.allowedApplications = new ArrayList<String>();
566 }
567 mConfig.allowedApplications.add(packageName);
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700568 return this;
569 }
570
571 /**
572 * Adds an application that's denied access to the VPN connection.
573 *
574 * By default, all applications are allowed access, except for those denied through this
Robert Greenwaltfc4f7212014-08-25 12:41:08 -0700575 * method. Denied applications will use networking as if the VPN wasn't running.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700576 *
577 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
578 * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
579 * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
580 *
581 * {@code packageName} must be the canonical name of a currently installed application.
582 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
583 *
584 * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
585 *
586 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
587 *
588 * @return this {@link Builder} object to facilitate chaining method calls.
589 */
590 public Builder addDisallowedApplication(String packageName)
591 throws PackageManager.NameNotFoundException {
Paul Jensen0784eea2014-08-19 16:00:24 -0400592 if (mConfig.allowedApplications != null) {
593 throw new UnsupportedOperationException("addAllowedApplication already called");
594 }
595 verifyApp(packageName);
596 if (mConfig.disallowedApplications == null) {
597 mConfig.disallowedApplications = new ArrayList<String>();
598 }
599 mConfig.disallowedApplications.add(packageName);
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700600 return this;
601 }
602
603 /**
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700604 * Allows all apps to bypass this VPN connection.
605 *
606 * By default, all traffic from apps is forwarded through the VPN interface and it is not
607 * possible for apps to side-step the VPN. If this method is called, apps may use methods
608 * such as {@link ConnectivityManager#setProcessDefaultNetwork} to instead send/receive
609 * directly over the underlying network or any other network they have permissions for.
610 *
611 * @return this {@link Builder} object to facilitate chaining of method calls.
612 */
613 public Builder allowBypass() {
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700614 mConfig.allowBypass = true;
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700615 return this;
616 }
617
618 /**
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700619 * Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
620 *
621 * By default, the file descriptor returned by {@link #establish} is non-blocking.
622 *
623 * @param blocking True to put the descriptor into blocking mode; false for non-blocking.
624 *
625 * @return this {@link Builder} object to facilitate chaining method calls.
626 */
627 public Builder setBlocking(boolean blocking) {
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700628 mConfig.blocking = blocking;
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700629 return this;
630 }
631
632 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700633 * Create a VPN interface using the parameters supplied to this
634 * builder. The interface works on IP packets, and a file descriptor
635 * is returned for the application to access them. Each read
636 * retrieves an outgoing packet which was routed to the interface.
637 * Each write injects an incoming packet just like it was received
638 * from the interface. The file descriptor is put into non-blocking
639 * mode by default to avoid blocking Java threads. To use the file
640 * descriptor completely in native space, see
641 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
642 * close the file descriptor when the VPN connection is terminated.
643 * The VPN interface will be removed and the network will be
644 * restored by the system automatically.
645 *
646 * <p>To avoid conflicts, there can be only one active VPN interface
647 * at the same time. Usually network parameters are never changed
648 * during the lifetime of a VPN connection. It is also common for an
649 * application to create a new file descriptor after closing the
650 * previous one. However, it is rare but not impossible to have two
651 * interfaces while performing a seamless handover. In this case, the
652 * old interface will be deactivated when the new one is created
653 * successfully. Both file descriptors are valid but now outgoing
654 * packets will be routed to the new interface. Therefore, after
655 * draining the old file descriptor, the application MUST close it
656 * and start using the new file descriptor. If the new interface
657 * cannot be created, the existing interface and its file descriptor
658 * remain untouched.
659 *
660 * <p>An exception will be thrown if the interface cannot be created
661 * for any reason. However, this method returns {@code null} if the
662 * application is not prepared or is revoked. This helps solve
663 * possible race conditions between other VPN applications.
664 *
665 * @return {@link ParcelFileDescriptor} of the VPN interface, or
666 * {@code null} if the application is not prepared.
667 * @throws IllegalArgumentException if a parameter is not accepted
668 * by the operating system.
669 * @throws IllegalStateException if a parameter cannot be applied
670 * by the operating system.
671 * @throws SecurityException if the service is not properly declared
672 * in {@code AndroidManifest.xml}.
673 * @see VpnService
674 */
675 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700676 mConfig.addresses = mAddresses;
677 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700678
679 try {
680 return getService().establishVpn(mConfig);
681 } catch (RemoteException e) {
682 throw new IllegalStateException(e);
683 }
684 }
685 }
686}