Trying to make a tor proxy with tokio & socks

I am trying to make a tor proxy with tokio & socks but its keep failing.
Can you please help me out.

Error: failed to fill whole buffer

Code

use socks::{Socks5Stream, TargetAddr};
use std::io::Read;
use std::io::Write;
use tokio::io::{AsyncReadExt, Error};
use tokio::net::TcpStream;

#[tokio::main]
async fn main() {
    let target_addr = TargetAddr::Domain("check.torproject.org".to_owned(), 80);
    let mut stream = Socks5Stream::connect(target_addr, "127.0.0.1:9050").unwrap();

    let request = b"GET / HTTP/1.1\r\n\r\n";
    stream.write_all(request).unwrap();

    let mut response = vec![];
    stream.read_to_end(&mut response).unwrap();

    println!("Response: {}", String::from_utf8_lossy(&response));
}

This might be due to trying to use read_to_end (which would never return if the server keeps the connection open after processing your request) rather than parsing the response headers and then reading exactly Content-Length bytes. On a related note have you seen arti? This is a rust implementation of tor by the tor project developers themself that you can embed in your project without needing to use socks. Using it likely won't fix your issue, but when you have fixed your issue using it may be more convenient than having to install tor separately.

1 Like

Thanks

I tried but getting error with it.

Error: linking with cc failed: exit status: 1

use arti_client::{TorClient, TorClientConfig};
use futures::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() {
    let tor_client = TorClient::create_bootstrapped(TorClientConfig::default())
        .await
        .unwrap();

    let mut stream = tor_client
        .connect(("check.torproject.org", 80))
        .await
        .unwrap();

    stream
        .write_all(b"GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();

    stream.flush().await.unwrap();

    let mut buf = Vec::new();
    stream.read_to_end(&mut buf).await.unwrap();

    println!("{}", String::from_utf8_lossy(&buf));
}

Maybe arti has a native dependency you haven't installed yet? Could you post the part before that error message? That should contain an indication of which library is missing.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.