Skip to content

Commit

Permalink
Do not attempt to create link previews for .onion links.
Browse files Browse the repository at this point in the history
  • Loading branch information
greyson-signal committed Aug 17, 2020
1 parent 086b708 commit 3f7dd21
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import android.text.util.Linkify;

import com.annimon.stream.Stream;
import com.google.android.collect.Sets;

import org.thoughtcrime.securesms.stickers.StickerUrl;
import org.thoughtcrime.securesms.util.Util;
Expand All @@ -21,6 +22,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand All @@ -37,6 +39,8 @@ public final class LinkPreviewUtil {
private static final Pattern FAVICON_PATTERN = Pattern.compile("<\\s*link[^>]*rel\\s*=\\s*\".*icon.*\"[^>]*>");
private static final Pattern FAVICON_HREF_PATTERN = Pattern.compile("href\\s*=\\s*\"([^\"]*)\"");

private static final Set<String> INVALID_TOP_LEVEL_DOMAINS = Sets.newHashSet("onion");

/**
* @return All whitelisted URLs in the source text.
*/
Expand Down Expand Up @@ -72,11 +76,16 @@ public static boolean isLegalUrl(@NonNull String url) {
Matcher matcher = DOMAIN_PATTERN.matcher(url);

if (matcher.matches()) {
String domain = matcher.group(2);
String cleanedDomain = domain.replaceAll("\\.", "");
String domain = matcher.group(2);
String cleanedDomain = domain.replaceAll("\\.", "");
String topLevelDomain = parseTopLevelDomain(domain);

boolean validCharacters = ALL_ASCII_PATTERN.matcher(cleanedDomain).matches() ||
ALL_NON_ASCII_PATTERN.matcher(cleanedDomain).matches();

boolean validTopLevelDomain = !INVALID_TOP_LEVEL_DOMAINS.contains(topLevelDomain);

return ALL_ASCII_PATTERN.matcher(cleanedDomain).matches() ||
ALL_NON_ASCII_PATTERN.matcher(cleanedDomain).matches();
return validCharacters && validTopLevelDomain;
} else {
return false;
}
Expand Down Expand Up @@ -127,6 +136,17 @@ public static boolean isLegalUrl(@NonNull String url) {
return new OpenGraph(openGraphTags, htmlTitle, faviconUrl);
}

private static @Nullable String parseTopLevelDomain(@NonNull String domain) {
int periodIndex = domain.lastIndexOf(".");

if (periodIndex >= 0 && periodIndex < domain.length() - 1) {
return domain.substring(periodIndex + 1);
} else {
return null;
}
}


public static final class OpenGraph {

private final Map<String, String> values;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public static Collection<Object[]> data() {
{ "кц.com", false },
{ "http://asĸ.com", false },
{ "http://foo.кц.рф", false },
{ "https://abcdefg.onion", false },
{ "", false }
});
}
Expand Down

0 comments on commit 3f7dd21

Please sign in to comment.