targetConn, err := net.Dial("tcp", targetAddr)
if err != nil {
log.Printf("Failed to connect to target: %s\n", err)
return
}
defer targetConn.Close()
go io.Copy(targetConn, clientConn)
io.Copy(clientConn, targetConn)
}
Assistant
User
как сделать так, что когда человек отключается от прокси, он и отключался от таргета
Assistant
The provided code is a simple TCP proxy server implemented in Go. The proxy listens for incoming connections, accepts them, and forwards the data to a specified target address. Here's a breakdown of the code and how it works:
Code Explanation
Imports:
io: For copying data between connections.
log: For logging information and errors.
net: For networking functionality.
os: For accessing environment variables.
Main Function:
Logs the version of the proxy server (Version 0.0.3).
Retrieves the LISTEN address and the TARGET address from the environment variables.
Creates a TCP listener on the specified address.
If the listener fails to start, it logs an error and exits.
Enters a loop to accept incoming connections.
Accepting Connections:
For each accepted connection, it logs the remote address of the client.
Spawns a new goroutine to handle the connection, allowing the server to continue accepting new connections concurrently.
Handling Connections:
The handleConnection function is responsible for setting up the connection to the target server.
It connects to the target address specified in the environment variable.
If unable to connect to the target, it logs an error and exits the function.
Uses io.Copy to copy data between the client and target connections both ways, which allows bidirectional communication.
Usage
To run this TCP proxy server, you must set the LISTEN and TARGET environment variables:
LISTEN: The address and port on which the proxy will listen for incoming connections (e.g., :8080).
TARGET: The address and port of the target server to which the proxy will forward the data (e.g., example.com:80).
Example of Running the Proxy
You can run this server from the command line using:
bash
export LISTEN=:8080
export TARGET=example.com:80
go run your_proxy_server.go
Notes
Concurrency: The use of goroutines allows the proxy to handle multiple simultaneous connections efficiently.
Error Handling: Logs error messages but continues execution, allowing the server to remain responsive.
Graceful Shutdown: The listener will be closed using defer listener.Close(), which is important for cleanup, although a more robust implementation would also support signal handling to shut down gracefully.
Security Considerations: It's important to consider security implications when running a proxy server, such as validation of target addresses and managing inbound/outbound traffic responsibly.
Для того чтобы при отключении клиента от прокси-сервера, соединение с целевым сервером также закрывалось, необходимо правильно обработать обмен данными между клиентом и целевым сервером. Если клиент отключается, то нужно завершить работу и с соединением с целевым сервером. В текущем коде это сделано через io.Copy, который будет продолжать работать, пока идет обмен данными. Однако для того, чтобы обеспечить более явное управление завершением соединения, можно добавить дополнительную логику для проверки состояния соединения.
Вот пример доработанного кода с использованием каналов, позволяющий завершить соединение с целевым сервером при отключении клиента:
go
package main
import (
"io"
"log"
"net"
"os"
)
func main() {
log.Printf("Version 0.0.3")
listen := os.Getenv("LISTEN")
target := os.Getenv("TARGET")
listener, err := net.Listen("tcp", listen)
if err != nil {
log.Fatalf("Failed to listen on %s: %s\n", listen, err)
}
defer listener.Close()
log.Printf("Listening on %s and forwarding to %s\n", listen, target)
for {
clientConn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept connection: %s\n", err)
continue
}
log.Printf("New connection from %s\n", clientConn.RemoteAddr())
go handleConnection(clientConn, target)
}
}
func handleConnection(clientConn net.Conn, targetAddr string) {
defer clientConn.Close()
targetConn, err := net.Dial("tcp", targetAddr)
if err != nil {
log.Printf("Failed to connect to target: %s\n", err)
return
}
defer targetConn.Close()
// Используем канал для завершения горутины
done := make(chan struct{})
// Горутина для копирования данных от клиента к цели
go func() {
defer close(done)
io.Copy(targetConn, clientConn)
}()
// Копируем данные от цели к клиенту
io.Copy(clientConn, targetConn)
// Ждем завершения копирования из клиента в цель
<-done
}
Объяснение изменений:
Канал done: Создается канал done, который служит для синхронизации завершения копирования данных от клиента к целевому серверу.
Горутина для копирования: Внутри горутины, которая отвечает за копирование данных от клиента к целевому серверу, добавлено defer close(done). Это закрывает канал, когда копирование завершено.
Блокировка io.Copy: Основной поток (где происходит io.Copy от targetConn к clientConn) будет ждать завершения копирования от clientConn к targetConn, благодаря <-done.
Как это работает:
При отключении клиента от прокси, поток, копирующий данные от клиента к целевому серверу завершится, закроет канал done, и прокси также завершит обмен данными с целевым сервером.
Это обеспечит корректное закрытие обеих сторон соединения.