InputStreamBinder.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * Nextcloud SingleSignOn
  3. *
  4. * @author David Luhmer
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. * More information here: https://github.com/abeluck/android-streams-ipc
  20. */
  21. package com.nextcloud.android.sso;
  22. import android.accounts.Account;
  23. import android.accounts.AuthenticatorException;
  24. import android.accounts.OperationCanceledException;
  25. import android.content.Context;
  26. import android.content.SharedPreferences;
  27. import android.os.Binder;
  28. import android.os.ParcelFileDescriptor;
  29. import android.util.Log;
  30. import com.nextcloud.android.sso.aidl.IInputStreamService;
  31. import com.nextcloud.android.sso.aidl.NextcloudRequest;
  32. import com.nextcloud.android.sso.aidl.ParcelFileDescriptorUtil;
  33. import com.owncloud.android.authentication.AccountUtils;
  34. import com.owncloud.android.db.PreferenceManager;
  35. import com.owncloud.android.lib.common.OwnCloudAccount;
  36. import com.owncloud.android.lib.common.OwnCloudClient;
  37. import com.owncloud.android.lib.common.OwnCloudClientManager;
  38. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  39. import com.owncloud.android.lib.common.utils.Log_OC;
  40. import org.apache.commons.httpclient.HttpMethodBase;
  41. import org.apache.commons.httpclient.NameValuePair;
  42. import org.apache.commons.httpclient.methods.DeleteMethod;
  43. import org.apache.commons.httpclient.methods.GetMethod;
  44. import org.apache.commons.httpclient.methods.PostMethod;
  45. import org.apache.commons.httpclient.methods.PutMethod;
  46. import org.apache.commons.httpclient.methods.StringRequestEntity;
  47. import java.io.ByteArrayInputStream;
  48. import java.io.ByteArrayOutputStream;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.ObjectInputStream;
  52. import java.io.ObjectOutputStream;
  53. import java.io.Serializable;
  54. import java.util.Map;
  55. import static com.nextcloud.android.sso.Constants.EXCEPTION_ACCOUNT_NOT_FOUND;
  56. import static com.nextcloud.android.sso.Constants.EXCEPTION_HTTP_REQUEST_FAILED;
  57. import static com.nextcloud.android.sso.Constants.EXCEPTION_INVALID_REQUEST_URL;
  58. import static com.nextcloud.android.sso.Constants.EXCEPTION_INVALID_TOKEN;
  59. import static com.nextcloud.android.sso.Constants.EXCEPTION_UNSUPPORTED_METHOD;
  60. /**
  61. * Stream binder to pass usable InputStreams across the process boundary in Android.
  62. */
  63. public class InputStreamBinder extends IInputStreamService.Stub {
  64. private final static String TAG = "InputStreamBinder";
  65. private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json";
  66. private static final String CHARSET_UTF8 = "UTF-8";
  67. private static final int HTTP_STATUS_CODE_OK = 200;
  68. private static final int HTTP_STATUS_CODE_MULTIPLE_CHOICES = 300;
  69. private static final char PATH_SEPARATOR = '/';
  70. private Context context;
  71. public InputStreamBinder(Context context) {
  72. this.context = context;
  73. }
  74. private NameValuePair[] convertMapToNVP(Map<String, String> map) {
  75. NameValuePair[] nvp = new NameValuePair[map.size()];
  76. int i = 0;
  77. for (String key : map.keySet()) {
  78. nvp[i] = new NameValuePair(key, map.get(key));
  79. i++;
  80. }
  81. return nvp;
  82. }
  83. public ParcelFileDescriptor performNextcloudRequest(ParcelFileDescriptor input) {
  84. // read the input
  85. final InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);
  86. Exception exception = null;
  87. InputStream httpStream = new InputStream() {
  88. @Override
  89. public int read() {
  90. return 0;
  91. }
  92. };
  93. try {
  94. // Start request and catch exceptions
  95. NextcloudRequest request = deserializeObjectAndCloseStream(is);
  96. httpStream = processRequest(request);
  97. } catch (Exception e) {
  98. Log_OC.e(TAG, e.getMessage());
  99. exception = e;
  100. }
  101. try {
  102. // Write exception to the stream followed by the actual network stream
  103. InputStream exceptionStream = serializeObjectToInputStream(exception);
  104. InputStream resultStream = new java.io.SequenceInputStream(exceptionStream, httpStream);
  105. return ParcelFileDescriptorUtil.pipeFrom(resultStream, thread -> Log.d(TAG, "Done sending result"));
  106. } catch (IOException e) {
  107. Log_OC.e(TAG, e.getMessage());
  108. }
  109. return null;
  110. }
  111. private <T extends Serializable> ByteArrayInputStream serializeObjectToInputStream(T obj) throws IOException {
  112. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  113. ObjectOutputStream oos = new ObjectOutputStream(baos);
  114. oos.writeObject(obj);
  115. oos.flush();
  116. oos.close();
  117. return new ByteArrayInputStream(baos.toByteArray());
  118. }
  119. private <T extends Serializable> T deserializeObjectAndCloseStream(InputStream is) throws IOException, ClassNotFoundException {
  120. ObjectInputStream ois = new ObjectInputStream(is);
  121. T result = (T) ois.readObject();
  122. is.close();
  123. ois.close();
  124. return result;
  125. }
  126. private InputStream processRequest(final NextcloudRequest request) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
  127. Account account = AccountUtils.getOwnCloudAccountByName(context, request.accountName); // TODO handle case that account is not found!
  128. if(account == null) {
  129. throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
  130. }
  131. // Validate token
  132. if (!isValid(request)) {
  133. throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
  134. }
  135. // Validate URL
  136. if(request.url.length() == 0 || request.url.charAt(0) != PATH_SEPARATOR) {
  137. throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL, new IllegalStateException("URL need to start with a /"));
  138. }
  139. OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
  140. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  141. OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);
  142. request.url = client.getBaseUri() + request.url;
  143. HttpMethodBase method;
  144. switch (request.method) {
  145. case "GET":
  146. method = new GetMethod(request.url);
  147. break;
  148. case "POST":
  149. method = new PostMethod(request.url);
  150. if (request.requestBody != null) {
  151. StringRequestEntity requestEntity = new StringRequestEntity(
  152. request.requestBody,
  153. CONTENT_TYPE_APPLICATION_JSON,
  154. CHARSET_UTF8);
  155. ((PostMethod) method).setRequestEntity(requestEntity);
  156. }
  157. break;
  158. case "PUT":
  159. method = new PutMethod(request.url);
  160. if (request.requestBody != null) {
  161. StringRequestEntity requestEntity = new StringRequestEntity(
  162. request.requestBody,
  163. CONTENT_TYPE_APPLICATION_JSON,
  164. CHARSET_UTF8);
  165. ((PutMethod) method).setRequestEntity(requestEntity);
  166. }
  167. break;
  168. case "DELETE":
  169. method = new DeleteMethod(request.url);
  170. break;
  171. default:
  172. throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD);
  173. }
  174. method.setQueryString(convertMapToNVP(request.parameter));
  175. method.addRequestHeader("OCS-APIREQUEST", "true");
  176. int status = client.executeMethod(method);
  177. // Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
  178. if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
  179. return method.getResponseBodyAsStream();
  180. } else {
  181. throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED, new IllegalStateException(String.valueOf(status)));
  182. }
  183. }
  184. private boolean isValid(NextcloudRequest request) {
  185. if(request.packageName == null) {
  186. String callingPackageName = context.getPackageManager().getNameForUid(Binder.getCallingUid());
  187. request.packageName = callingPackageName;
  188. }
  189. SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
  190. String storedToken = sharedPreferences.getString(request.packageName, "");
  191. return request.validateToken(storedToken);
  192. }
  193. }