def encodeControllerString(cont_str, hex_encode = True):
'''
Encode a string for transmission over the control port.
If hex_encode is True, encode in hexadecimal, otherwise, encode
in the Tor Control Protocol QuotedString format.
Does not support the CString encoding.
Only some strings in the tor control protocol need encoding.
The same encodings are used by tor and the controller.
'''
if hex_encode:
# hex encoded strings do not have an 0x prefix
encoded = hexlify(cont_str)
else: # QuotedString
# quoted strings escape \ and " with \, then quote with "
# the order of these replacements is important: they ensure that
# " becomes \" rather than \\"
cont_str = cont_str.replace("\\", "\\\\")
cont_str = cont_str.replace("\"", "\\\"")
encoded = "\"" + cont_str + "\""
# sanity check
assert TorControlProtocol.decodeControllerString(encoded) == cont_str
return encoded
评论列表
文章目录