Expiration of SSO session is detected in background operations (download, upload...
[pub/Android/ownCloud.git] / src / eu / alefzero / webdav / WebdavClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package eu.alefzero.webdav;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import org.apache.commons.httpclient.Credentials;
27 import org.apache.commons.httpclient.HttpClient;
28 import org.apache.commons.httpclient.HttpConnectionManager;
29 import org.apache.commons.httpclient.HttpException;
30 import org.apache.commons.httpclient.HttpMethod;
31 import org.apache.commons.httpclient.HttpMethodBase;
32 import org.apache.commons.httpclient.HttpVersion;
33 import org.apache.commons.httpclient.UsernamePasswordCredentials;
34 import org.apache.commons.httpclient.auth.AuthPolicy;
35 import org.apache.commons.httpclient.auth.AuthScope;
36 import org.apache.commons.httpclient.cookie.CookiePolicy;
37 import org.apache.commons.httpclient.methods.HeadMethod;
38 import org.apache.commons.httpclient.params.HttpMethodParams;
39 import org.apache.http.HttpStatus;
40 import org.apache.http.params.CoreProtocolPNames;
41
42 import com.owncloud.android.Log_OC;
43
44 import com.owncloud.android.authentication.AccountAuthenticator;
45 import com.owncloud.android.network.BearerAuthScheme;
46 import com.owncloud.android.network.BearerCredentials;
47
48 import android.accounts.AccountAuthenticatorActivity;
49 import android.net.Uri;
50
51 public class WebdavClient extends HttpClient {
52 private Uri mUri;
53 private Credentials mCredentials;
54 private boolean mFollowRedirects;
55 private String mSsoSessionCookie;
56 private String mAuthTokenType;
57 final private static String TAG = "WebdavClient";
58 public static final String USER_AGENT = "Android-ownCloud";
59
60 static private byte[] sExhaustBuffer = new byte[1024];
61
62 /**
63 * Constructor
64 */
65 public WebdavClient(HttpConnectionManager connectionMgr) {
66 super(connectionMgr);
67 Log_OC.d(TAG, "Creating WebdavClient");
68 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
69 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
70 mFollowRedirects = true;
71 mSsoSessionCookie = null;
72 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
73 }
74
75 public void setBearerCredentials(String accessToken) {
76 AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class);
77
78 List<String> authPrefs = new ArrayList<String>(1);
79 authPrefs.add(BearerAuthScheme.AUTH_POLICY);
80 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
81
82 mCredentials = new BearerCredentials(accessToken);
83 getState().setCredentials(AuthScope.ANY, mCredentials);
84 mSsoSessionCookie = null;
85 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
86 }
87
88 public void setBasicCredentials(String username, String password) {
89 List<String> authPrefs = new ArrayList<String>(1);
90 authPrefs.add(AuthPolicy.BASIC);
91 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
92
93 getParams().setAuthenticationPreemptive(true);
94 mCredentials = new UsernamePasswordCredentials(username, password);
95 getState().setCredentials(AuthScope.ANY, mCredentials);
96 mSsoSessionCookie = null;
97 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
98 }
99
100 public void setSsoSessionCookie(String accessToken) {
101 getParams().setAuthenticationPreemptive(false);
102 getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
103 mSsoSessionCookie = accessToken;
104 mCredentials = null;
105 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;
106 }
107
108
109 /**
110 * Check if a file exists in the OC server
111 *
112 * TODO replace with ExistenceOperation
113 *
114 * @return 'true' if the file exists; 'false' it doesn't exist
115 * @throws Exception When the existence could not be determined
116 */
117 public boolean existsFile(String path) throws IOException, HttpException {
118 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
119 try {
120 int status = executeMethod(head);
121 Log_OC.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
122 exhaustResponse(head.getResponseBodyAsStream());
123 return (status == HttpStatus.SC_OK);
124
125 } finally {
126 head.releaseConnection(); // let the connection available for other methods
127 }
128 }
129
130 /**
131 * Requests the received method with the received timeout (milliseconds).
132 *
133 * Executes the method through the inherited HttpClient.executedMethod(method).
134 *
135 * Sets the socket and connection timeouts only for the method received.
136 *
137 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
138 *
139 * @param method HTTP method request.
140 * @param readTimeout Timeout to set for data reception
141 * @param conntionTimout Timeout to set for connection establishment
142 */
143 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
144 int oldSoTimeout = getParams().getSoTimeout();
145 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
146 try {
147 if (readTimeout >= 0) {
148 method.getParams().setSoTimeout(readTimeout); // this should be enough...
149 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
150 }
151 if (connectionTimeout >= 0) {
152 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
153 }
154 return executeMethod(method);
155 } finally {
156 getParams().setSoTimeout(oldSoTimeout);
157 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
158 }
159 }
160
161
162 @Override
163 public int executeMethod(HttpMethod method) throws IOException, HttpException {
164 try {
165 method.setFollowRedirects(mFollowRedirects);
166 } catch (Exception e) {
167
168 }
169 if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
170 method.setRequestHeader("Cookie", mSsoSessionCookie);
171 }
172 return super.executeMethod(method);
173 }
174
175
176 /**
177 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
178 *
179 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
180 */
181 public void exhaustResponse(InputStream responseBodyAsStream) {
182 if (responseBodyAsStream != null) {
183 try {
184 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
185 responseBodyAsStream.close();
186
187 } catch (IOException io) {
188 Log_OC.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
189 }
190 }
191 }
192
193 /**
194 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
195 */
196 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
197 getParams().setSoTimeout(defaultDataTimeout);
198 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
199 }
200
201 /**
202 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
203 * @param uri
204 */
205 public void setBaseUri(Uri uri) {
206 mUri = uri;
207 }
208
209 public Uri getBaseUri() {
210 return mUri;
211 }
212
213 public final Credentials getCredentials() {
214 return mCredentials;
215 }
216
217 public final String getSsoSessionCookie() {
218 return mSsoSessionCookie;
219 }
220
221 public void setFollowRedirects(boolean followRedirects) {
222 mFollowRedirects = followRedirects;
223 }
224
225 public String getAuthTokenType() {
226 return mAuthTokenType;
227 }
228
229 }