File: HostPortExtractor.php

package info (click to toggle)
matomo 5.5.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 73,596 kB
  • sloc: php: 231,041; javascript: 102,286; python: 202; xml: 189; sh: 172; makefile: 20; sql: 10
file content (180 lines) | stat: -rw-r--r-- 6,137 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik\Plugins\Installation;

use InvalidArgumentException;

class HostPortExtractor
{
    public $host;
    public $port;

    private function __construct(string $host, string $port)
    {
        $this->host = $host;
        $this->port = $port;
    }

    /**
     * Extracts the correctly formatted host and port values from the user-provided
     * database server host.
     *
     * @param string $dbHost The user provided host to extract values from
     * @return HostPortExtractor|null Extracted Host and Port, null if nothing can be extracted
     */
    public static function extract(string $dbHost): ?HostPortExtractor
    {
        try {
            if (self::isIPv6($dbHost)) {
                return self::extractIPv6($dbHost);
            } elseif (self::isUnixSocket($dbHost)) {
                return self::extractUnixSocket($dbHost);
            } elseif (self::isIPWithPort($dbHost)) {
                return self::extractIPAndPort($dbHost);
            } else {
                return null;
            }
        } catch (InvalidArgumentException $e) {
            return null;
        }
    }

    /**
     * Determines if the provided host is correctly formatted IPv6
     *
     * @param string $dbHost The user provided database server host
     * @return boolean Whether the provided host is correct IPv6
     */
    private static function isIPv6(string $dbHost): bool
    {
        // filter_var requires potential IPv6 addresses to not be encased
        preg_match_all('/^\[(.*?)\]/', $dbHost, $matches);
        $listOfTextInsideSquareBrackets = $matches[1];

        /*
         * Only return true if there is some text inside square brackets,
         * and that text is considered valid IPv6 as per filter_var()
         */
        if (
            count($listOfTextInsideSquareBrackets) > 0 &&
            filter_var(
                $listOfTextInsideSquareBrackets[0],
                FILTER_VALIDATE_IP,
                FILTER_FLAG_IPV6
            ) !== false
        ) {
            return true;
        }
        return false;
    }

    /**
     * Extracts the Host and Port from a user provided database server host,
     * assuming the provided host is a IPv6 address, with or without a port
     *
     * @param string $dbHost The user provided database server host
     * @throws InvalidArgumentException if the provided dbHost is not a valid IPv6
     * @return HostPortExtractor The extracted Host & Port
     */
    private static function extractIPv6(string $dbHost): HostPortExtractor
    {
        if (!self::isIPv6($dbHost)) {
            throw new InvalidArgumentException('$dbHost must be a valid IPv6 address');
        }

        // find and extract the text inside square brackets: []
        preg_match_all('/\[(.*?)\]/', $dbHost, $matches);
        $listOfTextInsideSquareBrackets = $matches[1];

        $port = '';

        // extract text after closing bracket to search for port
        $components = explode(']', $dbHost);
        if (count($components) > 1 && strlen($components[1]) > 0) {
            // check if the text is a valid port e.g. ':3000'
            preg_match('/^:(\d+)$/', $components[1], $portMatches);
            if (count($portMatches) > 0) {
                $port = $portMatches[1];
            } else {
                throw new InvalidArgumentException('$dbHost port is invalid');
            }
        }
        // db connector requires IPv6 to be encased in square brackets
        $host = '[' . $listOfTextInsideSquareBrackets[0] . ']';

        return new HostPortExtractor($host, $port);
    }

    /**
     * Determines if the provided host is a Unix Socket
     *
     * @param string $dbHost The user provided database server host
     * @return boolean Whether the provided host is a unix socket
     */
    private static function isUnixSocket(string $dbHost): bool
    {
        return (strpos($dbHost, '/') !== false);
    }

    /**
     * Extracts the host & port from the user provided database server host,
     * assuming the provided host is a unix socket
     *
     * @param string $dbHost The user provided database server host
     * @throws InvalidArgumentException if the provided dbHost is not a valid Unix Socket
     * @return HostPortExtractor The extracted Host & Port
     */
    private static function extractUnixSocket(string $dbHost): HostPortExtractor
    {
        if (!self::isUnixSocket($dbHost)) {
            throw new InvalidArgumentException('$dbHost must be a valid Unix Socket');
        }

        /*
         * The DB connector requires unix sockets to be provided as ports in
         * order to connect successfully.
         */
        $portIndex = strpos($dbHost, '/');
        $port = substr($dbHost, $portIndex);

        return new HostPortExtractor('', $port);
    }

    /**
     * Determines if the provided host is a standard web address or IP with a port
     *
     * @param string $dbHost The user provided database server host
     * @return boolean Whether the provided host is a standard address or IP with port
     */
    private static function isIPWithPort(string $dbHost): bool
    {
        $numColons = substr_count($dbHost, ':');
        return ($numColons === 1);
    }

    /**
     * Extracts the host & port from the user provided database server host,
     * assuming the provided host is a standard address or IP with a port
     *
     * @param string $dbHost The user provided database server host
     * @throws InvalidArgumentException if the provided dbHost is not a valid address with a port
     * @return HostPortExtractor The extracted host & port
     */
    private static function extractIPAndPort(string $dbHost): HostPortExtractor
    {
        if (!self::isIPWithPort($dbHost)) {
            throw new InvalidArgumentException('$dbHost must be a valid address');
        }

        [$host, $port] = explode(':', $dbHost);

        return new HostPortExtractor($host, $port);
    }
}