InputStreamBinder.java 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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.ArrayList;
  55. import java.util.Arrays;
  56. import java.util.List;
  57. import java.util.Map;
  58. import static com.nextcloud.android.sso.Constants.EXCEPTION_ACCOUNT_NOT_FOUND;
  59. import static com.nextcloud.android.sso.Constants.EXCEPTION_INVALID_TOKEN;
  60. import static com.nextcloud.android.sso.Constants.EXCEPTION_UNSUPPORTED_METHOD;
  61. /**
  62. * Stream binder to pass usable InputStreams across the process boundary in Android.
  63. */
  64. public class InputStreamBinder extends IInputStreamService.Stub {
  65. private final static String TAG = "InputStreamBinder";
  66. private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json";
  67. private static final String CHARSET_UTF8 = "UTF-8";
  68. private static final int HTTP_STATUS_CODE_OK = 200;
  69. private static final char PATH_SEPARATOR = '/';
  70. private Context context;
  71. private List<String> validPackages = new ArrayList<>(Arrays.asList(
  72. "de.luhmer.owncloudnewsreader"
  73. //"it.niedermann.owncloud.notes"
  74. ));
  75. public InputStreamBinder(Context context) {
  76. this.context = context;
  77. }
  78. private NameValuePair[] convertMapToNVP(Map<String, String> map) {
  79. NameValuePair[] nvp = new NameValuePair[map.size()];
  80. int i = 0;
  81. for (String key : map.keySet()) {
  82. nvp[i] = new NameValuePair(key, map.get(key));
  83. i++;
  84. }
  85. return nvp;
  86. }
  87. public ParcelFileDescriptor performNextcloudRequest(ParcelFileDescriptor input) {
  88. // read the input
  89. final InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);
  90. Exception exception = null;
  91. InputStream httpStream = new InputStream() {
  92. @Override
  93. public int read() {
  94. return 0;
  95. }
  96. };
  97. try {
  98. // Start request and catch exceptions
  99. NextcloudRequest request = deserializeObjectAndCloseStream(is);
  100. httpStream = processRequest(request);
  101. } catch (Exception e) {
  102. Log_OC.e(TAG, e.getMessage());
  103. exception = e;
  104. }
  105. try {
  106. // Write exception to the stream followed by the actual network stream
  107. InputStream exceptionStream = serializeObjectToInputStream(exception);
  108. InputStream resultStream = new java.io.SequenceInputStream(exceptionStream, httpStream);
  109. return ParcelFileDescriptorUtil.pipeFrom(resultStream, thread -> Log.d(TAG, "Done sending result"));
  110. } catch (IOException e) {
  111. Log_OC.e(TAG, e.getMessage());
  112. }
  113. return null;
  114. }
  115. private <T extends Serializable> ByteArrayInputStream serializeObjectToInputStream(T obj) throws IOException {
  116. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  117. ObjectOutputStream oos = new ObjectOutputStream(baos);
  118. oos.writeObject(obj);
  119. oos.flush();
  120. oos.close();
  121. return new ByteArrayInputStream(baos.toByteArray());
  122. }
  123. private <T extends Serializable> T deserializeObjectAndCloseStream(InputStream is) throws IOException, ClassNotFoundException {
  124. ObjectInputStream ois = new ObjectInputStream(is);
  125. T result = (T) ois.readObject();
  126. is.close();
  127. ois.close();
  128. return result;
  129. }
  130. private InputStream processRequest(final NextcloudRequest request) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
  131. Account account = AccountUtils.getOwnCloudAccountByName(context, request.accountName); // TODO handle case that account is not found!
  132. if(account == null) {
  133. throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
  134. }
  135. // Validate token
  136. if (!isValid(request)) {
  137. throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
  138. }
  139. // Validate URL
  140. if(request.url.charAt(0) != PATH_SEPARATOR) {
  141. throw new IllegalStateException("URL need to start with a /");
  142. }
  143. OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
  144. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  145. OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);
  146. request.url = client.getBaseUri() + request.url;
  147. HttpMethodBase method;
  148. switch (request.method) {
  149. case "GET":
  150. method = new GetMethod(request.url);
  151. break;
  152. case "POST":
  153. method = new PostMethod(request.url);
  154. if (request.requestBody != null) {
  155. StringRequestEntity requestEntity = new StringRequestEntity(
  156. request.requestBody,
  157. CONTENT_TYPE_APPLICATION_JSON,
  158. CHARSET_UTF8);
  159. ((PostMethod) method).setRequestEntity(requestEntity);
  160. }
  161. break;
  162. case "PUT":
  163. method = new PutMethod(request.url);
  164. if (request.requestBody != null) {
  165. StringRequestEntity requestEntity = new StringRequestEntity(
  166. request.requestBody,
  167. CONTENT_TYPE_APPLICATION_JSON,
  168. CHARSET_UTF8);
  169. ((PutMethod) method).setRequestEntity(requestEntity);
  170. }
  171. break;
  172. case "DELETE":
  173. method = new DeleteMethod(request.url);
  174. break;
  175. default:
  176. throw new UnsupportedOperationException(EXCEPTION_UNSUPPORTED_METHOD);
  177. }
  178. method.setQueryString(convertMapToNVP(request.parameter));
  179. method.addRequestHeader("OCS-APIREQUEST", "true");
  180. int status = client.executeMethod(method);
  181. if (status == HTTP_STATUS_CODE_OK) {
  182. return method.getResponseBodyAsStream();
  183. } else {
  184. throw new IllegalStateException("Request returned code: " + status);
  185. }
  186. }
  187. private boolean isValid(NextcloudRequest request) {
  188. if(request.packageName == null) {
  189. String callingPackageName = context.getPackageManager().getNameForUid(Binder.getCallingUid());
  190. request.packageName = callingPackageName;
  191. }
  192. SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
  193. String storedToken = sharedPreferences.getString(request.packageName, "");
  194. return validPackages.contains(request.packageName) && request.token.equals(storedToken);
  195. }
  196. }