blob: c42791cb142c75d0f5473186e137389ebf39d886 [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>
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -070065 * <li>User action is required the first time an application creates a VPN
66 * connection.</li>
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070067 * <li>There can be only one VPN connection running at the same time. The
68 * existing interface is deactivated when a new one is created.</li>
69 * <li>A system-managed notification is shown during the lifetime of a
70 * VPN connection.</li>
71 * <li>A system-managed dialog gives the information of the current VPN
72 * connection. It also provides a button to disconnect.</li>
73 * <li>The network is restored automatically when the file descriptor is
74 * closed. It also covers the cases when a VPN application is crashed
75 * or killed by the system.</li>
76 * </ul>
77 *
78 * <p>There are two primary methods in this class: {@link #prepare} and
79 * {@link Builder#establish}. The former deals with user action and stops
80 * the VPN connection created by another application. The latter creates
81 * a VPN interface using the parameters supplied to the {@link Builder}.
82 * An application must call {@link #prepare} to grant the right to use
83 * other methods in this class, and the right can be revoked at any time.
84 * Here are the general steps to create a VPN connection:
85 * <ol>
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -070086 * <li>When the user presses the button to connect, call {@link #prepare}
87 * and launch the returned intent, if non-null.</li>
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070088 * <li>When the application becomes prepared, start the service.</li>
89 * <li>Create a tunnel to the remote server and negotiate the network
90 * parameters for the VPN connection.</li>
91 * <li>Supply those parameters to a {@link Builder} and create a VPN
92 * interface by calling {@link Builder#establish}.</li>
93 * <li>Process and exchange packets between the tunnel and the returned
94 * file descriptor.</li>
95 * <li>When {@link #onRevoke} is invoked, close the file descriptor and
96 * shut down the tunnel gracefully.</li>
97 * </ol>
98 *
99 * <p>Services extended this class need to be declared with appropriate
100 * permission and intent filter. Their access must be secured by
101 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
102 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
103 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
104 * <pre>
105 * &lt;service android:name=".ExampleVpnService"
106 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
107 * &lt;intent-filter&gt;
108 * &lt;action android:name="android.net.VpnService"/&gt;
109 * &lt;/intent-filter&gt;
110 * &lt;/service&gt;</pre>
111 *
112 * @see Builder
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700113 */
114public class VpnService extends Service {
115
116 /**
117 * The action must be matched by the intent filter of this service. It also
118 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
119 * permission so that other applications cannot abuse it.
120 */
121 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
122
123 /**
124 * Use IConnectivityManager since those methods are hidden and not
125 * available in ConnectivityManager.
126 */
127 private static IConnectivityManager getService() {
128 return IConnectivityManager.Stub.asInterface(
129 ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
130 }
131
132 /**
133 * Prepare to establish a VPN connection. This method returns {@code null}
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -0700134 * if the VPN application is already prepared or if the user has previously
135 * consented to the VPN application. Otherwise, it returns an
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700136 * {@link Intent} to a system activity. The application should launch the
137 * activity using {@link Activity#startActivityForResult} to get itself
138 * prepared. The activity may pop up a dialog to require user action, and
139 * the result will come back via its {@link Activity#onActivityResult}.
140 * If the result is {@link Activity#RESULT_OK}, the application becomes
141 * prepared and is granted to use other methods in this class.
142 *
143 * <p>Only one application can be granted at the same time. The right
144 * is revoked when another application is granted. The application
145 * losing the right will be notified via its {@link #onRevoke}. Unless
146 * it becomes prepared again, subsequent calls to other methods in this
147 * class will fail.
148 *
Jeff Davidson6d6ea3b2014-09-11 14:13:22 -0700149 * <p>The user may disable the VPN at any time while it is activated, in
150 * which case this method will return an intent the next time it is
151 * executed to obtain the user's consent again.
152 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700153 * @see #onRevoke
154 */
155 public static Intent prepare(Context context) {
156 try {
157 if (getService().prepareVpn(context.getPackageName(), null)) {
158 return null;
159 }
160 } catch (RemoteException e) {
161 // ignore
162 }
163 return VpnConfig.getIntentForConfirmation();
164 }
165
166 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800167 * Protect a socket from VPN connections. After protecting, data sent
168 * through this socket will go directly to the underlying network,
169 * so its traffic will not be forwarded through the VPN.
170 * This method is useful if some connections need to be kept
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700171 * outside of VPN. For example, a VPN tunnel should protect itself if its
172 * destination is covered by VPN routes. Otherwise its outgoing packets
173 * will be sent back to the VPN interface and cause an infinite loop. This
174 * method will fail if the application is not prepared or is revoked.
175 *
176 * <p class="note">The socket is NOT closed by this method.
177 *
178 * @return {@code true} on success.
179 */
180 public boolean protect(int socket) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400181 return NetworkUtils.protectFromVpn(socket);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700182 }
183
184 /**
185 * Convenience method to protect a {@link Socket} from VPN connections.
186 *
187 * @return {@code true} on success.
188 * @see #protect(int)
189 */
190 public boolean protect(Socket socket) {
191 return protect(socket.getFileDescriptor$().getInt$());
192 }
193
194 /**
195 * Convenience method to protect a {@link DatagramSocket} from VPN
196 * connections.
197 *
198 * @return {@code true} on success.
199 * @see #protect(int)
200 */
201 public boolean protect(DatagramSocket socket) {
202 return protect(socket.getFileDescriptor$().getInt$());
203 }
204
205 /**
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700206 * Adds a network address to the VPN interface.
207 *
208 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
209 * address is already in use or cannot be assigned to the interface for any other reason.
210 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700211 * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
212 * be routed over the VPN. @see Builder#allowFamily
213 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700214 * @throws {@link IllegalArgumentException} if the address is invalid.
215 *
216 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
217 * @param prefixLength The prefix length of the address.
218 *
219 * @return {@code true} on success.
220 * @see Builder#addAddress
221 */
222 public boolean addAddress(InetAddress address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700223 check(address, prefixLength);
224 try {
225 return getService().addVpnAddress(address.getHostAddress(), prefixLength);
226 } catch (RemoteException e) {
227 throw new IllegalStateException(e);
228 }
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700229 }
230
231 /**
232 * Removes a network address from the VPN interface.
233 *
234 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
235 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
236 * cannot be removed), or if the address cannot be removed for any other reason.
237 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700238 * After removing an address, if there are no addresses, routes or DNS servers of a particular
239 * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
240 * family from being routed. In other words, once an address family has been allowed, it stays
241 * allowed for the rest of the VPN's session. @see Builder#allowFamily
242 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700243 * @throws {@link IllegalArgumentException} if the address is invalid.
244 *
245 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
246 * @param prefixLength The prefix length of the address.
247 *
248 * @return {@code true} on success.
249 */
250 public boolean removeAddress(InetAddress address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700251 check(address, prefixLength);
252 try {
253 return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
254 } catch (RemoteException e) {
255 throw new IllegalStateException(e);
256 }
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700257 }
258
259 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700260 * Return the communication interface to the service. This method returns
261 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
262 * action. Applications overriding this method must identify the intent
263 * and return the corresponding interface accordingly.
264 *
265 * @see Service#onBind
266 */
267 @Override
268 public IBinder onBind(Intent intent) {
269 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
270 return new Callback();
271 }
272 return null;
273 }
274
275 /**
276 * Invoked when the application is revoked. At this moment, the VPN
277 * interface is already deactivated by the system. The application should
278 * close the file descriptor and shut down gracefully. The default
279 * implementation of this method is calling {@link Service#stopSelf()}.
280 *
281 * <p class="note">Calls to this method may not happen on the main thread
282 * of the process.
283 *
284 * @see #prepare
285 */
286 public void onRevoke() {
287 stopSelf();
288 }
289
290 /**
291 * Use raw Binder instead of AIDL since now there is only one usage.
292 */
293 private class Callback extends Binder {
294 @Override
295 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
296 if (code == IBinder.LAST_CALL_TRANSACTION) {
297 onRevoke();
298 return true;
299 }
300 return false;
301 }
302 }
303
304 /**
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -0700305 * Private method to validate address and prefixLength.
306 */
307 private static void check(InetAddress address, int prefixLength) {
308 if (address.isLoopbackAddress()) {
309 throw new IllegalArgumentException("Bad address");
310 }
311 if (address instanceof Inet4Address) {
312 if (prefixLength < 0 || prefixLength > 32) {
313 throw new IllegalArgumentException("Bad prefixLength");
314 }
315 } else if (address instanceof Inet6Address) {
316 if (prefixLength < 0 || prefixLength > 128) {
317 throw new IllegalArgumentException("Bad prefixLength");
318 }
319 } else {
320 throw new IllegalArgumentException("Unsupported family");
321 }
322 }
323
324 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700325 * Helper class to create a VPN interface. This class should be always
326 * used within the scope of the outer {@link VpnService}.
327 *
328 * @see VpnService
329 */
330 public class Builder {
331
332 private final VpnConfig mConfig = new VpnConfig();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700333 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
334 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700335
336 public Builder() {
337 mConfig.user = VpnService.this.getClass().getName();
338 }
339
340 /**
341 * Set the name of this session. It will be displayed in
342 * system-managed dialogs and notifications. This is recommended
343 * not required.
344 */
345 public Builder setSession(String session) {
346 mConfig.session = session;
347 return this;
348 }
349
350 /**
351 * Set the {@link PendingIntent} to an activity for users to
352 * configure the VPN connection. If it is not set, the button
353 * to configure will not be shown in system-managed dialogs.
354 */
355 public Builder setConfigureIntent(PendingIntent intent) {
356 mConfig.configureIntent = intent;
357 return this;
358 }
359
360 /**
361 * Set the maximum transmission unit (MTU) of the VPN interface. If
362 * it is not set, the default value in the operating system will be
363 * used.
364 *
365 * @throws IllegalArgumentException if the value is not positive.
366 */
367 public Builder setMtu(int mtu) {
368 if (mtu <= 0) {
369 throw new IllegalArgumentException("Bad mtu");
370 }
371 mConfig.mtu = mtu;
372 return this;
373 }
374
375 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700376 * Add a network address to the VPN interface. Both IPv4 and IPv6
377 * addresses are supported. At least one address must be set before
378 * calling {@link #establish}.
379 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700380 * Adding an address implicitly allows traffic from that address family
381 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
382 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700383 * @throws IllegalArgumentException if the address is invalid.
384 */
385 public Builder addAddress(InetAddress address, int prefixLength) {
386 check(address, prefixLength);
387
388 if (address.isAnyLocalAddress()) {
389 throw new IllegalArgumentException("Bad address");
390 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700391 mAddresses.add(new LinkAddress(address, prefixLength));
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700392 mConfig.updateAllowedFamilies(address);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700393 return this;
394 }
395
396 /**
397 * Convenience method to add a network address to the VPN interface
398 * using a numeric address string. See {@link InetAddress} for the
399 * definitions of numeric address formats.
400 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700401 * Adding an address implicitly allows traffic from that address family
402 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
403 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700404 * @throws IllegalArgumentException if the address is invalid.
405 * @see #addAddress(InetAddress, int)
406 */
407 public Builder addAddress(String address, int prefixLength) {
408 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
409 }
410
411 /**
412 * Add a network route to the VPN interface. Both IPv4 and IPv6
413 * routes are supported.
414 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700415 * Adding a route implicitly allows traffic from that address family
416 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
417 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700418 * @throws IllegalArgumentException if the route is invalid.
419 */
420 public Builder addRoute(InetAddress address, int prefixLength) {
421 check(address, prefixLength);
422
423 int offset = prefixLength / 8;
424 byte[] bytes = address.getAddress();
425 if (offset < bytes.length) {
426 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
427 if (bytes[offset] != 0) {
428 throw new IllegalArgumentException("Bad address");
429 }
430 }
431 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700432 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null));
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700433 mConfig.updateAllowedFamilies(address);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700434 return this;
435 }
436
437 /**
438 * Convenience method to add a network route to the VPN interface
439 * using a numeric address string. See {@link InetAddress} for the
440 * definitions of numeric address formats.
441 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700442 * Adding a route implicitly allows traffic from that address family
443 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
444 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700445 * @throws IllegalArgumentException if the route is invalid.
446 * @see #addRoute(InetAddress, int)
447 */
448 public Builder addRoute(String address, int prefixLength) {
449 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
450 }
451
452 /**
453 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
454 * addresses are supported. If none is set, the DNS servers of
455 * the default network will be used.
456 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700457 * Adding a server implicitly allows traffic from that address family
458 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
459 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700460 * @throws IllegalArgumentException if the address is invalid.
461 */
462 public Builder addDnsServer(InetAddress address) {
463 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
464 throw new IllegalArgumentException("Bad address");
465 }
466 if (mConfig.dnsServers == null) {
467 mConfig.dnsServers = new ArrayList<String>();
468 }
469 mConfig.dnsServers.add(address.getHostAddress());
470 return this;
471 }
472
473 /**
474 * Convenience method to add a DNS server to the VPN connection
475 * using a numeric address string. See {@link InetAddress} for the
476 * definitions of numeric address formats.
477 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700478 * Adding a server implicitly allows traffic from that address family
479 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
480 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700481 * @throws IllegalArgumentException if the address is invalid.
482 * @see #addDnsServer(InetAddress)
483 */
484 public Builder addDnsServer(String address) {
485 return addDnsServer(InetAddress.parseNumericAddress(address));
486 }
487
488 /**
489 * Add a search domain to the DNS resolver.
490 */
491 public Builder addSearchDomain(String domain) {
492 if (mConfig.searchDomains == null) {
493 mConfig.searchDomains = new ArrayList<String>();
494 }
495 mConfig.searchDomains.add(domain);
496 return this;
497 }
498
499 /**
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700500 * Allows traffic from the specified address family.
501 *
502 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
503 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
504 * route or DNS server is added, that family is allowed.
505 *
506 * This method allows an address family to be unblocked even without adding an address,
507 * route or DNS server of that family. Traffic of that family will then typically
508 * fall-through to the underlying network if it's supported.
509 *
510 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
511 * {@link IllegalArgumentException} is thrown if it's neither.
512 *
513 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
514 *
515 * @return this {@link Builder} object to facilitate chaining of method calls.
516 */
517 public Builder allowFamily(int family) {
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -0700518 if (family == AF_INET) {
519 mConfig.allowIPv4 = true;
520 } else if (family == AF_INET6) {
521 mConfig.allowIPv6 = true;
522 } else {
523 throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
524 AF_INET6);
525 }
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700526 return this;
527 }
528
Paul Jensen0784eea2014-08-19 16:00:24 -0400529 private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
530 IPackageManager pm = IPackageManager.Stub.asInterface(
531 ServiceManager.getService("package"));
532 try {
533 pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
534 } catch (RemoteException e) {
535 throw new IllegalStateException(e);
536 }
537 }
538
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700539 /**
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700540 * Adds an application that's allowed to access the VPN connection.
541 *
542 * If this method is called at least once, only applications added through this method (and
543 * no others) are allowed access. Else (if this method is never called), all applications
Robert Greenwaltfc4f7212014-08-25 12:41:08 -0700544 * are allowed by default. If some applications are added, other, un-added applications
545 * will use networking as if the VPN wasn't running.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700546 *
547 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
548 * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
549 * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
550 *
551 * {@code packageName} must be the canonical name of a currently installed application.
552 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
553 *
554 * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
555 *
556 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
557 *
558 * @return this {@link Builder} object to facilitate chaining method calls.
559 */
560 public Builder addAllowedApplication(String packageName)
561 throws PackageManager.NameNotFoundException {
Paul Jensen0784eea2014-08-19 16:00:24 -0400562 if (mConfig.disallowedApplications != null) {
563 throw new UnsupportedOperationException("addDisallowedApplication already called");
564 }
565 verifyApp(packageName);
566 if (mConfig.allowedApplications == null) {
567 mConfig.allowedApplications = new ArrayList<String>();
568 }
569 mConfig.allowedApplications.add(packageName);
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700570 return this;
571 }
572
573 /**
574 * Adds an application that's denied access to the VPN connection.
575 *
576 * By default, all applications are allowed access, except for those denied through this
Robert Greenwaltfc4f7212014-08-25 12:41:08 -0700577 * method. Denied applications will use networking as if the VPN wasn't running.
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700578 *
579 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
580 * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
581 * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
582 *
583 * {@code packageName} must be the canonical name of a currently installed application.
584 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
585 *
586 * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
587 *
588 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
589 *
590 * @return this {@link Builder} object to facilitate chaining method calls.
591 */
592 public Builder addDisallowedApplication(String packageName)
593 throws PackageManager.NameNotFoundException {
Paul Jensen0784eea2014-08-19 16:00:24 -0400594 if (mConfig.allowedApplications != null) {
595 throw new UnsupportedOperationException("addAllowedApplication already called");
596 }
597 verifyApp(packageName);
598 if (mConfig.disallowedApplications == null) {
599 mConfig.disallowedApplications = new ArrayList<String>();
600 }
601 mConfig.disallowedApplications.add(packageName);
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700602 return this;
603 }
604
605 /**
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700606 * Allows all apps to bypass this VPN connection.
607 *
608 * By default, all traffic from apps is forwarded through the VPN interface and it is not
609 * possible for apps to side-step the VPN. If this method is called, apps may use methods
610 * such as {@link ConnectivityManager#setProcessDefaultNetwork} to instead send/receive
611 * directly over the underlying network or any other network they have permissions for.
612 *
613 * @return this {@link Builder} object to facilitate chaining of method calls.
614 */
615 public Builder allowBypass() {
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700616 mConfig.allowBypass = true;
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700617 return this;
618 }
619
620 /**
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700621 * Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
622 *
623 * By default, the file descriptor returned by {@link #establish} is non-blocking.
624 *
625 * @param blocking True to put the descriptor into blocking mode; false for non-blocking.
626 *
627 * @return this {@link Builder} object to facilitate chaining method calls.
628 */
629 public Builder setBlocking(boolean blocking) {
Jeff Davidson6bbf39c2014-07-23 10:14:53 -0700630 mConfig.blocking = blocking;
Sreeram Ramachandrancc26b4c2014-07-18 16:41:25 -0700631 return this;
632 }
633
634 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700635 * Create a VPN interface using the parameters supplied to this
636 * builder. The interface works on IP packets, and a file descriptor
637 * is returned for the application to access them. Each read
638 * retrieves an outgoing packet which was routed to the interface.
639 * Each write injects an incoming packet just like it was received
640 * from the interface. The file descriptor is put into non-blocking
641 * mode by default to avoid blocking Java threads. To use the file
642 * descriptor completely in native space, see
643 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
644 * close the file descriptor when the VPN connection is terminated.
645 * The VPN interface will be removed and the network will be
646 * restored by the system automatically.
647 *
648 * <p>To avoid conflicts, there can be only one active VPN interface
649 * at the same time. Usually network parameters are never changed
650 * during the lifetime of a VPN connection. It is also common for an
651 * application to create a new file descriptor after closing the
652 * previous one. However, it is rare but not impossible to have two
653 * interfaces while performing a seamless handover. In this case, the
654 * old interface will be deactivated when the new one is created
655 * successfully. Both file descriptors are valid but now outgoing
656 * packets will be routed to the new interface. Therefore, after
657 * draining the old file descriptor, the application MUST close it
658 * and start using the new file descriptor. If the new interface
659 * cannot be created, the existing interface and its file descriptor
660 * remain untouched.
661 *
662 * <p>An exception will be thrown if the interface cannot be created
663 * for any reason. However, this method returns {@code null} if the
664 * application is not prepared or is revoked. This helps solve
665 * possible race conditions between other VPN applications.
666 *
667 * @return {@link ParcelFileDescriptor} of the VPN interface, or
668 * {@code null} if the application is not prepared.
669 * @throws IllegalArgumentException if a parameter is not accepted
670 * by the operating system.
671 * @throws IllegalStateException if a parameter cannot be applied
672 * by the operating system.
673 * @throws SecurityException if the service is not properly declared
674 * in {@code AndroidManifest.xml}.
675 * @see VpnService
676 */
677 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700678 mConfig.addresses = mAddresses;
679 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700680
681 try {
682 return getService().establishVpn(mConfig);
683 } catch (RemoteException e) {
684 throw new IllegalStateException(e);
685 }
686 }
687 }
688}