Test Failed
Push — master ( e380d0...f5671d )
by W
02:58
created

st2common/st2common/util/ip_utils.py (6 issues)

1
# Licensed to the Apache Software Foundation (ASF) under one or more
2
# contributor license agreements.  See the NOTICE file distributed with
3
# this work for additional information regarding copyright ownership.
4
# The ASF licenses this file to You under the Apache License, Version 2.0
5
# (the "License"); you may not use this file except in compliance with
6
# the License.  You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
from __future__ import absolute_import
17
import re
18
19
import ipaddr
20
from st2common.log import logging
21
22
LOG = logging.getLogger(__name__)
23
24
__all__ = [
25
    'is_ipv4',
26
    'is_ipv6',
27
    'split_host_port'
28
]
29
30
BRACKET_PATTERN = "^\[.*\]"  # IPv6 bracket pattern to specify port
0 ignored issues
show
A suspicious escape sequence \[ was found. Did you maybe forget to add an r prefix?

Escape sequences in Python are generally interpreted according to rules similar to standard C. Only if strings are prefixed with r or R are they interpreted as regular expressions.

The escape sequence that was used indicates that you might have intended to write a regular expression.

Learn more about the available escape sequences. in the Python documentation.

Loading history...
A suspicious escape sequence \] was found. Did you maybe forget to add an r prefix?

Escape sequences in Python are generally interpreted according to rules similar to standard C. Only if strings are prefixed with r or R are they interpreted as regular expressions.

The escape sequence that was used indicates that you might have intended to write a regular expression.

Learn more about the available escape sequences. in the Python documentation.

Loading history...
31
COMPILED_BRACKET_PATTERN = re.compile(BRACKET_PATTERN)
32
33
HOST_ONLY_IN_BRACKET = "^\[.*\]$"
0 ignored issues
show
A suspicious escape sequence \[ was found. Did you maybe forget to add an r prefix?

Escape sequences in Python are generally interpreted according to rules similar to standard C. Only if strings are prefixed with r or R are they interpreted as regular expressions.

The escape sequence that was used indicates that you might have intended to write a regular expression.

Learn more about the available escape sequences. in the Python documentation.

Loading history...
A suspicious escape sequence \] was found. Did you maybe forget to add an r prefix?

Escape sequences in Python are generally interpreted according to rules similar to standard C. Only if strings are prefixed with r or R are they interpreted as regular expressions.

The escape sequence that was used indicates that you might have intended to write a regular expression.

Learn more about the available escape sequences. in the Python documentation.

Loading history...
34
COMPILED_HOST_ONLY_IN_BRACKET_PATTERN = re.compile(HOST_ONLY_IN_BRACKET)
35
36
37
def is_ipv6(ip_str):
38
    """
39
    Validate whether given string is IPv6.
40
41
    :param ip_str: String to validate.
42
    :type ip_str: ``str``
43
44
    :rtype: ``bool``
45
    """
46
    try:
47
        addr = ipaddr.IPAddress(ip_str)
48
        return addr.version == 6
49
    except:
50
        return False
51
52
53
def is_ipv4(ip_str):
54
    """
55
    Validate whether given string is IPv4.
56
57
    :param ip_str: String to validate.
58
    :type ip_str: ``str``
59
60
    :rtype: ``bool``
61
    """
62
    try:
63
        addr = ipaddr.IPAddress(ip_str)
64
        return addr.version == 4
65
    except:
66
        return False
67
68
69
def split_host_port(host_str):
70
    """
71
    Split host_str into host and port.
72
    Can handle IPv4, IPv6, hostname inside or outside brackets.
73
74
    Note: If you want to specify a port with IPv6, you definitely
75
    should enclose IP address within [].
76
77
    :param host_str: Host port string.
78
    :type host_str: ``str``
79
80
    :return: Hostname (string), port (int) tuple. Raises exception on invalid port.
81
    :rtype: ``tuple`` of ``str`` and ``int``
82
    """
83
84
    hostname = host_str
85
    port = None
86
87
    # If it's simple IPv6 or IPv4 address, return here.
88
    if is_ipv6(host_str) or is_ipv4(host_str):
89
        return (hostname, port)
90
91
    # Check if it's square bracket style.
92
    match = COMPILED_BRACKET_PATTERN.match(host_str)
93
    if match:
94
        LOG.debug('Square bracket style.')
95
        # Check if square bracket style no port.
96
        match = COMPILED_HOST_ONLY_IN_BRACKET_PATTERN.match(host_str)
97
        if match:
98
            hostname = match.group().strip('[]')
99
            return (hostname, port)
100
101
        hostname, separator, port = hostname.rpartition(':')
102
        try:
103
            LOG.debug('host_str: %s, hostname: %s port: %s' % (host_str, hostname, port))
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
104
            port = int(port)
105
            hostname = hostname.strip('[]')
106
            return (hostname, port)
107
        except:
108
            raise Exception('Invalid port %s specified.' % port)
109
    else:
110
        LOG.debug('Non-bracket address. host_str: %s' % host_str)
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
111
        if ':' in host_str:
112
            LOG.debug('Non-bracket with port.')
113
            hostname, separator, port = hostname.rpartition(':')
114
            try:
115
                port = int(port)
116
                return (hostname, port)
117
            except:
118
                raise Exception('Invalid port %s specified.' % port)
119
120
    return (hostname, port)
121