Search code examples
pythonencodingbittorrent

Decoding error message from tracker


I am trying to decode an error message from a UDP tracker. below is my code.

import struct, socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info_hash  = "%1D%D4%D1%EDQn%DB%5CL%83%90%1B%2B%F8%83%A2%19%C0%7C%98"
peer_id = "-UT1234-m%09%B2%D5%99%FA%1Fj%88%AC%0D%A7"
action =1 # announce
downloaded = 0
left = 0
uploaded = 0
event =0
ip = 0
key = 0
num_want = -1
port = 9999
announce_pack = struct.pack(">QLL20s20sQQQLLLLi",connection_id,action,transaction_id,info_hash,peer_id,down  loaded,left,uploaded,event,ip,key,num_want,port)
client_socket.sendto(announce_pack, ("tracker.ccc.de", 80))
res = client_socket.recv(1024)
try:
   action = struct.unpack(">HLLLLQQQ20s20sLLH", res[:98])
except Exception as e:
   error_action, error_tid, error_message = struct.unpack(">ii8s", res)
   raise TrackerRequestException(error_message.decode('utf-16'), "")

i am able to unpack the message but for some reason i am getting error message a

\uc061\u51be\u5841\ud3bf

how do I decode this into proper text?

I got the protocol description from this link http://bittorrent.org/beps/bep_0015.html


Solution

  • There can be an exception for any number of reasons; you could have read too little data for example (socket.recv(1024) can return fewer bytes if that's all that's available at that time).

    You need to follow the BEP more closely. You need to check that you have received at least 8 bytes first, and then check for the TID, and the action code. Only if your action code is set to 3 is the response an error message.

    The message is not encoded in UTF-16. It should just be ASCII data.