Repository: mozilla/bleach

Issue:
Linkify creates http link in mailto link when host contains a hyphen
Linkify creates http links **in** mailto links if the mail host name contains a hyphen `-` (and `parse_email=True`). The http link starts with the hyphen, even if host names mustn't start with hyphens at all (https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames).

```py
>>> linkify('foo@exa-mple.com', parse_email=True)
'<a href="mailto:foo@exa-mple.com">foo@exa<a href="http://-mple.com" rel="nofollow">-mple.com</a></a>'
```
This is what the link looks like: <a href="mailto:foo@exa-mple.com">foo@exa<a href="http://-mple.com" rel="nofollow">-mple.com</a></a> :smile:

Discussion:

Patch:
diff --git a/.gitignore b/.gitignore
index f5adb54..26bbdf8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,4 @@ build
 docs/_build/
 .cache/
 .eggs/
+.*env*/
diff --git a/bleach/linkifier.py b/bleach/linkifier.py
index 471ce93..c8d3340 100644
--- a/bleach/linkifier.py
+++ b/bleach/linkifier.py
@@ -349,7 +349,17 @@ class LinkifyFilter(Filter):
 
     def handle_links(self, src_iter):
         """Handle links in character tokens"""
+        in_a = False  # happens, if parse_email=True and if a mail was found
         for token in src_iter:
+            if in_a:
+                if token['type'] == 'EndTag' and token['name'] == 'a':
+                    in_a = False
+                yield token
+                continue
+            elif token['type'] == 'StartTag' and token['name'] == 'a':
+                in_a = True
+                yield token
+                continue
             if token['type'] == 'Characters':
                 text = token['data']
                 new_tokens = []
diff --git a/setup.py b/setup.py
old mode 100644
new mode 100755
index 1df9765..7e5c6ca
--- a/setup.py
+++ b/setup.py
@@ -1,3 +1,5 @@
+#!/usr/bin/env python
+
 import re
 import sys
 


Test patch:
diff --git a/tests/test_links.py b/tests/test_links.py
index b967151..3d44665 100644
--- a/tests/test_links.py
+++ b/tests/test_links.py
@@ -588,6 +588,14 @@ def test_hang():
     )
 
 
+def test_hyphen_in_mail():
+    """Test hyphens `-` in mails. Issue #300."""
+    assert (
+        linkify('ex@am-ple.com', parse_email=True) ==
+        '<a href="mailto:ex@am-ple.com">ex@am-ple.com</a>'
+    )
+
+
 def test_url_re_arg():
     """Verifies that a specified url_re is used"""
     fred_re = re.compile(r"""(fred\.com)""")