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