import socket,struct,time
def enc(p):
    r=b''
    for k,v in p.items():
        for b in (k.encode(),v.encode()):
            if len(b)<128: r+=struct.pack('B',len(b))
            else: r+=struct.pack('!I',len(b)|0x80000000)
        r+=k.encode()+v.encode()
    return r
def rd(s,t=1.0):
    s.settimeout(t)
    try:
        d=s.recv(65536)
        print('   recv ->',repr(d[:200]))
        return d
    except socket.timeout:
        print('   recv TIMEOUT'); return None
    except Exception as e:
        print('   recv EXC',repr(e)); return None
p={'GATEWAY_INTERFACE':'CGI/1.1','REQUEST_METHOD':'GET','SCRIPT_FILENAME':'/tmp/t1.php','SCRIPT_NAME':'/x.php','REQUEST_URI':'/x.php','QUERY_STRING':'','SERVER_PROTOCOL':'HTTP/1.1','REMOTE_ADDR':'127.0.0.1','SERVER_NAME':'localhost','SERVER_PORT':'80','SERVER_ADDR':'127.0.0.1','REDIRECT_STATUS':'200','DOCUMENT_ROOT':'/','HTTP_HOST':'localhost'}
begin=struct.pack('!BBHH',1,1,1,8)+struct.pack('!HB',1,0)+b'\x00'*5
pd=enc(p)
try:
    s=socket.create_connection(('127.0.0.1',9000),4)
    print('connected')
    s.sendall(begin); print('sent BEGIN'); rd(s)
    s.sendall(struct.pack('!BBHH',1,4,1,len(pd))+pd); print('sent PARAMS data'); rd(s)
    s.sendall(struct.pack('!BBHH',1,4,1,0)); print('sent PARAMS end'); rd(s)
    s.sendall(struct.pack('!BBHH',1,5,1,0)); print('sent STDIN end'); rd(s,3)
    s.close()
except Exception as e:
    print('EXC',repr(e))
print('--- ls /var/log/php-fpm ---')
import os
try:
    print(os.listdir('/var/log/php-fpm'))
except Exception as e: print(e)
print('--- tail /var/log/messages grep php/fpm ---')
try:
    for line in open('/var/log/messages','rb').readlines()[-200:]:
        s=line.decode(errors='replace').strip()
        if 'fpm' in s.lower() or 'segfault' in s.lower():
            print(s)
except Exception as e: print(e)
