|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | +Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) |
| 5 | +See the file 'LICENSE' for copying permission |
| 6 | +""" |
| 7 | + |
| 8 | +""" |
| 9 | +Minimal pure-python ClickHouse client over its native HTTP interface (stdlib only, no clickhouse_connect). |
| 10 | +
|
| 11 | +ClickHouse exposes an HTTP endpoint that runs a query in the request body and streams the result back in a |
| 12 | +chosen format; we use TabSeparatedWithNames (first line = column names, then tab-separated rows with |
| 13 | +backslash escaping and \\N for NULL). Covers ClickHouse and its HTTP-compatible forks. |
| 14 | +""" |
| 15 | + |
| 16 | +import base64 |
| 17 | + |
| 18 | +try: |
| 19 | + from urllib.request import Request, urlopen # Python 3 |
| 20 | + from urllib.error import HTTPError, URLError |
| 21 | +except ImportError: |
| 22 | + from urllib2 import Request, urlopen, HTTPError, URLError # Python 2 |
| 23 | + |
| 24 | +from extra.dbwire import OperationalError |
| 25 | +from extra.dbwire import ProgrammingError |
| 26 | + |
| 27 | +def _unescape(value): |
| 28 | + if value == "\\N": |
| 29 | + return None |
| 30 | + if "\\" not in value: |
| 31 | + return value |
| 32 | + out, it = [], iter(range(len(value))) |
| 33 | + i = 0 |
| 34 | + n = len(value) |
| 35 | + while i < n: |
| 36 | + ch = value[i] |
| 37 | + if ch == "\\" and i + 1 < n: |
| 38 | + nxt = value[i + 1] |
| 39 | + out.append({"t": "\t", "n": "\n", "r": "\r", "0": "\0", "\\": "\\", "'": "'"}.get(nxt, nxt)) |
| 40 | + i += 2 |
| 41 | + else: |
| 42 | + out.append(ch) |
| 43 | + i += 1 |
| 44 | + return "".join(out) |
| 45 | + |
| 46 | +class Cursor(object): |
| 47 | + def __init__(self, connection): |
| 48 | + self.connection = connection |
| 49 | + self.description = None |
| 50 | + self.rowcount = -1 |
| 51 | + self._rows = [] |
| 52 | + self._pos = 0 |
| 53 | + |
| 54 | + def execute(self, query, params=None): |
| 55 | + if params is not None: |
| 56 | + raise ProgrammingError("parameter binding is not supported; pass a fully-formed query string") |
| 57 | + self.description, self.rowcount, self._rows, self._pos = None, -1, [], 0 |
| 58 | + self.description, self._rows = self.connection._query(query) |
| 59 | + self.rowcount = len(self._rows) |
| 60 | + return self |
| 61 | + |
| 62 | + def fetchall(self): |
| 63 | + retVal = self._rows[self._pos:] |
| 64 | + self._pos = len(self._rows) |
| 65 | + return retVal |
| 66 | + |
| 67 | + def fetchone(self): |
| 68 | + if self._pos >= len(self._rows): |
| 69 | + return None |
| 70 | + retVal = self._rows[self._pos] |
| 71 | + self._pos += 1 |
| 72 | + return retVal |
| 73 | + |
| 74 | + def close(self): |
| 75 | + self._rows = [] |
| 76 | + |
| 77 | +class Connection(object): |
| 78 | + def __init__(self, host, port, user, password, database, timeout): |
| 79 | + self._url = "http://%s:%d/?database=%s&default_format=TabSeparatedWithNames" % (host, port, database or "default") |
| 80 | + self._headers = {} |
| 81 | + if user or password: |
| 82 | + token = base64.b64encode(("%s:%s" % (user or "", password or "")).encode("utf-8")).decode("ascii") |
| 83 | + self._headers["Authorization"] = "Basic %s" % token |
| 84 | + self._timeout = timeout |
| 85 | + |
| 86 | + def cursor(self): |
| 87 | + return Cursor(self) |
| 88 | + |
| 89 | + def commit(self): |
| 90 | + pass # ClickHouse statements are executed immediately (no client-side transaction) |
| 91 | + |
| 92 | + def rollback(self): |
| 93 | + pass |
| 94 | + |
| 95 | + def close(self): |
| 96 | + pass # HTTP is stateless |
| 97 | + |
| 98 | + def _query(self, query): |
| 99 | + req = Request(self._url, data=query.encode("utf-8"), headers=self._headers) |
| 100 | + try: |
| 101 | + body = urlopen(req, timeout=self._timeout).read().decode("utf-8", "replace") |
| 102 | + except HTTPError as ex: |
| 103 | + raise ProgrammingError("(remote) %s" % ex.read().decode("utf-8", "replace").strip()) |
| 104 | + except URLError as ex: |
| 105 | + raise OperationalError("(remote) %s" % ex) |
| 106 | + |
| 107 | + if not body: |
| 108 | + return None, [] |
| 109 | + lines = body.split("\n") |
| 110 | + if lines and lines[-1] == "": |
| 111 | + lines.pop() |
| 112 | + if not lines: |
| 113 | + return None, [] |
| 114 | + description = [(name, None, None, None, None, None, None) for name in (_unescape(_) for _ in lines[0].split("\t"))] |
| 115 | + rows = [tuple(_unescape(_) for _ in line.split("\t")) for line in lines[1:]] |
| 116 | + return description, rows |
| 117 | + |
| 118 | +def connect(host=None, port=8123, user=None, password=None, database=None, connect_timeout=None, **kwargs): |
| 119 | + connection = Connection(host or "localhost", int(port or 8123), user, password, database, connect_timeout) |
| 120 | + try: |
| 121 | + connection._query("SELECT 1") # verify connectivity/credentials up front |
| 122 | + except ProgrammingError: |
| 123 | + raise |
| 124 | + except Exception as ex: |
| 125 | + raise OperationalError("could not connect to '%s:%s' (%s)" % (host, port, ex)) |
| 126 | + return connection |
0 commit comments