text
stringlengths
1
93.6k
cookie_pattern = re.compile(r'Set-Cookie: (\S+)(?:;.*)*$', re.IGNORECASE)
def get_bytes(a_string):
if sys.version_info < (3, 0):
return bytes(a_string)
else:
return bytes(a_string, 'ASCII')
# helper function to generate the above password
def gen_pwd(len):
p = list()
for i in range(len):
p.append(
random.choice(
string.ascii_letters + string.digits))
return b''.join(get_bytes(p))
websock_mutex = threading.Lock()
def header_mode(mode):
return b"X-Type: %s\r\n" % mode
# hat tip to: https://stackoverflow.com/a/42429447/204634
class CountdownTimer(threading.Thread):
quit = False
def run(self):
for remaining in range(120, 0, -1):
if self.quit:
sys.stdout.write("\n")
break
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
class HeartBeat(threading.Thread):
def __init__(self, websock):
super(HeartBeat, self).__init__()
self.timer_lock = threading.Lock()
self.timer = None
self.reset_timer()
self.quit = None
self.websock = websock
def stop(self):
self.quit = True
def reset_timer(self):
with self.timer_lock:
self.timer = datetime.datetime.now()
def run(self):
log.debug("Heartbeat started")
try:
while not self.quit:
t = datetime.datetime.now() - self.timer
if t.seconds < HEARTBEAT_THRESHOLD:
time.sleep(0.1)
else:
with websock_mutex:
# log.debug("Sending heartbeat")
self.websock.sendall(to_chunk(HEARTBEAT_STRING))
# can't tell why, but this should be outside of the data
# mutex
self.reset_timer()
except socket.error as e:
raise SystemExit("Heartbeat error: {}".format(e))
class POSTFactory(object):
"""Used to send POST requests for each message."""
def __init__(self, path, hostname, password):
self.req_headers = b''.join((
b"POST " + path + b" HTTP/1.1\r\n",
b"Host: " + hostname + b"\r\n",
b"X-Pwd: " + password + b"\r\n",
b"accept-encoding: *;q=0\r\n", # ,gzip;q=0,deflate;q=0\r\n",
b"Transfer-Encoding: chunked\r\n",
b"Content-Type: application/octet-stream; charset=utf-8\r\n",
))
def build_request(self, my_headers, req_body, is_last=False):
if is_last:
req_body += to_chunk(b"")
request = b''.join((
self.req_headers,
my_headers,
HTTP_SEPARATOR,
req_body))
return request