#!/usr/bin/env python3
"""
Minimal fake PostgreSQL server for reproducing postgres_fdw crashes on
malformed remote results.  Not a real server: it answers just enough of the
protocol for postgres_fdw to connect and send its queries.

Usage: fake_pg_server.py PORT [zero-rows|zero-cols] [password]

  EXPLAIN (get_remote_estimate(), with use_remote_estimate 'true'):
    zero-rows (default): RowDescription with one text column, no DataRow
    zero-cols:           RowDescription with no columns, no DataRow
    Both give PGRES_TUPLES_OK with PQntuples() == 0, so
    PQgetvalue(res, 0, 0) returns NULL.

  IMPORT FOREIGN SCHEMA (postgresImportForeignSchema()):
    the schema-existence check gets one row, and the column query gets one
    row with only two columns (relname, attname) instead of eight, so
    PQgetvalue(res, i, 3) returns NULL.

  password: ask for a cleartext password and accept any.  postgres_fdw
    requires the remote server to ask for a password when the local user is
    not a superuser.

Any other simple query gets a bare CommandComplete.
"""
import socket
import struct
import sys
import threading

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 55433
MODE = sys.argv[2] if len(sys.argv) > 2 else 'zero-rows'
ASK_PASSWORD = len(sys.argv) > 3 and sys.argv[3] == 'password'
TEXTOID = 25


def msg(kind, payload=b''):
    return kind + struct.pack('!I', len(payload) + 4) + payload


def cstr(s):
    return s.encode() + b'\0'


def recv_exact(sock, n):
    buf = b''
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))
        if not chunk:
            raise EOFError
        buf += chunk
    return buf


def result(columns, rows, tag):
    """RowDescription + DataRows (all text) + CommandComplete."""
    desc = struct.pack('!H', len(columns))
    for name in columns:
        # name, table OID, attnum, type OID, typlen, typmod, format code
        desc += cstr(name) + struct.pack('!IhIhih', 0, 0, TEXTOID, -1, -1, 0)
    out = msg(b'T', desc)
    for row in rows:
        data = struct.pack('!H', len(row))
        for value in row:
            data += struct.pack('!I', len(value)) + value.encode()
        out += msg(b'D', data)
    return out + msg(b'C', cstr(tag))


def answer(query):
    q = query.lstrip()
    if q.upper().startswith('EXPLAIN'):
        return result([] if MODE == 'zero-cols' else ['QUERY PLAN'], [], 'EXPLAIN')
    if q.startswith('SELECT 1 FROM pg_catalog.pg_namespace'):
        return result(['?column?'], [['1']], 'SELECT 1')
    if q.startswith('SELECT relname, '):
        return result(['relname', 'attname'], [['t', 'a']], 'SELECT 1')
    words = q.split()
    return msg(b'C', cstr(words[0].upper() if words else 'EMPTY'))


def handle(sock):
    status = b'I'
    try:
        while True:
            length, code = struct.unpack('!II', recv_exact(sock, 8))
            recv_exact(sock, length - 8)
            if code in (80877103, 80877104):    # SSLRequest, GSSENCRequest
                sock.sendall(b'N')
                continue
            break                               # StartupMessage

        if ASK_PASSWORD:
            sock.sendall(msg(b'R', struct.pack('!I', 3)))   # cleartext
            header = recv_exact(sock, 5)                    # PasswordMessage
            recv_exact(sock, struct.unpack('!I', header[1:])[0] - 4)

        out = msg(b'R', struct.pack('!I', 0))   # AuthenticationOk
        for key, value in [('server_version', '18.1'),
                           ('server_encoding', 'UTF8'),
                           ('client_encoding', 'UTF8'),
                           ('DateStyle', 'ISO, MDY'),
                           ('integer_datetimes', 'on'),
                           ('standard_conforming_strings', 'on'),
                           ('TimeZone', 'UTC')]:
            out += msg(b'S', cstr(key) + cstr(value))
        out += msg(b'K', struct.pack('!II', 4242, 4242))
        sock.sendall(out + msg(b'Z', b'I'))

        while True:
            header = recv_exact(sock, 5)
            kind = header[:1]
            body = recv_exact(sock, struct.unpack('!I', header[1:])[0] - 4)
            if kind == b'X':
                return
            if kind != b'Q':
                err = b'SERROR\0C0A000\0Monly simple queries are supported\0\0'
                sock.sendall(msg(b'E', err) + msg(b'Z', status))
                continue
            query = body.rstrip(b'\0').decode(errors='replace')
            print('query:', ' '.join(query.split())[:120], flush=True)
            first = query.split()[0].upper() if query.split() else ''
            if first in ('START', 'BEGIN'):
                status = b'T'
            elif first in ('COMMIT', 'ROLLBACK', 'ABORT'):
                status = b'I'
            sock.sendall(answer(query) + msg(b'Z', status))
    except (EOFError, ConnectionError):
        pass
    finally:
        sock.close()


def main():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('127.0.0.1', PORT))
    server.listen()
    print('fake server listening on 127.0.0.1:%d (%s%s)'
          % (PORT, MODE, ', password' if ASK_PASSWORD else ''), flush=True)
    while True:
        conn, _ = server.accept()
        threading.Thread(target=handle, args=(conn,), daemon=True).start()


if __name__ == '__main__':
    main()
