def read_get(self): reader = SocketReader(self.sock) resp = HttpStream(reader) status_code = resp.status_code() headers = dict(resp.headers()) body = resp.body_string() return {"status_code": status_code, "headers": headers, "body": body}
def _handle_client(self, client, address): try: r = SocketReader(client) p = HttpStream(r) headers = p.headers() body = "" if "CONTENT-LENGTH" in headers and int( headers["CONTENT-LENGTH"]) > 0: body = p.body_string(binary=False) # System requests if p.path() == "/alive": self._respond(client, "ok") return # User requests req = IpcServer.Request(self._respond, client, p.path(), p.method(), headers, body) if p.path() == "/message": req.respond() self.requests.put(req) except Exception as e: client.close() raise e
def test_parse_from_real_socket(): # would fail on python2.6 before the recv_into hack sock, sink = socket.socketpair() sink.send(complete_request) reader = SocketReader(sock) stream = HttpStream(reader) assert stream.headers()
def handle(self, sock, addr): p = HttpStream(SocketReader(sock)) path = p.path() data = "hello world" sock.send("".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data ]))
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(('gunicorn.org', 80)) s.send("GET / HTTP/1.1\r\nHost: gunicorn.org\r\n\r\n") p = HttpStream(SocketReader(s)) print(p.headers()) print(p.body_file().read()) finally: s.close()
def get_response(self, request, connection): """ return final respons, it is only accessible via peform method """ if log.isEnabledFor(logging.DEBUG): log.debug("Start to parse response") p = HttpStream(SocketReader(connection.socket()), kind=1, decompress=self.decompress) if log.isEnabledFor(logging.DEBUG): log.debug("Got response: %s %s" % (p.version(), p.status())) log.debug("headers: [%s]" % p.headers()) location = p.headers().get('location') if self.follow_redirect: should_close = not p.should_keep_alive() if p.status_code() in (301, 302, 307,): # read full body and release the connection p.body_file().read() connection.release(should_close) if request.method in ('GET', 'HEAD',) or \ self.force_follow_redirect: if hasattr(self.body, 'read'): try: self.body.seek(0) except AttributeError: raise RequestError("Can't redirect %s to %s " "because body has already been read" % (self.url, location)) return self.redirect(location, request) elif p.status_code() == 303 and self.method == "POST": # read full body and release the connection p.body_file().read() connection.release(should_close) request.method = "GET" request.body = None return self.redirect(location, request) # create response object resp = self.response_class(connection, request, p) # apply response filters for f in self.response_filters: f.on_response(resp, request) if log.isEnabledFor(logging.DEBUG): log.debug("return response class") # return final response return resp
def recGETbody(HOST, request_headerGET): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) try: s.sendall(request_headerGET.encode('utf-8')) except: print("An error has occured while trying to send the GET request") dataReceived = SocketReader(s) parsed = HttpStream(dataReceived) body = parsed.body_file().read().decode('utf-8') return body
def recPOSTheader(HOST, request_headerPOST): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) try: s.sendall(request_headerPOST.encode('utf-8')) except: print("An error has occured while trying to send the POST request") dataReceived = SocketReader(s) parsed = HttpStream(dataReceived) header = parsed.headers() return header
def proxy_connection(self, request, req_addr, is_ssl): """ do the proxy connection """ proxy_settings = os.environ.get('%s_proxy' % request.parsed_url.scheme) if proxy_settings and proxy_settings is not None: request.is_proxied = True proxy_settings, proxy_auth = _get_proxy_auth(proxy_settings) addr = parse_netloc(urlparse.urlparse(proxy_settings)) if is_ssl: if proxy_auth: proxy_auth = 'Proxy-authorization: %s' % proxy_auth proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % req_addr user_agent = request.headers.iget('user_agent') if not user_agent: user_agent = "User-Agent: restkit/%s\r\n" % __version__ proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent) conn = self._pool.get(host=addr[0], port=addr[1], pool=self._pool, is_ssl=is_ssl, extra_headers=[], **self.ssl_args) conn.send(proxy_pieces) p = HttpStream(SocketReader(conn.socket()), kind=1, decompress=True) if p.status_code != 200: raise ProxyError("Tunnel connection failed: %d %s" % (resp.status_int, body)) _ = p.body_string() else: headers = [] if proxy_auth: headers = [('Proxy-authorization', proxy_auth)] conn = self._pool.get(host=addr[0], port=addr[1], pool=self._pool, is_ssl=False, extra_headers=[], **self.ssl_args) return conn return
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(('baike.baidu.com', 80)) s.send( b("GET /view/262.htm HTTP/1.1\r\nHost: baike.baidu.com\r\n\r\n")) p = HttpStream(SocketReader(s), decompress=True) print(p.headers()) print(p.body_file().read()) finally: s.close()
def GETverbose(HOST, request_headerGET): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, 80)) try: s.sendall(request_headerGET.encode('utf-8')) except: print("An error has occured while trying to send the GET request") dataReceived = SocketReader(s) parsed = HttpStream(dataReceived) body = parsed.body_file().read().decode('utf-8') header = parsed.headers() return pprint.pformat(header) + body
def connect(self, host, port='http', timeout=None, secure=None, **kwargs): assert self.socket is None, "http connection already established" if secure is None and port == 'https': secure = True self.socket = net.connect(host, port, timeout=timeout, secure=secure, **kwargs) self.reader = SocketReader(self.socket) self.host = host if port not in ('http', 'https'): self.host += ':%s' % port
def https_proxy(self, connectreq: HttpStream): self.request.sendall(CON_ESTABLISH) host, port = connectreq.path().split(':') cert_path = self.generate_cert(host) # request to localhost as server try: sock_client = ssl.wrap_socket(self.request, keyfile="cert.key", certfile=cert_path, ssl_version=ssl.PROTOCOL_TLS, server_side=True) sock_server = socket.create_connection((host, port)) sock_server = ssl.create_default_context().wrap_socket(sock_server, server_hostname=host) except OSError: return client_reader = SocketReader(sock_client) server_reader = SocketReader(sock_server) while True: # request to mail.ru as client clientreq = HttpStream(client_reader, decompress=True) try: clientreq_tosend = join_data(clientreq, 'Request') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return sock_server.sendall(clientreq_tosend) # request from mail.ru to localhost as client server_resp = HttpStream(server_reader, decompress=True) try: server_resp_tosend = join_data(server_resp, 'Response') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return try: sock_client.sendall(server_resp_tosend) except BrokenPipeError: return req = Request(clientreq.method(), server_resp.status_code(), clientreq_tosend, host) self.add_date_base(clientreq, req)
def repeat_request(req_id): req = session.query(Request).filter(Request.id == req_id).limit(1).all() if len(req) == 0: return redirect(url_for('requests', error_message=f'Not found ID {req_id}')) req = req[0] sock_server = socket.create_connection((req.host, 443)) sock_server = ssl.create_default_context().wrap_socket(sock_server, server_hostname=req.host) server_reader = SocketReader(sock_server) sock_server.sendall(req.headers) server_resp = HttpStream(server_reader, decompress=True) req = req.headers.decode().split('\r\n') answer = join_data(server_resp, 'Response') answer = answer.decode(errors='ignore') answer = answer.split('\r\n') return render_template('repeat.html', req_id=req_id, req=req, answer=answer)
def handle(self): self.logger = logging.getLogger("proxy") self.session = Session() try: request = HttpStream(SocketReader(self.request)) _ = request.status() except http_parser.http.BadStatusLine: return self.logger.warning(request.path()) if 'CONNECT' == request.method(): self.https_proxy(request) else: self.http_proxy(request) self.session.close()
def processData(newsocketconn, fromaddr, context, ipaddr, q): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() q.put(makeLogMessage("INFO", "idrac", "ProcessData")) if p.method() == 'POST': bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8", errors='ignore') ### Read the json response and print the output # outdata = dict() try: with open(f"{ipaddr[3]}/output/{ipaddr[2]}", "a+") as fd: fd.write(bodydata) fd.write("\n") except Exception as ex: print("Exception Occured =", ex) StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) # if p.method() == 'GET': # res = "HTTP/1.1 200 OK\n" \ # "Content-Type: application/json\n" \ # "\n" + json.dumps(data_buffer) # connstreamout.send(res.encode()) # data_buffer.clear() except Exception as err: outdata = connstreamout.read() traceback.print_exc() print("Data needs to read in normal Text format.") finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close()
def handle(self): h = SocketReader(self.request) p = HttpStream(h) #delagate=url[p.url()] delagate = Server.urls[p.url()] data = p.body_string() if data: data = data.decode('utf-8') else: data = "" js = None data = self.createData(data) print(p.url(), data) try: res = delagate(self.request, data) #todo change to: # self.request.send(res) except Exception as ex: print(ex)
def http_proxy(self, connectreq: HttpStream): reqheaders = connectreq.headers() # if ":" in connectreq.path(): parsed_url = connectreq.url().split('//')[1].split(':') if len(parsed_url) > 1: host = parsed_url[0] port = parsed_url[1].split('/')[0] else: host, port = reqheaders['host'], 80 if 'Proxy-Connection' in reqheaders: del reqheaders['Proxy-Connection'] elif 'proxy-connection' in reqheaders: del reqheaders['proxy-connection'] # request to mail.ru as client sock_server = socket.create_connection((host, port)) try: clientreq = join_data(connectreq, 'Request') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return sock_server.sendall(clientreq) # request from mail.ru to localhost as client if connectreq.method() == 'HEAD': return server_reader = SocketReader(sock_server) server_resp = HttpStream(server_reader, decompress=True) try: server_resp_tosend = join_data(server_resp, 'Response') except (http_parser.http.ParserError, http_parser.http.BadStatusLine, ConnectionResetError): return self.request.sendall(server_resp_tosend) req = Request(connectreq.method(), server_resp.status_code(), clientreq, host) self.add_date_base(connectreq, req)
def process_data(newsocketconn, fromaddr, threads): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn ### Output File Name outputfile = "Events_" + str(fromaddr[0]) + ".txt" logfile = "TimeStamp.log" global event_count, data_buffer outdata = headers = HostDetails = "" try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() #print("headers: ", headers) if p.method() == 'POST': bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8", errors='ignore') for eachHeader in headers.items(): if eachHeader[0] == 'Host' or eachHeader[0] == 'host': HostDetails = eachHeader[1] ### Read the json response and print the output #logging.info(f"Server IP Address is {}".format(fromaddr[0]) outdata = dict() current_date = DT.now().strftime("%Y%m%d") folder_suffix = "-{}".format( listenerport) if listenerport != '443' else '' directory = '{}{}/{}/{}'.format(report_location, folder_suffix, fromaddr[0], current_date) try: outdata = json.loads(bodydata) except json.decoder.JSONDecodeError: raw_invalid_file_thread = threading.Thread( target=writeInvalidJason, args=(directory, outdata), name="{}_F".format(fromaddr[0])) threads.append(raw_invalid_file_thread) raw_invalid_file_thread.start() if outdata: #writeRawJson(directory, outdata) raw_file_thread = threading.Thread( target=writeRawJson, args=(directory, outdata, fromaddr[0]), name="{}_F".format(fromaddr[0])) threads.append(raw_file_thread) raw_file_thread.start() StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) try: if event_count.get(str(fromaddr[0])): event_count[str( fromaddr[0])] = event_count[str(fromaddr[0])] + 1 else: event_count[str(fromaddr[0])] = 1 logging.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]])) except Exception as err: logging.error(err) #print(traceback.print_exc()) for th in threads: th.join() if p.method() == 'GET': res = "HTTP/1.1 200 OK\n" \ "Content-Type: application/json\n" \ "\n" + json.dumps(data_buffer) connstreamout.send(res.encode()) data_buffer.clear() except Exception as err: outdata = connstreamout.read() traceback.print_exc() #logging.exception(f"Data needs to read in normal Text format.{err}. Message is : {str(outdata)}") finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close() logging.debug("Connection closed")
def tostream(input): sock = FakeInputSocket(input) reader = SocketReader(sock) return HttpStream(reader)
def processData(newsocketconn, fromaddr, context, ipaddr): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn global event_count, data_buffer outdata = headers = HostDetails = "" try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() if p.method() == 'POST': bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8", errors='ignore') ### Read the json response and print the output # outdata = dict() try: old_time = getTimestampfromFilename(ipaddr[2]) new_time = (datetime.strptime(old_time, "%Y%m%d%H%M%S") + timedelta(seconds=int(ipaddr[4])) ).strftime("%Y%m%d%H%M%S") cur_time = datetime.now().strftime("%Y%m%d%H%M%S") a = np.where( int(cur_time) > int(new_time), new_time, False) fd = ipaddr[2] if eval(a.item(0)): filename = fd.name.split("/")[-1] # print(filename, "<--test") os.system(f"gzip {ipaddr[3]}/output/{filename}") shutil.move(f"{ipaddr[3]}/output/{filename}.gz", f"{ipaddr[3]}/complete/") fd.close() filename = ipaddr[0] + '_' + ipaddr[ 1] + '_' + fromaddr[0] + '_' + new_time + ".jsonl" try: fd = open(f"{ipaddr[3]}/output/{filename}", "a+") except FileNotFoundError as ex: if not os.path.exists(f"{file_collection_path}"): os.makedirs(file_collection_path) ipaddr[2] = open(f"{ipaddr[3]}/output/{filename}", "a+") # print(bodydata, type(bodydata), "<---bodydata") fd.write(bodydata) fd.write("\n") except Exception as ex: print("Exception Occured =", ex) StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) # try: # if event_count.get(str(fromaddr[0])): # event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1 # else: # event_count[str(fromaddr[0])] = 1 # # logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]])) # except Exception as err: # print(traceback.print_exc()) # for th in threads: # th.join() if p.method() == 'GET': res = "HTTP/1.1 200 OK\n" \ "Content-Type: application/json\n" \ "\n" + json.dumps(data_buffer) connstreamout.send(res.encode()) data_buffer.clear() except Exception as err: outdata = connstreamout.read() traceback.print_exc() print("Data needs to read in normal Text format.") print(outdata) finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close()
async def processData(newsocketconn, fromaddr, context, ipaddr): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn global event_count, data_buffer outdata = headers = HostDetails = "" try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() if p.method() == 'POST': bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8", errors='ignore') for eachHeader in headers.items(): if eachHeader[0] == 'Host' or eachHeader[0] == 'host': HostDetails = eachHeader[1] ### Read the json response and print the output outdata = dict() try: # get Current fd Timestamp timestamp = getTimestampfromFilename(ipaddr) # createJsonFile(ipaddr) fd = ipaddr[2] newFile = canGernerateNewJsonFile(timestamp, ipaddr[4]) if newFile: print(f"newfile Creates for iDRAC {fromaddr[0]}") fd = createJsonFile(ipaddr, fromaddr[0]) ipaddr[2] = fd fd.write(bodydata) fd.write("\n") except Exception as ex: print("Exception occurred while processing report", ex) # influx_thread = threading.Thread(target=writeReportToInflux, args=(fromaddr[0],directory, outdata)) # threads.append(influx_thread) # influx_thread.start() StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) # try: # if event_count.get(str(fromaddr[0])): # event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1 # else: # event_count[str(fromaddr[0])] = 1 # # logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]])) # except Exception as err: # print(traceback.print_exc()) # for th in threads: # th.join() if p.method() == 'GET': res = "HTTP/1.1 200 OK\n" \ "Content-Type: application/json\n" \ "\n" + json.dumps(data_buffer) connstreamout.send(res.encode()) data_buffer.clear() except Exception as err: outdata = connstreamout.read() traceback.print_exc() print("Data needs to read in normal Text format.") print(outdata) finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close()
def handle(self, sock, addr): s = SocketReader(sock) l = s.readline() print l sock.send(l)
def handle(self, sock, addr): p = HttpStream(SocketReader(sock)) path = p.path() if not path or path == "/": path = "index.html" if path.startswith("/"): path = path[1:] real_path = os.path.join(CURDIR, "static", path) if os.path.isdir(real_path): lines = ["<ul>"] for d in os.listdir(real_path): fpath = os.path.join(real_path, d) lines.append("<li><a href=" + d + ">" + d + "</a>") data = "".join(lines) resp = "".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data ]) sock.sendall(resp) elif not os.path.exists(real_path): util.write_error(sock, 404, "Not found", real_path + " not found") else: ctype = mimetypes.guess_type(real_path)[0] if ctype.startswith('text') or 'html' in ctype: try: f = open(real_path, 'rb') data = f.read() resp = "".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(len(data)) + "\r\n", "Connection: close\r\n\r\n", data ]) sock.sendall(resp) finally: f.close() else: try: f = open(real_path, 'r') clen = int(os.fstat(f.fileno())[6]) # send headers sock.send("".join([ "HTTP/1.1 200 OK\r\n", "Content-Type: " + ctype + "\r\n", "Content-Length:" + str(clen) + "\r\n", "Connection: close\r\n\r\n" ])) if not sendfile: while True: data = f.read(4096) if not data: break sock.send(data) else: fileno = f.fileno() sockno = sock.fileno() sent = 0 offset = 0 nbytes = clen sent += sendfile(sockno, fileno, offset + sent, nbytes - sent) while sent != nbytes: sent += sendfile(sock.fileno(), fileno, offset + sent, nbytes - sent) finally: f.close()
class HttpConnection(HttpSocket): def __init__(self, socket=None, host=None): HttpSocket.__init__(self, socket) self.version = HTTP_11 self.host = host self.reader = None if socket is None else SocketReader(self.socket) def connect(self, host, port='http', timeout=None, secure=None, **kwargs): assert self.socket is None, "http connection already established" if secure is None and port == 'https': secure = True self.socket = net.connect(host, port, timeout=timeout, secure=secure, **kwargs) self.reader = SocketReader(self.socket) self.host = host if port not in ('http', 'https'): self.host += ':%s' % port def close(self): try: if self.reader is not None: self.reader.close() except Exception: pass finally: self.reader = None self.host = None HttpSocket.close(self) def shutdown(self): self.socket.shutdown() def recv(self): try: stream = HttpStream(self.reader, kind=HTTP_RESPONSE, parser_class=HttpParser, decompress=True) status = stream.status_code() version = stream.version() fields = stream.headers() content = stream.body_file() self.version = 'HTTP/%s.%s' % version return status, fields, content except NoMoreData: pass def send(self, method, path, query=None, fragment=None, fields=None, content=None, version=None): if fields is None: fields = HttpFields() elif not isinstance(fields, HttpFields): fields = HttpFields(fields) if query is None: query = { } if content is None: content = b'' if version is None: version = self.version assert version in (HTTP_10, HTTP_11), "invalid http version: %s" % version fields.setdefault('Content-Length', six.text_type(len(content))) fields.setdefault('Host', self.host) for k, v in six.iteritems(dict(query)): query[k] = format_query_value(v) if six.PY3: query = urlencode(query, encoding='utf-8') else: query = urlencode(query) header = '' header += method header += ' ' header += urlunparse(('', '', path, '', query, fragment if bool(fragment) else '')) header += ' %s\r\n' % version header += ''.join('%s: %s\r\n' % (k, v) for k, v in six.iteritems(fields)) header += '\r\n' header = header.encode('utf-8') self.socket.sendall(header + content) def request(self, *args, **kwargs): self.send(*args, **kwargs) return self.recv() def delete(self, *args, **kwargs): return self.request('DELETE', *args, **kwargs) def get(self, *args, **kwargs): return self.request('GET', *args, **kwargs) def head(self, *args, **kwargs): return self.request('HEAD', *args, **kwargs) def options(self, *args, **kwargs): return self.request('OPTIONS', *args, **kwargs) def post(self, *args, **kwargs): return self.request('POST', *args, **kwargs) def put(self, *args, **kwargs): return self.request('PUT', *args, **kwargs)
def __init__(self, socket=None, host=None): HttpSocket.__init__(self, socket) self.version = HTTP_11 self.host = host self.reader = None if socket is None else SocketReader(self.socket)
def processData(newsocketconn, fromaddr, context): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn global event_count, data_buffer outdata = headers = HostDetails = "" try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() if p.method() == 'POST': bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8", errors='ignore') for eachHeader in headers.items(): if eachHeader[0] == 'Host' or eachHeader[0] == 'host': HostDetails = eachHeader[1] ### Read the json response and print the output print("Server IP Address is ", fromaddr[0]) outdata = dict() # current_date = DT.now().strftime("%Y%m%d") # folder_suffix = "-{}".format(listenerport) if listenerport != '443' else '' # directory = '{}{}/{}/{}'.format(report_location,folder_suffix,fromaddr[0],current_date) try: print(bodydata) with open("output.json", "a+") as f: f.write(bodydata) f.write("\n") except json.decoder.JSONDecodeError: print("Exception occurred while processing report") # influx_thread = threading.Thread(target=writeReportToInflux, args=(fromaddr[0],directory, outdata)) # threads.append(influx_thread) # influx_thread.start() StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) # try: # if event_count.get(str(fromaddr[0])): # event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1 # else: # event_count[str(fromaddr[0])] = 1 # # logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]])) # except Exception as err: # print(traceback.print_exc()) # for th in threads: # th.join() if p.method() == 'GET': res = "HTTP/1.1 200 OK\n" \ "Content-Type: application/json\n" \ "\n" + json.dumps(data_buffer) connstreamout.send(res.encode()) data_buffer.clear() except Exception as err: outdata = connstreamout.read() traceback.print_exc() print("Data needs to read in normal Text format.") print(outdata) finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close()
def perform(self, request): """ perform the request. If an error happen it will first try to restart it """ if log.isEnabledFor(logging.DEBUG): log.debug("Start to perform request: %s %s %s" % (request.host, request.method, request.path)) tries = 0 while True: conn = None try: # get or create a connection to the remote host conn = self.get_connection(request) # send headers msg = self.make_headers_string(request, conn.extra_headers) # send body if request.body is not None: chunked = request.is_chunked() if request.headers.iget('content-length') is None and \ not chunked: raise RequestError( "Can't determine content length and " + "Transfer-Encoding header is not chunked") # handle 100-Continue status # http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 hdr_expect = request.headers.iget("expect") if hdr_expect is not None and \ hdr_expect.lower() == "100-continue": conn.send(msg) msg = None p = HttpStream(SocketReader(conn.socket()), kind=1, decompress=True) if p.status_code != 100: self.reset_request() if log.isEnabledFor(logging.DEBUG): log.debug("return response class") return self.response_class(conn, request, p) chunked = request.is_chunked() if log.isEnabledFor(logging.DEBUG): log.debug("send body (chunked: %s)" % chunked) if isinstance(request.body, (str, )): if msg is not None: conn.send(msg + to_bytestring(request.body), chunked) else: conn.send(to_bytestring(request.body), chunked) else: if msg is not None: conn.send(msg) if hasattr(request.body, 'read'): if hasattr(request.body, 'seek'): request.body.seek(0) conn.sendfile(request.body, chunked) else: conn.sendlines(request.body, chunked) if chunked: conn.send_chunk("") else: conn.send(msg) return self.get_response(request, conn) except socket.gaierror as e: if conn is not None: conn.release(True) raise RequestError(str(e)) except socket.timeout as e: if conn is not None: conn.release(True) raise RequestTimeout(str(e)) except socket.error as e: if log.isEnabledFor(logging.DEBUG): log.debug("socket error: %s" % str(e)) if conn is not None: conn.close() errors = (errno.EAGAIN, errno.EPIPE, errno.EBADF, errno.ECONNRESET) if e[0] not in errors or tries >= self.max_tries: raise RequestError("socket.error: %s" % str(e)) # should raised an exception in other cases request.maybe_rewind(msg=str(e)) except NoMoreData as e: if conn is not None: conn.release(True) request.maybe_rewind(msg=str(e)) if tries >= self.max_tries: raise except BadStatusLine: if conn is not None: conn.release(True) # should raised an exception in other cases request.maybe_rewind(msg="bad status line") if tries >= self.max_tries: raise except Exception: # unkown error log.debug("unhandled exception %s" % traceback.format_exc()) if conn is not None: conn.release(True) raise tries += 1 self._pool.backend_mod.sleep(self.wait_tries)
def read_output_data(newsocketconn, fromaddr): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn ### Output File Name outputfile = "Events_" + str(fromaddr[0]) + ".txt" global event_count outdata = headers = HostDetails = "" try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() print("headers: ", headers) bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8") print("bodydata: ", bodydata) for eachHeader in headers.items(): if eachHeader[0] == 'Host' or eachHeader[0] == 'host': HostDetails = eachHeader[1] ### Read the json response and print the output print("\n") print("Server IP Address is ", fromaddr[0]) print("Server PORT number is ", fromaddr[1]) print("Listener IP is ", HostDetails) outdata = json.loads(bodydata) event_array = outdata['Events'] for event in event_array: print("EventType is ", event['EventType']) print("MessageId is ", event['MessageId']) if 'EventId' in event: print("EventId is ", event['EventId']) if 'EventTimestamp' in event: print("EventTimestamp is ", event['EventTimestamp']) if 'Severity' in event: print("Severity is ", event['Severity']) if 'Message' in event: print("Message is ", event['Message']) if 'MessageArgs' in event: print("MessageArgs is ", event['MessageArgs']) if 'Context' in outdata: print("Context is ", outdata['Context']) print("\n") except Exception as err: outdata = connstreamout.read() print("Data needs to read in normal Text format.") print(outdata) ### Check the context and send the status OK if context matches if outdata.get('Context', None) != ContextDetail: print("Context ({}) does not match with the server ({}).".format( outdata.get('Context', None), ContextDetail)) StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) try: if event_count.get(str(fromaddr[0])): event_count[str( fromaddr[0])] = event_count[str(fromaddr[0])] + 1 else: event_count[str(fromaddr[0])] = 1 print("Event Counter for Host %s is %s" % (str(fromaddr[0]), event_count[fromaddr[0]])) print("\n") fd = open(outputfile, "a") fd.write("Time:%s Count:%s\nHost IP:%s\nEvent Details:%s\n" % (time.ctime(), event_count[str( fromaddr[0])], str(fromaddr), outdata)) fd.close() except Exception as err: print(traceback.print_exc()) finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close()
class HttpClient(HttpSocket): def __init__(self, socket, address, server): HttpSocket.__init__(self, socket) self.address = address self.reader = SocketReader(self.socket) self.server = server self.version = HTTP_11 def __iter__(self): while True: request = self.recv() if request is None: break yield request def iter_wsgi(self): while True: environ = self.recv(True) if environ is None: break yield environ def close(self): try: if self.reader is not None: self.reader.close() except Exception: pass finally: self.reader = None HttpSocket.close(self) def recv(self, wsgi=False): try: stream = HttpStream(self.reader, kind=HTTP_REQUEST, parser_class=HttpParser, decompress=True) if bool(wsgi): environ = stream.wsgi_environ() environ['wsgi.url_scheme'] = guess_scheme(environ) environ['wsgi.input'] = stream.body_file() environ['wsgi.socket'] = self.socket return environ # BUG: # http-parser has an issue here, if we call 'method' before 'headers' # and invalid method name is returned... fields = stream.headers() method = stream.method() url = stream.url() version = stream.version() content = stream.body_file() url = urlparse(url) path = url.path query = parse_qs(url.query, keep_blank_values=True) fragment = url.fragment for k, v in six.iteritems(dict(query)): query[k] = parse_query_value(v) self.version = 'HTTP/%s.%s' % version return method, path, query, fragment, fields, content except NoMoreData: pass def send(self, status, fields=None, content=None, version=None): if fields is None: fields = { } elif not isinstance(fields, HttpFields): fields = HttpFields(fields) if content is None: content = b'' if version is None: version = self.version assert version in (HTTP_10, HTTP_11), "invalid http version: %s" % version fields.setdefault('Content-Length', six.text_type(len(content))) if self.server is not None: fields.setdefault('Server', self.server) if isinstance(status, int): status = '%s %s' % (status, reasons[status]) header = '' header += '%s %s\r\n' % (version, status) header += ''.join('%s: %s\r\n' % (k, v) for k, v in six.iteritems(fields)) header += '\r\n' header = header.encode('utf-8') return self.socket.sendall(header + content)
def handle(self, sock, addr): s = SocketReader(sock) l = s.readline() print l sock.send(l)
def __init__(self, socket, address, server): HttpSocket.__init__(self, socket) self.address = address self.reader = SocketReader(self.socket) self.server = server self.version = HTTP_11
def perform(self, request): """ perform the request. If an error happen it will first try to restart it """ if log.isEnabledFor(logging.DEBUG): log.debug("Start to perform request: %s %s %s" % (request.host, request.method, request.path)) tries = 0 while True: conn = None try: # get or create a connection to the remote host conn = self.get_connection(request) # send headers msg = self.make_headers_string(request, conn.extra_headers) # send body if request.body is not None: chunked = request.is_chunked() if request.headers.iget('content-length') is None and \ not chunked: raise RequestError( "Can't determine content length and " + "Transfer-Encoding header is not chunked") # handle 100-Continue status # http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3 hdr_expect = request.headers.iget("expect") if hdr_expect is not None and \ hdr_expect.lower() == "100-continue": conn.send(msg) msg = None p = HttpStream(SocketReader(conn.socket()), kind=1, decompress=True) if p.status_code != 100: self.reset_request() if log.isEnabledFor(logging.DEBUG): log.debug("return response class") return self.response_class(conn, request, p) chunked = request.is_chunked() if log.isEnabledFor(logging.DEBUG): log.debug("send body (chunked: %s)" % chunked) if isinstance(request.body, types.StringTypes): if msg is not None: conn.send(msg + to_bytestring(request.body), chunked) else: conn.send(to_bytestring(request.body), chunked) else: if msg is not None: conn.send(msg) if hasattr(request.body, 'read'): if hasattr(request.body, 'seek'): request.body.seek(0) conn.sendfile(request.body, chunked) else: conn.sendlines(request.body, chunked) if chunked: conn.send_chunk("") else: conn.send(msg) return self.get_response(request, conn) except socket.gaierror, e: if conn is not None: conn.release(True) raise RequestError(str(e)) except socket.timeout, e: if conn is not None: conn.release(True) raise RequestTimeout(str(e))
def process_data(newsocketconn, fromaddr): if useSSL: connstreamout = context.wrap_socket(newsocketconn, server_side=True) else: connstreamout = newsocketconn ### Output File Name outputfile = "Events_" + str(fromaddr[0]) + ".txt" logfile = "TimeStamp.log" global event_count, data_buffer outdata = headers = HostDetails = "" try: try: ### Read the json response using Socket Reader and split header and body r = SocketReader(connstreamout) p = HttpStream(r) headers = p.headers() my_logger.info("headers: %s", headers) if p.method() == 'POST': bodydata = p.body_file().read() bodydata = bodydata.decode("utf-8") my_logger.info("\n") my_logger.info("bodydata: %s", bodydata) data_buffer.append(bodydata) for eachHeader in headers.items(): if eachHeader[0] == 'Host' or eachHeader[0] == 'host': HostDetails = eachHeader[1] ### Read the json response and print the output my_logger.info("\n") my_logger.info("Server IP Address is %s", fromaddr[0]) my_logger.info("Server PORT number is %s", fromaddr[1]) my_logger.info("Listener IP is %s", HostDetails) my_logger.info("\n") outdata = json.loads(bodydata) if 'Events' in outdata and config['verbose']: event_array = outdata['Events'] for event in event_array: my_logger.info("EventType is %s", event['EventType']) my_logger.info("MessageId is %s", event['MessageId']) if 'EventId' in event: my_logger.info("EventId is %s", event['EventId']) if 'EventGroupId' in event: my_logger.info("EventGroupId is %s", event['EventGroupId']) if 'EventTimestamp' in event: my_logger.info("EventTimestamp is %s", event['EventTimestamp']) if 'Severity' in event: my_logger.info("Severity is %s", event['Severity']) if 'MessageSeverity' in event: my_logger.info("MessageSeverity is %s", event['MessageSeverity']) if 'Message' in event: my_logger.info("Message is %s", event['Message']) if 'MessageArgs' in event: my_logger.info("MessageArgs is %s", event['MessageArgs']) if 'Context' in outdata: my_logger.info("Context is %s", outdata['Context']) my_logger.info("\n") if 'MetricValues' in outdata and config['verbose']: metric_array = outdata['MetricValues'] my_logger.info("Metric Report Name is: %s", outdata.get('Name')) for metric in metric_array: my_logger.info("Member ID is: %s", metric.get('MetricId')) my_logger.info("Metric Value is: %s", metric.get('MetricValue')) my_logger.info("TimeStamp is: %s", metric.get('Timestamp')) if 'MetricProperty' in metric: my_logger.info("Metric Property is: %s", metric['MetricProperty']) my_logger.info("\n") ### Check the context and send the status OK if context matches if config['contextdetail'] is not None and outdata.get('Context', None) != config['contextdetail']: my_logger.info("Context ({}) does not match with the server ({})." .format(outdata.get('Context', None), config['contextdetail'])) StatusCode = """HTTP/1.1 200 OK\r\n\r\n""" connstreamout.send(bytes(StatusCode, 'UTF-8')) with open(logfile, 'a') as f: if 'EventTimestamp' in outdata: receTime = datetime.now() sentTime = datetime.strptime(outdata['EventTimestamp'], "%Y-%m-%d %H:%M:%S.%f") f.write("%s %s %sms\n" % ( sentTime.strftime("%Y-%m-%d %H:%M:%S.%f"), receTime, (receTime - sentTime).microseconds / 1000)) else: f.write('No available timestamp.') try: if event_count.get(str(fromaddr[0])): event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1 else: event_count[str(fromaddr[0])] = 1 my_logger.info("Event Counter for Host %s = %s" % (str(fromaddr[0]), event_count[fromaddr[0]])) my_logger.info("\n") fd = open(outputfile, "a") fd.write("Time:%s Count:%s\nHost IP:%s\nEvent Details:%s\n" % ( datetime.now(), event_count[str(fromaddr[0])], str(fromaddr), json.dumps(outdata))) fd.close() except Exception as err: my_logger.info(traceback.print_exc()) if p.method() == 'GET': # for x in data_buffer: # my_logger.info(x) res = "HTTP/1.1 200 OK\n" \ "Content-Type: application/json\n" \ "\n" + json.dumps(data_buffer) connstreamout.send(res.encode()) data_buffer.clear() except Exception as err: outdata = connstreamout.read() my_logger.info("Data needs to read in normal Text format.") my_logger.info(outdata) finally: connstreamout.shutdown(socket.SHUT_RDWR) connstreamout.close()