-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmicropg_superlite.py
195 lines (177 loc) · 9.16 KB
/
micropg_superlite.py
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#############################################################################
# The MIT License (MIT)
#
# Copyright (c) 2014-2019, 2021-2024 Hajime Nakagami (micropg)
# Copyright (c) 2023-2025 TimonW-Dev, BetaFloof, MikeRoth93 (micropg_lite based on micropg)
# Copyright (c) 2025 TimonW-Dev (micropg_superlite based on micropg_lite)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##############################################################################
# PostgreSQL driver for micropython https://github.com/micropython/micropython but it's more lightweight and made for ESP8266
# It's a micropg (https://github.com/nakagami/micropg) subset.
# micropg (https://github.com/nakagami/micropg) a minipg (https://github.com/nakagami/minipg) subset.
##############################################################################
### Version 1.0.0
import hashlib, socket, binascii, random
# -----------------------------------------------------------------------------
def raiseExceptionLostConnection():
raise Exception("08003:Lost connection")
def hmac_sha256_digest(key, msg):
pad_key = key + b'\x00' * (64 - len(key) % 64)
return hashlib.sha256(bytes(0x5c ^ b for b in pad_key) + hashlib.sha256(bytes(0x36 ^ b for b in pad_key) + msg).digest()).digest()
class Cursor:
def __init__(self, connection):
self.connection = connection
def execute(self, q, a=()):
if not self.connection or not bool(self.connection.sock): raiseExceptionLostConnection()
self._rows = []
if a: q = q.replace('%', '%%').replace('%%s', '%s') % tuple(('NULL' if i is None else "'" + i.replace("'", "''") + "'" if isinstance(i, str) else "'" + ''.join(['\\%03o' % c for c in i]) + "'" for i in a))
self.connection.execute(q, self)
def fetchall(self):
rows = self._rows
self._rows = []
return rows
def close(self):
self.connection = None
class connect:
def __init__(self, host, user, password, database, port=5432):
self.user = user
self.password = password
self.database = database
self.host = host
self.port = port
self.encoding = 'UTF8'
self._ready_for_query = b'I'
# Inlined _open() function
self.sock = socket.socket()
self.sock.connect(socket.getaddrinfo(self.host, self.port)[0][-1])
v = b'\x00\x03\x00\x00user\x00' + self.user.encode('ascii') + b'\x00'
if self.database: v += b'database\x00' + self.database.encode('ascii') + b'\x00'
v += b'\x00'
self._write((len(v) + 4).to_bytes(4, 'big') + v)
self._process_messages(None)
def _send_message(self, message, data):
self._write(b''.join([message, (len(data) + 4).to_bytes(4, 'big'), data, b'H\x00\x00\x00\x04']))
def _process_messages(self, obj):
while True:
try: code = ord(self._read(1))
except: raiseExceptionLostConnection()
data = self._read(int.from_bytes(self._read(4), 'big') - 4)
if code == 90:
self._ready_for_query = data
break
elif code == 82:
nonce = str(random.getrandbits(32))
first = f'n,,n=,r={nonce}'.encode('utf-8')
msg = b'SCRAM-SHA-256\x00' + (len(first)).to_bytes(4, 'big') + first
self._write(b'p' + (len(msg) + 4).to_bytes(4, 'big') + msg)
assert ord(self._read(1)) == 82
data = self._read(int.from_bytes(self._read(4), 'big') - 4)
server = dict(kv.split('=', 1) for kv in data[4:].decode('utf-8').split(','))
pw_bytes = self.password.encode('utf-8')
iters = int(server['i'])
u1 = hmac_sha256_digest(pw_bytes, binascii.a2b_base64(server['s']) + b'\x00\x00\x00\x01')
ui = int.from_bytes(u1, 'big')
for _ in range(iters - 1):
u1 = hmac_sha256_digest(pw_bytes, u1)
ui ^= int.from_bytes(u1, 'big')
client_key = hmac_sha256_digest(ui.to_bytes(32, 'big'), b"Client Key")
auth_msg = f"n=,r={nonce},r={server['r']},s={server['s']},i={server['i']},c=biws,r={server['r']}"
proof = binascii.b2a_base64(bytes(x ^ y for x, y in zip(client_key, hmac_sha256_digest(hashlib.sha256(client_key).digest(), auth_msg.encode('utf-8'))))).rstrip(b'\n')
final = f"c=biws,r={server['r']},p={proof.decode('utf-8')}".encode('utf-8')
self._write(b'p' + (len(final) + 4).to_bytes(4, 'big') + final)
for _ in range(3):
assert ord(self._read(1)) == 82
data = self._read(int.from_bytes(self._read(4), 'big') - 4)
if int.from_bytes(data[:4], 'big') == 0: break
elif code == 67 and obj:
parts = data[:-1].decode('ascii').split()
if parts and parts[-1].isdigit(): obj._rowcount = int(parts[-1])
elif code == 84 and obj:
count = int.from_bytes(data[:2], 'big')
obj.description = [None] * count
n = 2
for i in range(count):
name_end = data.index(b'\x00', n)
name = data[n:name_end]
n = name_end + 1
try: name = name.decode(self.encoding)
except: pass
type_code = int.from_bytes(data[n+6:n+10], 'big')
size, precision, scale = int.from_bytes(data[n+10:n+12], 'big'), -1, -1
obj.description[i] = (name, type_code, None, size, precision, scale, None)
n += 18
elif code == 68 and obj:
n, row = 2, []
while n < len(data):
if data[n:n+4] == b'\xff\xff\xff\xff': row.append(None); n += 4
else:
ln = int.from_bytes(data[n:n+4], 'big')
col_data = data[n+4:n+4+ln]
col_oid = obj.description[len(row)][1]
decoded_data = col_data.decode(self.encoding) if col_data else None
if col_oid == 16: decoded_data = (decoded_data == 't')
elif col_oid in (21, 23, 20, 26): decoded_data = int(decoded_data)
elif col_oid in (700, 701): decoded_data = float(decoded_data)
row.append(decoded_data)
n += ln + 4
obj._rows.append(tuple(row))
elif code == 69: raiseExceptionLostConnection()
elif code == 100: obj.write(data)
elif code == 71:
while True:
buf = obj.read(8192)
if not buf: break
self._write(b'd' + (len(buf) + 4).to_bytes(4, 'big') + buf)
self._write(b'c\x00\x00\x00\x04S\x00\x00\x00\x04')
def _read(self, ln):
if not self.sock: raiseExceptionLostConnection()
r = bytearray(ln)
pos = 0
while pos < ln:
chunk = self.sock.read(ln - pos) if hasattr(self.sock, "read") else self.sock.recv(ln - pos)
if not chunk: raiseExceptionLostConnection()
r[pos:pos+len(chunk)] = chunk
pos += len(chunk)
return bytes(r)
def _write(self, b):
if not self.sock:
raiseExceptionLostConnection()
pos = 0
while pos < len(b):
pos += self.sock.write(b[pos:]) if hasattr(self.sock, "write") else self.sock.send(b[pos:])
def cursor(self):
return Cursor(self)
def execute(self, query, obj=None):
if self._ready_for_query != b'T':
self._send_message(b'Q', b"BEGIN\x00")
self._process_messages(None)
self._send_message(b'Q', query.encode(self.encoding) + b'\x00')
self._process_messages(obj)
# Commit
if self.sock:
self._send_message(b'Q', b"COMMIT\x00")
self._process_messages(None)
self._send_message(b'Q', b"BEGIN\x00")
self._process_messages(None)
def close(self):
if self.sock:
self._write(b'X\x00\x00\x00\x04')
self.sock.close()
self.sock = None