### VMess Server Setup and Handler Implementation in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt Provides a Go implementation for setting up a VMess server. It includes a basic 'ProxyHandler' to manage incoming TCP and UDP connections, forwarding them to their destinations. The server is configured with user credentials and listens on a specified port. Dependencies include 'sing-vmess', 'sing/common/metadata', and 'sing/common/network'. ```go package main import ( "context" "net" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) // Handler implementation for proxying connections type ProxyHandler struct{} func (h *ProxyHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) { // Handle TCP connection - dial to destination remote, err := net.Dial("tcp", destination.String()) if err != nil { conn.Close() return } defer remote.Close() defer conn.Close() // Bidirectional copy go func() { buf := make([]byte, 32768) _, _ = copyBuffer(remote, conn, buf) }() buf := make([]byte, 32768) _, _ = copyBuffer(conn, remote, buf) } func (h *ProxyHandler) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) { // Handle UDP packets defer conn.Close() remote, err := net.ListenPacket("udp", "") if err != nil { return } defer remote.Close() // Forward packets bidirectionally buffer := make([]byte, 65535) for { n, _, err := conn.ReadFrom(buffer) if err != nil { break } _, _ = remote.WriteTo(buffer[:n], destination.UDPAddr()) } } func main() { handler := &ProxyHandler{} // Create service with handler service := vmess.NewService[string](handler) // Add users with their credentials users := []string{"user1", "user2"} userIds := []string{ "b831381d-6324-4d53-ad4f-8cda48b30811", "a2c3e4f5-1234-5678-9abc-def012345678", } alterIds := []int{0, 0} // 0 for AEAD mode err := service.UpdateUsers(users, userIds, alterIds) if err != nil { panic(err) } err = service.Start() if err != nil { panic(err) } defer service.Close() // Listen for incoming connections listener, err := net.Listen("tcp", ":8388") if err != nil { panic(err) } defer listener.Close() println("VMess server listening on :8388") for { conn, err := listener.Accept() if err != nil { continue } go func(c net.Conn) { ctx := context.Background() source := M.SocksaddrFromNet(c.RemoteAddr()) err := service.NewConnection(ctx, c, source, nil) if err != nil { c.Close() } }(conn) } } func copyBuffer(dst net.Conn, src net.Conn, buf []byte) (int64, error) { var written int64 for { nr, err := src.Read(buf) if nr > 0 { nw, ew := dst.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { return written, ew } } if err != nil { return written, err } } } ``` -------------------------------- ### Creating UDP Packet Connections in VMess Client Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This example illustrates setting up a UDP packet connection through VMess for datagram proxying, useful for DNS or other UDP traffic. Dependencies include sing-vmess and metadata parsing; inputs are upstream TCP and UDP destination, outputs a packet connection for WriteTo/ReadFrom. Limitations encompass encapsulating UDP in TCP and potential performance overhead for high-volume datagrams. ```go package main import ( "net" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" ) func main() { client, err := vmess.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", "aes-128-gcm", 0, ) if err != nil { panic(err) } upstream, err := net.Dial("tcp", "proxy.example.com:443") if err != nil { panic(err) } destination := M.ParseSocksaddr("8.8.8.8:53") // Create UDP packet connection packetConn, err := client.DialPacketConn(upstream, destination) if err != nil { upstream.Close() panic(err) } defer packetConn.Close() // Send DNS query dnsQuery := []byte{ 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x01, 0x00, 0x01, } _, err = packetConn.WriteTo(dnsQuery, destination.UDPAddr()) if err != nil { panic(err) } response := make([]byte, 512) n, addr, err := packetConn.ReadFrom(response) if err != nil { panic(err) } println("Received", n, "bytes from", addr.String()) } ``` -------------------------------- ### Use VLESS for UDP and XUDP Traffic in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This Go code demonstrates how to utilize VLESS for UDP traffic, supporting both standard UDP and the enhanced XUDP protocol. It requires the sing-vmess library. The examples show creating a VLESS client and then using DialPacketConn for standard UDP and DialXUDPPacketConn for XUDP, allowing for specific packet routing and reading with source address information. ```go package main import ( "net" "github.com/sagernet/sing-vmess/vless" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/logger" "github.com/sagernet/sing/common/buf" ) func main() { client, err := vless.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", "", // No flow for UDP logger.NOP(), "", ) if err != nil { panic(err) } // Example 1: Standard UDP packet connection upstream1, _ := net.Dial("tcp", "vless.example.com:443") destination := M.ParseSocksaddr("8.8.8.8:53") packetConn, err := client.DialPacketConn(upstream1, destination) if err != nil { upstream1.Close() panic(err) } defer packetConn.Close() // Send UDP data _, err = packetConn.Write([]byte("DNS query data")) if err != nil { panic(err) } // Example 2: XUDP for enhanced UDP with addressing upstream2, _ := net.Dial("tcp", "vless.example.com:443") xudpConn, err := client.DialXUDPPacketConn(upstream2, M.ParseSocksaddr("0.0.0.0:0")) if err != nil { upstream2.Close() panic(err) } defer xudpConn.Close() // Write packet to specific destination buffer := buf.NewSize(512) buffer.Write([]byte("XUDP packet data")) target := M.ParseSocksaddr("192.168.1.1:53") err = xudpConn.WritePacket(buffer, target) if err != nil { panic(err) } // Read with source address information recvBuf := buf.NewSize(2048) srcAddr, err := xudpConn.ReadPacket(recvBuf) if err != nil { panic(err) } defer recvBuf.Release() println("Received from", srcAddr.String()) } ``` -------------------------------- ### Create VLESS Client for Basic Proxy Connections in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This Go code demonstrates how to create a VLESS client to establish basic proxy connections. It supports optional XTLS vision flow control. Dependencies include the sing-vmess library. The function takes a user UUID, flow control type, logger, and encryption options as input, and returns a VLESS client for establishing connections. ```go package main import ( "net" "github.com/sagernet/sing-vmess/vless" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/logger" ) func main() { // Create VLESS client client, err := vless.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", // User UUID "xtls-rprx-vision", // Flow: "" or "xtls-rprx-vision" logger.NOP(), // Logger "", // Encryption options (empty for none) ) if err != nil { panic(err) } // Connect to VLESS server (typically over TLS) upstream, err := net.Dial("tcp", "vless.example.com:443") if err != nil { panic(err) } destination := M.ParseSocksaddr("www.example.com:443") // Dial connection through VLESS conn, err := client.DialConn(upstream, destination) if err != nil { upstream.Close() panic(err) } defer conn.Close() // Use connection for HTTPS traffic _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n")) if err != nil { panic(err) } response := make([]byte, 4096) n, err := conn.Read(response) if err != nil { panic(err) } println("Received:", string(response[:n])) } ``` -------------------------------- ### Creating and Dialing VMess Client Connections in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This snippet demonstrates initializing a VMess client with UUID, security type, and AlterID, then dialing a TCP connection to a destination via the proxy server. It depends on the sing-vmess and sing/common/metadata packages; inputs include server address and destination sockaddr, outputs a proxied connection for reading/writing. Limitations include requiring a valid upstream connection and handling errors for failed handshakes. ```go package main import ( "net" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" ) func main() { // Create VMess client with user UUID and security type client, err := vmess.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", // User UUID "aes-128-gcm", // Security: "none", "aes-128-cfb", "aes-128-gcm", "chacha20-poly1305", "auto" 0, // AlterID (0 for AEAD, >0 for legacy) ) if err != nil { panic(err) } // Establish TCP connection to VMess server upstream, err := net.Dial("tcp", "proxy.example.com:443") if err != nil { panic(err) } // Dial through VMess to final destination destination := M.ParseSocksaddr("www.google.com:443") conn, err := client.DialConn(upstream, destination) if err != nil { upstream.Close() panic(err) } defer conn.Close() // Use connection for encrypted communication _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n")) if err != nil { panic(err) } buffer := make([]byte, 4096) n, err := conn.Read(buffer) if err != nil { panic(err) } println(string(buffer[:n])) } ``` -------------------------------- ### Establishing Early VMess Connections for Zero RTT in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This code shows creating an early VMess connection that postpones the handshake until the first write operation, enabling zero RTT latency. It relies on the same dependencies as standard client creation; inputs are client config and destination, outputs a deferred-handshake connection. Limitations involve potential handshake failures on first write and suitability for scenarios needing immediate data send. ```go package main import ( "net" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" ) func main() { client, err := vmess.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", "chacha20-poly1305", 0, ) if err != nil { panic(err) } upstream, err := net.Dial("tcp", "proxy.example.com:443") if err != nil { panic(err) } destination := M.ParseSocksaddr("api.example.com:443") // Early connection doesn't send handshake immediately conn := client.DialEarlyConn(upstream, destination) defer conn.Close() // Handshake is sent with first write (zero RTT) payload := []byte("GET /api/data HTTP/1.1\r\nHost: api.example.com\r\n\r\n") _, err = conn.Write(payload) if err != nil { panic(err) } response := make([]byte, 8192) n, err := conn.Read(response) if err != nil { panic(err) } println("Response:", string(response[:n])) } ``` -------------------------------- ### VMess Client XUDP Connection in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt Demonstrates setting up a VMess client that uses the XUDP protocol for connecting to a proxy. It establishes a connection, sends a UDP packet with a specific destination, and receives a response, preserving source address information. Requires the 'sing-vmess' and 'sing' libraries. ```go package main import ( "net" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/buf" ) func main() { client, err := vmess.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", "aes-128-gcm", 0, ) if err != nil { panic(err) } upstream, err := net.Dial("tcp", "proxy.example.com:443") if err != nil { panic(err) } destination := M.ParseSocksaddr("example.com:0") // Create XUDP connection with mux support xudpConn, err := client.DialXUDPPacketConn(upstream, destination) if err != nil { upstream.Close() panic(err) } defer xudpConn.Close() // Write packet with specific destination buffer := buf.NewSize(256) buffer.Write([]byte("Hello XUDP")) targetAddr := M.ParseSocksaddr("192.168.1.100:8080") err = xudpConn.WritePacket(buffer, targetAddr) if err != nil { panic(err) } // Read packet with source address recvBuffer := buf.NewSize(2048) srcAddr, err := xudpConn.ReadPacket(recvBuffer) if err != nil { panic(err) } println("Received from", srcAddr.String(), ": ", string(recvBuffer.Bytes())) recvBuffer.Release() } ``` -------------------------------- ### Configure VMess Client with Advanced Options in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This Go code illustrates how to configure a VMess client with advanced options using the sing-vmess library. It allows for enabling global padding, authenticated length encryption, and custom time functions. These options enhance traffic obfuscation and security. The function signature for NewClient includes parameters for UUID, cipher, port, and variadic client options. ```go package main import ( "time" "github.com/sagernet/sing-vmess" ) func main() { // Create client with advanced options client, err := vmess.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", "aes-128-gcm", 0, vmess.ClientWithGlobalPadding(), // Enable global padding vmess.ClientWithAuthenticatedLength(), // Enable authenticated length vmess.ClientWithTimeFunc(time.Now), // Custom time function ) if err != nil { panic(err) } // GlobalPadding adds random padding to all chunks for traffic obfuscation // AuthenticatedLength encrypts chunk length information // TimeFunc allows custom time source (useful for testing or time sync) _ = client // Use client for connections as shown in previous examples } ``` -------------------------------- ### Implement Mux-aware VMess Server in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt This snippet creates a VMess server with multiplexing support using the sing-vmess library. It includes a MuxHandler for TCP and UDP stream forwarding, user configuration, and a listener on port 8388. Requires the sing-vmess and related sing packages. ```go package main import ( "context" "net" "github.com/sagernet/sing-vmess" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) // Mux-aware handler type MuxHandler struct{} func (h *MuxHandler) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) { // Handle individual TCP stream within mux remote, err := net.Dial("tcp", destination.String()) if err != nil { conn.Close() return } // Bidirectional forwarding go copyData(conn, remote) copyData(remote, conn) remote.Close() conn.Close() } func (h *MuxHandler) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) { // Handle UDP stream within mux defer conn.Close() remote, err := net.ListenPacket("udp", "") if err != nil { return } defer remote.Close() buffer := make([]byte, 65535) for { n, _, err := conn.ReadFrom(buffer) if err != nil { break } _, _ = remote.WriteTo(buffer[:n], destination.UDPAddr()) } } func copyData(dst net.Conn, src net.Conn) { buffer := make([]byte, 32768) for { n, err := src.Read(buffer) if err != nil { break } _, err = dst.Write(buffer[:n]) if err != nil { break } } } func main() { handler := &MuxHandler{} service := vmess.NewService[string](handler) // Configure service with users _ = service.UpdateUsers( []string{"user1"}, []string{"b831381d-6324-4d53-ad4f-8cda48b30811"}, []int{0}, ) _ = service.Start() defer service.Close() // Accept connections and handle mux listener, _ := net.Listen("tcp", ":8388") defer listener.Close() println("Mux-enabled VMess server on :8388") for { conn, err := listener.Accept() if err != nil { continue } go func(c net.Conn) { ctx := context.Background() source := M.SocksaddrFromNet(c.RemoteAddr()) // HandleMuxConnection is called automatically by service _ = service.NewConnection(ctx, c, source, nil) }(conn) } } ``` -------------------------------- ### Define VMess Protocol Constants in Go Source: https://context7.com/xchacha20-poly1305/sing-vmess/llms.txt Declares security types, command types, and request options as constants for VMess protocol configuration. Includes constants for AES-128-CFB, AES-128-GCM, ChaCha20-Poly1305, and None security modes. Defines TCP, UDP, and Mux command types. Specifies request options as bitflags for chunk streaming, connection reuse, chunk masking, global padding, and authenticated length. ```go package main import ( "github.com/sagernet/sing-vmess" ) func main() { // Security Types const ( SecurityTypeLegacy = 1 // AES-128-CFB (legacy) SecurityTypeAuto = 2 // Auto-select based on platform SecurityTypeAes128Gcm = 3 // AES-128-GCM (recommended) SecurityTypeChacha20Poly1305 = 4 // ChaCha20-Poly1305 SecurityTypeNone = 5 // No encryption (not recommended) ) // Command Types const ( CommandTCP = 1 // TCP connection CommandUDP = 2 // UDP connection CommandMux = 3 // Multiplexed connection ) // Request Options (bitflags) const ( RequestOptionChunkStream = 1 // Use chunk streaming RequestOptionConnectionReuse = 2 // Enable connection reuse RequestOptionChunkMasking = 4 // Mask chunk boundaries RequestOptionGlobalPadding = 8 // Add global padding RequestOptionAuthenticatedLength = 16 // Authenticate chunk lengths ) // Example: Creating client with auto security client, err := vmess.NewClient( "b831381d-6324-4d53-ad4f-8cda48b30811", "auto", // Will use AES-128-GCM on amd64/arm64, ChaCha20-Poly1305 otherwise 0, ) if err != nil { panic(err) } _ = client } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.