38 def send(self, sock: socket.socket, data: str | bytes) -> bool:
40 encrypted = self.
_crypto.encrypt(data)
41 total_len = len(encrypted)
44 for i
in range(nb_chunks):
48 chunk[0] = (nb_chunks >> 24) & 0xFF
49 chunk[1] = (nb_chunks >> 16) & 0xFF
50 chunk[2] = (nb_chunks >> 8) & 0xFF
51 chunk[3] = (nb_chunks >> 0) & 0xFF
53 chunk[4] = (i >> 24) & 0xFF
54 chunk[5] = (i >> 16) & 0xFF
55 chunk[6] = (i >> 8) & 0xFF
56 chunk[7] = (i >> 0) & 0xFF
58 chunk[8] = (len(chunk_data) >> 8) & 0xFF
59 chunk[9] = len(chunk_data) & 0xFF
61 chunk[10:10 + len(chunk_data)] = chunk_data
62 chunk[10 + len(chunk_data)] = 0x04
66 except Exception
as e:
67 print(f
"[SEND ERROR] {e}")
86 def receive(self, sock: socket.socket) -> str | bool:
88 received_chunks =
None
96 print(
"[RECEIVE ERROR] Timeout or socket closed before header")
111 chunk_len = (head[8] << 8) | head[9]
115 print(f
"[RECEIVE ERROR] chunk_len {chunk_len} inconsistent (need {needed} > {self._buffer_size})")
119 payload_plus_eot = self.
_recv_all(sock, chunk_len + 1)
120 if payload_plus_eot
is None:
121 print(f
"[RECEIVE ERROR] Timeout or socket closed while reading payload for chunk {chunk_index}")
125 if payload_plus_eot[-1] != 0x04:
126 print(f
"[RECEIVE ERROR] Missing or misplaced EOT for chunk {chunk_index}")
130 if remainder_padding > 0:
131 pad = self.
_recv_all(sock, remainder_padding)
133 print(f
"[RECEIVE ERROR] Timeout or socket closed while reading padding for chunk {chunk_index}")
137 if total_chunks
is None:
138 total_chunks = total_chunks_read
139 if total_chunks <= 0:
140 print(f
"[RECEIVE ERROR] invalid total_chunks = {total_chunks}")
142 received_chunks = [
False] * total_chunks
145 if not (0 <= chunk_index < total_chunks):
146 print(f
"[RECEIVE ERROR] chunk_index {chunk_index} out of bounds (total {total_chunks})")
149 if received_chunks[chunk_index]:
150 print(f
"[RECEIVE ERROR] duplicate chunk {chunk_index}")
154 ciphertext = payload_plus_eot[:chunk_len]
155 buffer.extend(ciphertext)
156 received_chunks[chunk_index] =
True
159 if all(received_chunks):
162 return self.
_crypto.decrypt(bytes(buffer))
164 except Exception
as e:
165 print(f
"[RECEIVE EXCEPTION] {e}")