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