Merge branch 'saml_based_federated_single_sign_on' into saml_based_federated_single_s...
[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.net.Uri;
49
50 public class WebdavClient extends HttpClient {
51 private Uri mUri;
52 private Credentials mCredentials;
53 private boolean mFollowRedirects;
54 private String mSsoSessionCookie;
55 private String mAuthTokenType;
56 final private static String TAG = "WebdavClient";
57 public static final String USER_AGENT = "Android-ownCloud";
58
59 static private byte[] sExhaustBuffer = new byte[1024];
60
61 /**
62 * Constructor
63 */
64 public WebdavClient(HttpConnectionManager connectionMgr) {
65 super(connectionMgr);
66 Log_OC.d(TAG, "Creating WebdavClient");
67 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
68 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
69 mFollowRedirects = true;
70 mSsoSessionCookie = null;
71 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
72 }
73
74 public void setBearerCredentials(String accessToken) {
75 AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class);
76
77 List<String> authPrefs = new ArrayList<String>(1);
78 authPrefs.add(BearerAuthScheme.AUTH_POLICY);
79 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
80
81 mCredentials = new BearerCredentials(accessToken);
82 getState().setCredentials(AuthScope.ANY, mCredentials);
83 mSsoSessionCookie = null;
84 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
85 }
86
87 public void setBasicCredentials(String username, String password) {
88 List<String> authPrefs = new ArrayList<String>(1);
89 authPrefs.add(AuthPolicy.BASIC);
90 getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
91
92 getParams().setAuthenticationPreemptive(true);
93 mCredentials = new UsernamePasswordCredentials(username, password);
94 getState().setCredentials(AuthScope.ANY, mCredentials);
95 mSsoSessionCookie = null;
96 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
97 }
98
99 public void setSsoSessionCookie(String accessToken) {
100 getParams().setAuthenticationPreemptive(false);
101 getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
102 mSsoSessionCookie = accessToken;
103 mCredentials = null;
104 mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;
105 }
106
107
108 /**
109 * Check if a file exists in the OC server
110 *
111 * TODO replace with ExistenceOperation
112 *
113 * @return 'true' if the file exists; 'false' it doesn't exist
114 * @throws Exception When the existence could not be determined
115 */
116 public boolean existsFile(String path) throws IOException, HttpException {
117 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
118 try {
119 int status = executeMethod(head);
120 Log_OC.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
121 exhaustResponse(head.getResponseBodyAsStream());
122 return (status == HttpStatus.SC_OK);
123
124 } finally {
125 head.releaseConnection(); // let the connection available for other methods
126 }
127 }
128
129 /**
130 * Requests the received method with the received timeout (milliseconds).
131 *
132 * Executes the method through the inherited HttpClient.executedMethod(method).
133 *
134 * Sets the socket and connection timeouts only for the method received.
135 *
136 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
137 *
138 * @param method HTTP method request.
139 * @param readTimeout Timeout to set for data reception
140 * @param conntionTimout Timeout to set for connection establishment
141 */
142 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
143 int oldSoTimeout = getParams().getSoTimeout();
144 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
145 try {
146 if (readTimeout >= 0) {
147 method.getParams().setSoTimeout(readTimeout); // this should be enough...
148 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
149 }
150 if (connectionTimeout >= 0) {
151 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
152 }
153 return executeMethod(method);
154 } finally {
155 getParams().setSoTimeout(oldSoTimeout);
156 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
157 }
158 }
159
160
161 @Override
162 public int executeMethod(HttpMethod method) throws IOException, HttpException {
163 try {
164 method.setFollowRedirects(mFollowRedirects);
165 } catch (Exception e) {
166
167 }
168 if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
169 method.setRequestHeader("Cookie", mSsoSessionCookie);
170 }
171 return super.executeMethod(method);
172 }
173
174
175 /**
176 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
177 *
178 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
179 */
180 public void exhaustResponse(InputStream responseBodyAsStream) {
181 if (responseBodyAsStream != null) {
182 try {
183 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
184 responseBodyAsStream.close();
185
186 } catch (IOException io) {
187 Log_OC.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
188 }
189 }
190 }
191
192 /**
193 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
194 */
195 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
196 getParams().setSoTimeout(defaultDataTimeout);
197 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
198 }
199
200 /**
201 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
202 * @param uri
203 */
204 public void setBaseUri(Uri uri) {
205 mUri = uri;
206 }
207
208 public Uri getBaseUri() {
209 return mUri;
210 }
211
212 public final Credentials getCredentials() {
213 return mCredentials;
214 }
215
216 public final String getSsoSessionCookie() {
217 return mSsoSessionCookie;
218 }
219
220 public void setFollowRedirects(boolean followRedirects) {
221 mFollowRedirects = followRedirects;
222 }
223
224 public String getAuthTokenType() {
225 return mAuthTokenType;
226 }
227
228 }