blob: 5d61de22e9aca03177e657c385e9bafb342fffd8 [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;
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -070027import android.content.pm.PackageManager;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040028import android.net.NetworkUtils;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070029import android.os.Binder;
30import android.os.IBinder;
31import android.os.Parcel;
32import android.os.ParcelFileDescriptor;
33import android.os.RemoteException;
34import android.os.ServiceManager;
35
36import com.android.internal.net.VpnConfig;
37
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070038import java.net.DatagramSocket;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070039import java.net.Inet4Address;
40import java.net.Inet6Address;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070041import java.net.InetAddress;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070042import java.net.Socket;
43import java.util.ArrayList;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070044import java.util.List;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -070045
46/**
47 * VpnService is a base class for applications to extend and build their
48 * own VPN solutions. In general, it creates a virtual network interface,
49 * configures addresses and routing rules, and returns a file descriptor
50 * to the application. Each read from the descriptor retrieves an outgoing
51 * packet which was routed to the interface. Each write to the descriptor
52 * injects an incoming packet just like it was received from the interface.
53 * The interface is running on Internet Protocol (IP), so packets are
54 * always started with IP headers. The application then completes a VPN
55 * connection by processing and exchanging packets with the remote server
56 * over a tunnel.
57 *
58 * <p>Letting applications intercept packets raises huge security concerns.
59 * A VPN application can easily break the network. Besides, two of them may
60 * conflict with each other. The system takes several actions to address
61 * these issues. Here are some key points:
62 * <ul>
63 * <li>User action is required to create a VPN connection.</li>
64 * <li>There can be only one VPN connection running at the same time. The
65 * existing interface is deactivated when a new one is created.</li>
66 * <li>A system-managed notification is shown during the lifetime of a
67 * VPN connection.</li>
68 * <li>A system-managed dialog gives the information of the current VPN
69 * connection. It also provides a button to disconnect.</li>
70 * <li>The network is restored automatically when the file descriptor is
71 * closed. It also covers the cases when a VPN application is crashed
72 * or killed by the system.</li>
73 * </ul>
74 *
75 * <p>There are two primary methods in this class: {@link #prepare} and
76 * {@link Builder#establish}. The former deals with user action and stops
77 * the VPN connection created by another application. The latter creates
78 * a VPN interface using the parameters supplied to the {@link Builder}.
79 * An application must call {@link #prepare} to grant the right to use
80 * other methods in this class, and the right can be revoked at any time.
81 * Here are the general steps to create a VPN connection:
82 * <ol>
83 * <li>When the user press the button to connect, call {@link #prepare}
84 * and launch the returned intent.</li>
85 * <li>When the application becomes prepared, start the service.</li>
86 * <li>Create a tunnel to the remote server and negotiate the network
87 * parameters for the VPN connection.</li>
88 * <li>Supply those parameters to a {@link Builder} and create a VPN
89 * interface by calling {@link Builder#establish}.</li>
90 * <li>Process and exchange packets between the tunnel and the returned
91 * file descriptor.</li>
92 * <li>When {@link #onRevoke} is invoked, close the file descriptor and
93 * shut down the tunnel gracefully.</li>
94 * </ol>
95 *
96 * <p>Services extended this class need to be declared with appropriate
97 * permission and intent filter. Their access must be secured by
98 * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
99 * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
100 * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
101 * <pre>
102 * &lt;service android:name=".ExampleVpnService"
103 * android:permission="android.permission.BIND_VPN_SERVICE"&gt;
104 * &lt;intent-filter&gt;
105 * &lt;action android:name="android.net.VpnService"/&gt;
106 * &lt;/intent-filter&gt;
107 * &lt;/service&gt;</pre>
108 *
109 * @see Builder
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700110 */
111public class VpnService extends Service {
112
113 /**
114 * The action must be matched by the intent filter of this service. It also
115 * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
116 * permission so that other applications cannot abuse it.
117 */
118 public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
119
120 /**
121 * Use IConnectivityManager since those methods are hidden and not
122 * available in ConnectivityManager.
123 */
124 private static IConnectivityManager getService() {
125 return IConnectivityManager.Stub.asInterface(
126 ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
127 }
128
129 /**
130 * Prepare to establish a VPN connection. This method returns {@code null}
131 * if the VPN application is already prepared. Otherwise, it returns an
132 * {@link Intent} to a system activity. The application should launch the
133 * activity using {@link Activity#startActivityForResult} to get itself
134 * prepared. The activity may pop up a dialog to require user action, and
135 * the result will come back via its {@link Activity#onActivityResult}.
136 * If the result is {@link Activity#RESULT_OK}, the application becomes
137 * prepared and is granted to use other methods in this class.
138 *
139 * <p>Only one application can be granted at the same time. The right
140 * is revoked when another application is granted. The application
141 * losing the right will be notified via its {@link #onRevoke}. Unless
142 * it becomes prepared again, subsequent calls to other methods in this
143 * class will fail.
144 *
145 * @see #onRevoke
146 */
147 public static Intent prepare(Context context) {
148 try {
149 if (getService().prepareVpn(context.getPackageName(), null)) {
150 return null;
151 }
152 } catch (RemoteException e) {
153 // ignore
154 }
155 return VpnConfig.getIntentForConfirmation();
156 }
157
158 /**
Chad Brubakerbcf12b32014-02-11 14:18:56 -0800159 * Protect a socket from VPN connections. After protecting, data sent
160 * through this socket will go directly to the underlying network,
161 * so its traffic will not be forwarded through the VPN.
162 * This method is useful if some connections need to be kept
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700163 * outside of VPN. For example, a VPN tunnel should protect itself if its
164 * destination is covered by VPN routes. Otherwise its outgoing packets
165 * will be sent back to the VPN interface and cause an infinite loop. This
166 * method will fail if the application is not prepared or is revoked.
167 *
168 * <p class="note">The socket is NOT closed by this method.
169 *
170 * @return {@code true} on success.
171 */
172 public boolean protect(int socket) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400173 return NetworkUtils.protectFromVpn(socket);
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700174 }
175
176 /**
177 * Convenience method to protect a {@link Socket} from VPN connections.
178 *
179 * @return {@code true} on success.
180 * @see #protect(int)
181 */
182 public boolean protect(Socket socket) {
183 return protect(socket.getFileDescriptor$().getInt$());
184 }
185
186 /**
187 * Convenience method to protect a {@link DatagramSocket} from VPN
188 * connections.
189 *
190 * @return {@code true} on success.
191 * @see #protect(int)
192 */
193 public boolean protect(DatagramSocket socket) {
194 return protect(socket.getFileDescriptor$().getInt$());
195 }
196
197 /**
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700198 * Adds a network address to the VPN interface.
199 *
200 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
201 * address is already in use or cannot be assigned to the interface for any other reason.
202 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700203 * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
204 * be routed over the VPN. @see Builder#allowFamily
205 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700206 * @throws {@link IllegalArgumentException} if the address is invalid.
207 *
208 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
209 * @param prefixLength The prefix length of the address.
210 *
211 * @return {@code true} on success.
212 * @see Builder#addAddress
213 */
214 public boolean addAddress(InetAddress address, int prefixLength) {
215 // TODO
216 return true;
217 }
218
219 /**
220 * Removes a network address from the VPN interface.
221 *
222 * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
223 * address is not assigned to the VPN interface, or if it is the only address assigned (thus
224 * cannot be removed), or if the address cannot be removed for any other reason.
225 *
Sreeram Ramachandran13846052014-07-10 12:35:23 -0700226 * After removing an address, if there are no addresses, routes or DNS servers of a particular
227 * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
228 * family from being routed. In other words, once an address family has been allowed, it stays
229 * allowed for the rest of the VPN's session. @see Builder#allowFamily
230 *
Sreeram Ramachandran81c295e2014-07-09 23:21:25 -0700231 * @throws {@link IllegalArgumentException} if the address is invalid.
232 *
233 * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
234 * @param prefixLength The prefix length of the address.
235 *
236 * @return {@code true} on success.
237 */
238 public boolean removeAddress(InetAddress address, int prefixLength) {
239 // TODO
240 return true;
241 }
242
243 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700244 * Return the communication interface to the service. This method returns
245 * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
246 * action. Applications overriding this method must identify the intent
247 * and return the corresponding interface accordingly.
248 *
249 * @see Service#onBind
250 */
251 @Override
252 public IBinder onBind(Intent intent) {
253 if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
254 return new Callback();
255 }
256 return null;
257 }
258
259 /**
260 * Invoked when the application is revoked. At this moment, the VPN
261 * interface is already deactivated by the system. The application should
262 * close the file descriptor and shut down gracefully. The default
263 * implementation of this method is calling {@link Service#stopSelf()}.
264 *
265 * <p class="note">Calls to this method may not happen on the main thread
266 * of the process.
267 *
268 * @see #prepare
269 */
270 public void onRevoke() {
271 stopSelf();
272 }
273
274 /**
275 * Use raw Binder instead of AIDL since now there is only one usage.
276 */
277 private class Callback extends Binder {
278 @Override
279 protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
280 if (code == IBinder.LAST_CALL_TRANSACTION) {
281 onRevoke();
282 return true;
283 }
284 return false;
285 }
286 }
287
288 /**
289 * Helper class to create a VPN interface. This class should be always
290 * used within the scope of the outer {@link VpnService}.
291 *
292 * @see VpnService
293 */
294 public class Builder {
295
296 private final VpnConfig mConfig = new VpnConfig();
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700297 private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
298 private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700299
300 public Builder() {
301 mConfig.user = VpnService.this.getClass().getName();
302 }
303
304 /**
305 * Set the name of this session. It will be displayed in
306 * system-managed dialogs and notifications. This is recommended
307 * not required.
308 */
309 public Builder setSession(String session) {
310 mConfig.session = session;
311 return this;
312 }
313
314 /**
315 * Set the {@link PendingIntent} to an activity for users to
316 * configure the VPN connection. If it is not set, the button
317 * to configure will not be shown in system-managed dialogs.
318 */
319 public Builder setConfigureIntent(PendingIntent intent) {
320 mConfig.configureIntent = intent;
321 return this;
322 }
323
324 /**
325 * Set the maximum transmission unit (MTU) of the VPN interface. If
326 * it is not set, the default value in the operating system will be
327 * used.
328 *
329 * @throws IllegalArgumentException if the value is not positive.
330 */
331 public Builder setMtu(int mtu) {
332 if (mtu <= 0) {
333 throw new IllegalArgumentException("Bad mtu");
334 }
335 mConfig.mtu = mtu;
336 return this;
337 }
338
339 /**
340 * Private method to validate address and prefixLength.
341 */
342 private void check(InetAddress address, int prefixLength) {
343 if (address.isLoopbackAddress()) {
344 throw new IllegalArgumentException("Bad address");
345 }
346 if (address instanceof Inet4Address) {
347 if (prefixLength < 0 || prefixLength > 32) {
348 throw new IllegalArgumentException("Bad prefixLength");
349 }
350 } else if (address instanceof Inet6Address) {
351 if (prefixLength < 0 || prefixLength > 128) {
352 throw new IllegalArgumentException("Bad prefixLength");
353 }
354 } else {
355 throw new IllegalArgumentException("Unsupported family");
356 }
357 }
358
359 /**
360 * Add a network address to the VPN interface. Both IPv4 and IPv6
361 * addresses are supported. At least one address must be set before
362 * calling {@link #establish}.
363 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700364 * Adding an address implicitly allows traffic from that address family
365 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
366 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700367 * @throws IllegalArgumentException if the address is invalid.
368 */
369 public Builder addAddress(InetAddress address, int prefixLength) {
370 check(address, prefixLength);
371
372 if (address.isAnyLocalAddress()) {
373 throw new IllegalArgumentException("Bad address");
374 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700375 mAddresses.add(new LinkAddress(address, prefixLength));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700376 return this;
377 }
378
379 /**
380 * Convenience method to add a network address to the VPN interface
381 * using a numeric address string. See {@link InetAddress} for the
382 * definitions of numeric address formats.
383 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700384 * Adding an address implicitly allows traffic from that address family
385 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
386 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700387 * @throws IllegalArgumentException if the address is invalid.
388 * @see #addAddress(InetAddress, int)
389 */
390 public Builder addAddress(String address, int prefixLength) {
391 return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
392 }
393
394 /**
395 * Add a network route to the VPN interface. Both IPv4 and IPv6
396 * routes are supported.
397 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700398 * Adding a route implicitly allows traffic from that address family
399 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
400 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700401 * @throws IllegalArgumentException if the route is invalid.
402 */
403 public Builder addRoute(InetAddress address, int prefixLength) {
404 check(address, prefixLength);
405
406 int offset = prefixLength / 8;
407 byte[] bytes = address.getAddress();
408 if (offset < bytes.length) {
409 for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
410 if (bytes[offset] != 0) {
411 throw new IllegalArgumentException("Bad address");
412 }
413 }
414 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700415 mRoutes.add(new RouteInfo(new LinkAddress(address, prefixLength), null));
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700416 return this;
417 }
418
419 /**
420 * Convenience method to add a network route to the VPN interface
421 * using a numeric address string. See {@link InetAddress} for the
422 * definitions of numeric address formats.
423 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700424 * Adding a route implicitly allows traffic from that address family
425 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
426 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700427 * @throws IllegalArgumentException if the route is invalid.
428 * @see #addRoute(InetAddress, int)
429 */
430 public Builder addRoute(String address, int prefixLength) {
431 return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
432 }
433
434 /**
435 * Add a DNS server to the VPN connection. Both IPv4 and IPv6
436 * addresses are supported. If none is set, the DNS servers of
437 * the default network will be used.
438 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700439 * Adding a server implicitly allows traffic from that address family
440 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
441 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700442 * @throws IllegalArgumentException if the address is invalid.
443 */
444 public Builder addDnsServer(InetAddress address) {
445 if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
446 throw new IllegalArgumentException("Bad address");
447 }
448 if (mConfig.dnsServers == null) {
449 mConfig.dnsServers = new ArrayList<String>();
450 }
451 mConfig.dnsServers.add(address.getHostAddress());
452 return this;
453 }
454
455 /**
456 * Convenience method to add a DNS server to the VPN connection
457 * using a numeric address string. See {@link InetAddress} for the
458 * definitions of numeric address formats.
459 *
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700460 * Adding a server implicitly allows traffic from that address family
461 * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
462 *
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700463 * @throws IllegalArgumentException if the address is invalid.
464 * @see #addDnsServer(InetAddress)
465 */
466 public Builder addDnsServer(String address) {
467 return addDnsServer(InetAddress.parseNumericAddress(address));
468 }
469
470 /**
471 * Add a search domain to the DNS resolver.
472 */
473 public Builder addSearchDomain(String domain) {
474 if (mConfig.searchDomains == null) {
475 mConfig.searchDomains = new ArrayList<String>();
476 }
477 mConfig.searchDomains.add(domain);
478 return this;
479 }
480
481 /**
Sreeram Ramachandrand7e71642014-07-09 23:01:30 -0700482 * Allows traffic from the specified address family.
483 *
484 * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
485 * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
486 * route or DNS server is added, that family is allowed.
487 *
488 * This method allows an address family to be unblocked even without adding an address,
489 * route or DNS server of that family. Traffic of that family will then typically
490 * fall-through to the underlying network if it's supported.
491 *
492 * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
493 * {@link IllegalArgumentException} is thrown if it's neither.
494 *
495 * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
496 *
497 * @return this {@link Builder} object to facilitate chaining of method calls.
498 */
499 public Builder allowFamily(int family) {
500 // TODO
501 return this;
502 }
503
504 /**
Sreeram Ramachandran633f0e82014-07-09 21:11:12 -0700505 * Adds an application that's allowed to access the VPN connection.
506 *
507 * If this method is called at least once, only applications added through this method (and
508 * no others) are allowed access. Else (if this method is never called), all applications
509 * are allowed by default.
510 *
511 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
512 * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
513 * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
514 *
515 * {@code packageName} must be the canonical name of a currently installed application.
516 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
517 *
518 * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
519 *
520 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
521 *
522 * @return this {@link Builder} object to facilitate chaining method calls.
523 */
524 public Builder addAllowedApplication(String packageName)
525 throws PackageManager.NameNotFoundException {
526 // TODO
527 return this;
528 }
529
530 /**
531 * Adds an application that's denied access to the VPN connection.
532 *
533 * By default, all applications are allowed access, except for those denied through this
534 * method.
535 *
536 * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
537 * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
538 * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
539 *
540 * {@code packageName} must be the canonical name of a currently installed application.
541 * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
542 *
543 * @throws {@link PackageManager.NameNotFoundException} If the application isn't installed.
544 *
545 * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
546 *
547 * @return this {@link Builder} object to facilitate chaining method calls.
548 */
549 public Builder addDisallowedApplication(String packageName)
550 throws PackageManager.NameNotFoundException {
551 // TODO
552 return this;
553 }
554
555 /**
Sreeram Ramachandrana9294eb2014-07-09 21:43:03 -0700556 * Allows all apps to bypass this VPN connection.
557 *
558 * By default, all traffic from apps is forwarded through the VPN interface and it is not
559 * possible for apps to side-step the VPN. If this method is called, apps may use methods
560 * such as {@link ConnectivityManager#setProcessDefaultNetwork} to instead send/receive
561 * directly over the underlying network or any other network they have permissions for.
562 *
563 * @return this {@link Builder} object to facilitate chaining of method calls.
564 */
565 public Builder allowBypass() {
566 // TODO
567 return this;
568 }
569
570 /**
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700571 * Create a VPN interface using the parameters supplied to this
572 * builder. The interface works on IP packets, and a file descriptor
573 * is returned for the application to access them. Each read
574 * retrieves an outgoing packet which was routed to the interface.
575 * Each write injects an incoming packet just like it was received
576 * from the interface. The file descriptor is put into non-blocking
577 * mode by default to avoid blocking Java threads. To use the file
578 * descriptor completely in native space, see
579 * {@link ParcelFileDescriptor#detachFd()}. The application MUST
580 * close the file descriptor when the VPN connection is terminated.
581 * The VPN interface will be removed and the network will be
582 * restored by the system automatically.
583 *
584 * <p>To avoid conflicts, there can be only one active VPN interface
585 * at the same time. Usually network parameters are never changed
586 * during the lifetime of a VPN connection. It is also common for an
587 * application to create a new file descriptor after closing the
588 * previous one. However, it is rare but not impossible to have two
589 * interfaces while performing a seamless handover. In this case, the
590 * old interface will be deactivated when the new one is created
591 * successfully. Both file descriptors are valid but now outgoing
592 * packets will be routed to the new interface. Therefore, after
593 * draining the old file descriptor, the application MUST close it
594 * and start using the new file descriptor. If the new interface
595 * cannot be created, the existing interface and its file descriptor
596 * remain untouched.
597 *
598 * <p>An exception will be thrown if the interface cannot be created
599 * for any reason. However, this method returns {@code null} if the
600 * application is not prepared or is revoked. This helps solve
601 * possible race conditions between other VPN applications.
602 *
603 * @return {@link ParcelFileDescriptor} of the VPN interface, or
604 * {@code null} if the application is not prepared.
605 * @throws IllegalArgumentException if a parameter is not accepted
606 * by the operating system.
607 * @throws IllegalStateException if a parameter cannot be applied
608 * by the operating system.
609 * @throws SecurityException if the service is not properly declared
610 * in {@code AndroidManifest.xml}.
611 * @see VpnService
612 */
613 public ParcelFileDescriptor establish() {
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700614 mConfig.addresses = mAddresses;
615 mConfig.routes = mRoutes;
Chia-chi Yeh199ed6e2011-08-03 17:38:49 -0700616
617 try {
618 return getService().establishVpn(mConfig);
619 } catch (RemoteException e) {
620 throw new IllegalStateException(e);
621 }
622 }
623 }
624}