diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 29f6faa19..d791f5155 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -173,7 +173,18 @@ + android:configChanges="touchscreen|keyboard|keyboardHidden|orientation|screenLayout|screenSize"> + + + + + + + + + + + outbox, smtp_login, smtp_password, smtp_server, smtp_port, smtp_security_label, smtp_security, auth_method_label, auth_method" /> + + + + diff --git a/res/values/arrays.xml b/res/values/arrays.xml index 6452bccb4..420e8b610 100644 --- a/res/values/arrays.xml +++ b/res/values/arrays.xml @@ -201,4 +201,9 @@ Off + + Automatic + OAuth2 + + diff --git a/res/values/strings.xml b/res/values/strings.xml index 706724cdf..0f2b7d064 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -267,6 +267,9 @@ SMTP server SMTP port SMTP Security + Authorization method + Continue with simplified setup? + The entered e-mail-address supports a simplified setup (OAuth2).\n\nIn the next step, please allow Delta Chat to act as your Chat with E-Mail app.\n\nDelta Chat has no servers, your data stays on your device! For GMail Accounts you need to create an App-Password if you have 2FA enabled. If this setting is not available, you need to enable Less Secure Apps. Please enter a valid email address Please enter a valid server / IP address diff --git a/src/com/b44t/messenger/DcContext.java b/src/com/b44t/messenger/DcContext.java index 383a84b1a..d4bcb655e 100644 --- a/src/com/b44t/messenger/DcContext.java +++ b/src/com/b44t/messenger/DcContext.java @@ -31,6 +31,7 @@ public class DcContext { public final static int DC_EVENT_GET_STRING = 2091; public final static int DC_EVENT_GET_QUANTITIY_STRING = 2092; public final static int DC_EVENT_HTTP_GET = 2100; + public final static int DC_EVENT_HTTP_POST = 2110; public final static int DC_IMEX_EXPORT_SELF_KEYS = 1; public final static int DC_IMEX_IMPORT_SELF_KEYS = 2; @@ -55,6 +56,8 @@ public class DcContext { public final static int DC_QR_URL = 332; public final static int DC_QR_ERROR = 400; + public final static int DC_LP_AUTH_OAUTH2 = 0x2; + public final static int DC_LP_AUTH_NORMAL = 0x4; public final static int DC_LP_IMAP_SOCKET_STARTTLS = 0x100; public final static int DC_LP_IMAP_SOCKET_SSL = 0x200; public final static int DC_LP_IMAP_SOCKET_PLAIN = 0x400; @@ -91,6 +94,7 @@ public class DcContext { public native String getConfig (String key, String def); public int getConfigInt (String key, int def) { try{return Integer.parseInt(getConfig(key, Integer.toString(def)));} catch(Exception e) {} return 0; } public native String getInfo (); + public native String getOauth2Url (String addr, String redirectUrl); public native String initiateKeyTransfer (); public native boolean continueKeyTransfer (int msg_id, String setup_code); public native void imex (int what, String dir); diff --git a/src/org/thoughtcrime/securesms/RegistrationActivity.java b/src/org/thoughtcrime/securesms/RegistrationActivity.java index 6cbbedfda..0a066aa34 100644 --- a/src/org/thoughtcrime/securesms/RegistrationActivity.java +++ b/src/org/thoughtcrime/securesms/RegistrationActivity.java @@ -2,6 +2,7 @@ package org.thoughtcrime.securesms; import android.content.DialogInterface; import android.content.Intent; +import android.net.Uri; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; @@ -26,7 +27,13 @@ import com.b44t.messenger.DcEventCenter; import org.thoughtcrime.securesms.connect.ApplicationDcContext; import org.thoughtcrime.securesms.connect.DcHelper; import org.thoughtcrime.securesms.permissions.Permissions; +import org.thoughtcrime.securesms.util.IntentUtils; +import org.thoughtcrime.securesms.util.concurrent.ListenableFuture; +import org.thoughtcrime.securesms.util.concurrent.SettableFuture; import org.thoughtcrime.securesms.util.views.ProgressDialog; +import org.w3c.dom.Text; + +import java.util.concurrent.ExecutionException; import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_ADDRESS; import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_MAIL_PASSWORD; @@ -38,13 +45,6 @@ import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_SEND_PORT; import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_SEND_SERVER; import static org.thoughtcrime.securesms.connect.DcHelper.CONFIG_SEND_USER; -/** - * The register account activity. Prompts ths user for their registration information - * and begins the account registration process. - * - * @author Moxie Marlinspike - * @author Daniel Böhrs - */ public class RegistrationActivity extends BaseActionBarActivity implements DcEventCenter.DcEventDelegate { private enum VerificationType { @@ -63,52 +63,13 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve MenuItem loginMenuItem; Spinner imapSecurity; Spinner smtpSecurity; + Spinner authMethod; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.registration_activity); - initializeResources(); - DcHelper.getContext(this).eventCenter.addObserver(this, DcContext.DC_EVENT_CONFIGURE_PROGRESS); - } - - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - MenuInflater inflater = this.getMenuInflater(); - menu.clear(); - inflater.inflate(R.menu.registration, menu); - loginMenuItem = menu.findItem(R.id.do_register); - super.onPrepareOptionsMenu(menu); - return true; - } - - public boolean onOptionsItemSelected(MenuItem item) { - int id = item.getItemId(); - - if (id == R.id.do_register) { - onLogin(); - return true; - } else if (id == android.R.id.home) { - // handle close button click here - finish(); - return true; - } - return super.onOptionsItemSelected(item); - } - - @Override - public void onDestroy() { - super.onDestroy(); - DcHelper.getContext(this).eventCenter.removeObservers(this); - } - - @Override - public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { - Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults); - } - - private void initializeResources() { emailInput = findViewById(R.id.email_text); passwordInput = findViewById(R.id.password_text); advancedGroup = findViewById(R.id.advanced_group); @@ -121,6 +82,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve imapSecurity = findViewById(R.id.imap_security); smtpSecurity = findViewById(R.id.smtp_security); + authMethod = findViewById(R.id.auth_method); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { @@ -134,7 +96,6 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve imapPortInput.setOnFocusChangeListener((view, focused) -> focusListener(view, focused, VerificationType.PORT)); smtpServerInput.setOnFocusChangeListener((view, focused) -> focusListener(view, focused, VerificationType.SERVER)); smtpPortInput.setOnFocusChangeListener((view, focused) -> focusListener(view, focused, VerificationType.PORT)); -// loginButton.setOnClickListener(l -> onLogin()); advancedTextView.setOnClickListener(l -> onAdvancedSettings()); advancedIcon.setOnClickListener(l -> onAdvancedSettings()); advancedIcon.setRotation(45); @@ -166,7 +127,60 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve if((server_flags&DcContext.DC_LP_SMTP_SOCKET_STARTTLS)!=0) sel = 2; if((server_flags&DcContext.DC_LP_SMTP_SOCKET_PLAIN)!=0) sel = 3; smtpSecurity.setSelection(sel); + + sel = 0; + if((server_flags&DcContext.DC_LP_AUTH_OAUTH2)!=0) sel = 1; + authMethod.setSelection(sel); } + + DcHelper.getContext(this).eventCenter.addObserver(this, DcContext.DC_EVENT_CONFIGURE_PROGRESS); + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + MenuInflater inflater = this.getMenuInflater(); + menu.clear(); + inflater.inflate(R.menu.registration, menu); + loginMenuItem = menu.findItem(R.id.do_register); + super.onPrepareOptionsMenu(menu); + return true; + } + + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + + if (id == R.id.do_register) { + checkOauth2start().addListener(new ListenableFuture.Listener() { + @Override + public void onSuccess(Boolean oauth2started) { + if(!oauth2started) { + onLogin(); + } + } + + @Override + public void onFailure(ExecutionException e) { + onLogin(); + } + }); + return true; + } else if (id == android.R.id.home) { + // handle close button click here + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public void onDestroy() { + super.onDestroy(); + DcHelper.getContext(this).eventCenter.removeObservers(this); + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { + Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults); } private void focusListener(View view, boolean focused, VerificationType type) { @@ -175,6 +189,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve switch (type) { case EMAIL: verifyEmail(inputEditText); + checkOauth2start(); break; case SERVER: verifyServer(inputEditText); @@ -186,18 +201,70 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve } } - private void verifyEmail(TextInputEditText view) { - String error = getString(R.string.login_error_mail); - String email = view.getText().toString(); - if (!matchesEmailPattern(email)) { - view.setError(error); + private long oauth2Requested = 0; + + private ListenableFuture checkOauth2start() { + SettableFuture oauth2started = new SettableFuture<>(); + + String email = emailInput.getText().toString(); + if (!TextUtils.isEmpty(email) ) { + + // the redirect-uri is also used as intent-filter in the manifest + // and should be whitelisted by the supported oauth2 services + String redirectUrl = "chat.delta:/"+BuildConfig.APPLICATION_ID+"/auth"; + + String oauth2url = DcHelper.getContext(this).getOauth2Url(email, redirectUrl); + if (!TextUtils.isEmpty(oauth2url)) { + new AlertDialog.Builder(this) + .setTitle(R.string.login_info_oauth2_title) + .setMessage(R.string.login_info_oauth2_text) + .setNegativeButton(R.string.cancel, (dialog, which)->{ + if(isGmail(email)) { + showGmailNoOauth2Hint(); + } + oauth2started.set(false); + }) + .setPositiveButton(R.string.perm_continue, (dialog, which)-> { + // pass control to browser, we'll be back in business at (**) + oauth2Requested = System.currentTimeMillis(); + IntentUtils.showBrowserIntent(this, oauth2url); + oauth2started.set(true); + }) + .setCancelable(false) + .show(); + } else if (isGmail(email)) { + showGmailNoOauth2Hint(); + oauth2started.set(false); + } + else { + oauth2started.set(false); + } } - if (!TextUtils.isEmpty(email) && isGmail(email) && !gmailDialogShown) { - gmailDialogShown = true; - new AlertDialog.Builder(this) - .setMessage(R.string.login_info_gmail_text) - .setPositiveButton(R.string.ok, null) - .show(); + else { + oauth2started.set(false); + } + + return oauth2started; + } + + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + if(Intent.ACTION_VIEW.equals(intent.getAction())) { + Uri uri = intent.getData(); + String path = uri.getPath(); + if(!(path.startsWith("/"+BuildConfig.APPLICATION_ID)||path.startsWith("/auth")) + || System.currentTimeMillis()-oauth2Requested > 3*60*60*1000) { + return; // timeout after some hours or a request belonging to a bad path. + } + + // back in business after we passed control to the browser in (**) + String code = uri.getQueryParameter("code"); + if(!TextUtils.isEmpty(code)) { + passwordInput.setText(code); + authMethod.setSelection(1/*OAuth2*/); + onLogin(); + } } } @@ -209,6 +276,25 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve return email != null && (email.toLowerCase().contains("@gmail.") || email.toLowerCase().contains("@googlemail.")); } + private void showGmailNoOauth2Hint() + { + if(!gmailDialogShown) { + gmailDialogShown = true; + new AlertDialog.Builder(this) + .setMessage(R.string.login_info_gmail_text) + .setPositiveButton(R.string.ok, null) + .show(); + } + } + + private void verifyEmail(TextInputEditText view) { + String error = getString(R.string.login_error_mail); + String email = view.getText().toString(); + if (!matchesEmailPattern(email)) { + view.setError(error); + } + } + private void verifyServer(TextInputEditText view) { String error = getString(R.string.login_error_server); String server = view.getText().toString(); @@ -289,6 +375,7 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve if(smtpSecurity.getSelectedItemPosition()==1) server_flags |= DcContext.DC_LP_SMTP_SOCKET_SSL; if(smtpSecurity.getSelectedItemPosition()==2) server_flags |= DcContext.DC_LP_SMTP_SOCKET_STARTTLS; if(smtpSecurity.getSelectedItemPosition()==3) server_flags |= DcContext.DC_LP_SMTP_SOCKET_PLAIN; + if(authMethod.getSelectedItemPosition()==1) server_flags |= DcContext.DC_LP_AUTH_OAUTH2; DcHelper.getContext(this).setConfigInt("server_flags", server_flags); // calling configure() results in @@ -338,6 +425,4 @@ public class RegistrationActivity extends BaseActionBarActivity implements DcEve } } } - - } diff --git a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java index a0f8e9872..5d0c0df4e 100644 --- a/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java +++ b/src/org/thoughtcrime/securesms/connect/ApplicationDcContext.java @@ -36,9 +36,12 @@ import org.thoughtcrime.securesms.util.Util; import java.io.BufferedInputStream; import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; @@ -585,6 +588,7 @@ public class ApplicationDcContext extends DcContext { break; case DC_EVENT_HTTP_GET: + // calling this from the main thread may result in NetworkOnMainThreadException error String httpContent = null; try { URL url = new URL(dataToString(data1)); @@ -609,6 +613,50 @@ public class ApplicationDcContext extends DcContext { } return stringToData(httpContent); + case DC_EVENT_HTTP_POST: + // calling this from the main thread may result in NetworkOnMainThreadException error + String postContent = null; + try { + String urlStr = dataToString(data1); + String paramStr = ""; + if(urlStr.contains("?")) { + paramStr = urlStr.substring(urlStr.indexOf("?")+1); + urlStr = urlStr.substring(0, urlStr.indexOf("?")); + } + byte[] bytes = paramStr.getBytes(); + + URL url = new URL(urlStr); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + try { + conn.setConnectTimeout(15 * 1000); + conn.setReadTimeout(15 * 1000); + conn.setDoOutput(true); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); + conn.getOutputStream().write(bytes); + + int responseCode = conn.getResponseCode(); + BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream()))); + StringBuilder total = new StringBuilder(); + String line; + while ((line = br.readLine()) != null) { + total.append(line).append('\n'); + } + if (responseCode == HttpURLConnection.HTTP_OK) { + postContent = total.toString(); + } + else { + Log.i("DeltaChat", String.format("DC_EVENT_HTTP_POST error: %s", total.toString())); + } + } finally { + conn.disconnect(); + } + } catch (Exception e) { + e.printStackTrace(); + } + return stringToData(postContent); + case DC_EVENT_GET_STRING: String s; switch ((int) data1) { diff --git a/src/org/thoughtcrime/securesms/preferences/AdvancedPreferenceFragment.java b/src/org/thoughtcrime/securesms/preferences/AdvancedPreferenceFragment.java index cd420dd6d..8ba068af4 100644 --- a/src/org/thoughtcrime/securesms/preferences/AdvancedPreferenceFragment.java +++ b/src/org/thoughtcrime/securesms/preferences/AdvancedPreferenceFragment.java @@ -155,7 +155,7 @@ public class AdvancedPreferenceFragment extends CorrectedPreferenceFragment String app = context.getString(R.string.app_name); String version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; - return String.format("%s v%s", app, version); + return String.format("%s %s", app, version); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, e); return context.getString(R.string.app_name); diff --git a/standards.md b/standards.md index ff2fc2b01..f54bfae27 100644 --- a/standards.md +++ b/standards.md @@ -8,6 +8,7 @@ Transport | IMAP v4 ([RFC 3501](https://tools.ietf.org/ht Embedded media | MIME Document Series ([RFC 2045](https://tools.ietf.org/html/rfc2045), [RFC 2046](https://tools.ietf.org/html/rfc2046)), Content-Disposition Header ([RFC 2183](https://tools.ietf.org/html/rfc2183)), Multipart/Related ([RFC 2387](https://tools.ietf.org/html/rfc2387)) Identify server folders | IMAP LIST Extension ([RFC 6154](https://tools.ietf.org/html/rfc6154)) Push | IMAP IDLE ([RFC 2177](https://tools.ietf.org/html/rfc2177)) +Authorization | OAuth2 ([RFC 6749](https://tools.ietf.org/html/rfc6749)) End-to-end encryption | [Autocrypt Level 1](https://autocrypt.org/level1.html), OpenPGP ([RFC 4880](https://tools.ietf.org/html/rfc4880)) and Security Multiparts for MIME ([RFC 1847](https://tools.ietf.org/html/rfc1847)) Configuration assistance | [Autoconfigure](https://developer.mozilla.org/en-US/docs/Mozilla/Thunderbird/Autoconfiguration) and [Autodiscover](https://technet.microsoft.com/library/bb124251(v=exchg.150).aspx) Messenger functions | [Email-chat](https://github.com/deltachat/spec/blob/master/spec.md#email-chat-specification)