I am creating torrent scraper in objective-c and I am using AFNetworking for the HTTP requests. I need to send a sha1 hash of the part of the meta info for a tracker request. I have successfully created the hash and verified that it is correct. I can not put the hash in an NSString since it does not encode binary data so I have put it in an NSData object and then in the parameters to send. This is what I have right now, but I always get an error back, and I would assume it is with the methods I am using to send the hash. I have also tried url encoding the hash and then putting it in an NSString with no avail
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
unsigned char infoHash[20];
[self.tracker generateTorrentInfoHash:infoHash];
const char peer_id[20] = "randomstringfornow";
[parameters setObject:[NSData dataWithBytes:&infoHash length:20] forKey:@"info_hash"];
[parameters setObject:[NSData dataWithBytes:&peer_id length:20] forKey:@"peer_id"];
[parameters setObject:@(8080) forKey:@"port"];
[parameters setObject:@(0) forKey:@"uploaded"];
[parameters setObject:@(self.tracker.metaInfo.totalFileSize) forKey:@"left"];
[parameters setObject:@(0) forKey:@"downloaded"];
[parameters setObject:@(0) forKey:@"compact"];
[parameters setObject:@"stopped" forKey:@"event"];
[self getPath:@"" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@",operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",operation.responseString);
}];
Does anyone know if there is a possible way of doing this with AFNetworking or maybe I am hopefully missing something simple.
Alright, I’m not an expert at torrents, but I think the challenge you’re having is that the bencoded data representation you’re pulling from encodes the SHA1 hash as 20 raw bytes of data.
You can’t send raw data like that in the GET portion of an HTTP request, so you’re going to need to encode it. Based on the specs, it appears that urlencoding the raw data is the official way to do so. (Other options would be to convert it to a human-readable hex string, for example).
From this Alternative Bittorrent Specification:
Starting with your raw 20 char C array, you need to get to a URLEncoded
NSString.Unfortunately, especially with this type of data, the simple method – using
stringByAddingPercentEscapesUsingEncodingin a loop – won’t work because it does not end up with a safe encoding to send as a GET parameter.With a bit of S.O. help ( How do I URL encode a string ), here is a bit of code that you can mold into the final product, but meets the spec doc for correct output:
Output is:
Good luck!