repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttpupgrade/client.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttpupgrade/client.go
package v2rayhttpupgrade import ( std_bufio "bufio" "context" "net" "net/http" "net/url" "strings" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/bufio" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" sHTTP "github.com/sagernet/sing/protocol/http" ) var _ adapter.V2RayClientTransport = (*Client)(nil) type Client struct { dialer N.Dialer tlsConfig tls.Config serverAddr M.Socksaddr requestURL url.URL headers http.Header host string } func NewClient(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayHTTPUpgradeOptions, tlsConfig tls.Config) (*Client, error) { if tlsConfig != nil { if len(tlsConfig.NextProtos()) == 0 { tlsConfig.SetNextProtos([]string{"http/1.1"}) } } var host string if options.Host != "" { host = options.Host } else if tlsConfig != nil && tlsConfig.ServerName() != "" { host = tlsConfig.ServerName() } else { host = serverAddr.String() } var requestURL url.URL if tlsConfig == nil { requestURL.Scheme = "http" } else { requestURL.Scheme = "https" } requestURL.Host = serverAddr.String() requestURL.Path = options.Path err := sHTTP.URLSetPath(&requestURL, options.Path) if err != nil { return nil, E.Cause(err, "parse path") } if !strings.HasPrefix(requestURL.Path, "/") { requestURL.Path = "/" + requestURL.Path } headers := make(http.Header) for key, value := range options.Headers { headers[key] = value } return &Client{ dialer: dialer, tlsConfig: tlsConfig, serverAddr: serverAddr, requestURL: requestURL, headers: headers, host: host, }, nil } func (c *Client) DialContext(ctx context.Context) (net.Conn, error) { conn, err := c.dialer.DialContext(ctx, N.NetworkTCP, c.serverAddr) if err != nil { return nil, err } if c.tlsConfig != nil { conn, err = tls.ClientHandshake(ctx, conn, c.tlsConfig) if err != nil { return nil, err } } request := &http.Request{ Method: http.MethodGet, URL: &c.requestURL, Header: c.headers.Clone(), Host: c.host, } request.Header.Set("Connection", "Upgrade") request.Header.Set("Upgrade", "websocket") err = request.Write(conn) if err != nil { return nil, err } bufReader := std_bufio.NewReader(conn) response, err := http.ReadResponse(bufReader, request) if err != nil { return nil, err } if response.StatusCode != 101 || !strings.EqualFold(response.Header.Get("Connection"), "upgrade") || !strings.EqualFold(response.Header.Get("Upgrade"), "websocket") { return nil, E.New("v2ray-http-upgrade: unexpected status: ", response.Status) } if bufReader.Buffered() > 0 { buffer := buf.NewSize(bufReader.Buffered()) _, err = buffer.ReadFullFrom(bufReader, buffer.Len()) if err != nil { return nil, err } conn = bufio.NewCachedConn(conn, buffer) } return conn, nil } func (c *Client) Close() error { return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttpupgrade/server.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttpupgrade/server.go
package v2rayhttpupgrade import ( "context" "net" "net/http" "os" "strings" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" aTLS "github.com/sagernet/sing/common/tls" sHttp "github.com/sagernet/sing/protocol/http" ) var _ adapter.V2RayServerTransport = (*Server)(nil) type Server struct { ctx context.Context tlsConfig tls.ServerConfig handler adapter.V2RayServerTransportHandler httpServer *http.Server host string path string headers http.Header } func NewServer(ctx context.Context, options option.V2RayHTTPUpgradeOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (*Server, error) { server := &Server{ ctx: ctx, tlsConfig: tlsConfig, handler: handler, host: options.Host, path: options.Path, headers: options.Headers.Build(), } if !strings.HasPrefix(server.path, "/") { server.path = "/" + server.path } server.httpServer = &http.Server{ Handler: server, ReadHeaderTimeout: C.TCPTimeout, MaxHeaderBytes: http.DefaultMaxHeaderBytes, BaseContext: func(net.Listener) context.Context { return ctx }, TLSNextProto: make(map[string]func(*http.Server, *tls.STDConn, http.Handler)), } return server, nil } type httpFlusher interface { FlushError() error } func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) { host := request.Host if len(s.host) > 0 && host != s.host { s.invalidRequest(writer, request, http.StatusBadRequest, E.New("bad host: ", host)) return } if request.URL.Path != s.path { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path)) return } if request.Method != http.MethodGet { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad method: ", request.Method)) return } if !strings.EqualFold(request.Header.Get("Connection"), "upgrade") { s.invalidRequest(writer, request, http.StatusNotFound, E.New("not a upgrade request")) return } if !strings.EqualFold(request.Header.Get("Upgrade"), "websocket") { s.invalidRequest(writer, request, http.StatusNotFound, E.New("not a websocket request")) return } if request.Header.Get("Sec-WebSocket-Key") != "" { s.invalidRequest(writer, request, http.StatusNotFound, E.New("real websocket request received")) return } writer.Header().Set("Connection", "upgrade") writer.Header().Set("Upgrade", "websocket") writer.WriteHeader(http.StatusSwitchingProtocols) if flusher, isFlusher := writer.(httpFlusher); isFlusher { err := flusher.FlushError() if err != nil { s.invalidRequest(writer, request, http.StatusInternalServerError, E.New("flush response")) } } hijacker, canHijack := writer.(http.Hijacker) if !canHijack { s.invalidRequest(writer, request, http.StatusInternalServerError, E.New("invalid connection, maybe HTTP/2")) return } conn, _, err := hijacker.Hijack() if err != nil { s.invalidRequest(writer, request, http.StatusInternalServerError, E.Cause(err, "hijack failed")) return } var metadata M.Metadata metadata.Source = sHttp.SourceAddress(request) s.handler.NewConnection(request.Context(), conn, metadata) } func (s *Server) invalidRequest(writer http.ResponseWriter, request *http.Request, statusCode int, err error) { if statusCode > 0 { writer.WriteHeader(statusCode) } s.handler.NewError(request.Context(), E.Cause(err, "process connection from ", request.RemoteAddr)) } func (s *Server) Network() []string { return []string{N.NetworkTCP} } func (s *Server) Serve(listener net.Listener) error { if s.tlsConfig != nil { if len(s.tlsConfig.NextProtos()) == 0 { s.tlsConfig.SetNextProtos([]string{"http/1.1"}) } listener = aTLS.NewListener(listener, s.tlsConfig) } return s.httpServer.Serve(listener) } func (s *Server) ServePacket(listener net.PacketConn) error { return os.ErrInvalid } func (s *Server) Close() error { return common.Close(common.PtrOrNil(s.httpServer)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/dhcp/server.go
Bcore/windows/resources/sing-box-main/transport/dhcp/server.go
package dhcp import ( "context" "net" "net/netip" "net/url" "os" "runtime" "strings" "sync" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/dialer" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-dns" "github.com/sagernet/sing-tun" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/control" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/task" "github.com/sagernet/sing/common/x/list" "github.com/insomniacslk/dhcp/dhcpv4" mDNS "github.com/miekg/dns" ) func init() { dns.RegisterTransport([]string{"dhcp"}, func(options dns.TransportOptions) (dns.Transport, error) { return NewTransport(options) }) } type Transport struct { options dns.TransportOptions router adapter.Router interfaceName string autoInterface bool interfaceCallback *list.Element[tun.DefaultInterfaceUpdateCallback] transports []dns.Transport updateAccess sync.Mutex updatedAt time.Time } func NewTransport(options dns.TransportOptions) (*Transport, error) { linkURL, err := url.Parse(options.Address) if err != nil { return nil, err } if linkURL.Host == "" { return nil, E.New("missing interface name for DHCP") } router := adapter.RouterFromContext(options.Context) if router == nil { return nil, E.New("missing router in context") } transport := &Transport{ options: options, router: router, interfaceName: linkURL.Host, autoInterface: linkURL.Host == "auto", } return transport, nil } func (t *Transport) Name() string { return t.options.Name } func (t *Transport) Start() error { err := t.fetchServers() if err != nil { return err } if t.autoInterface { t.interfaceCallback = t.router.InterfaceMonitor().RegisterCallback(t.interfaceUpdated) } return nil } func (t *Transport) Reset() { for _, transport := range t.transports { transport.Reset() } } func (t *Transport) Close() error { for _, transport := range t.transports { transport.Close() } if t.interfaceCallback != nil { t.router.InterfaceMonitor().UnregisterCallback(t.interfaceCallback) } return nil } func (t *Transport) Raw() bool { return true } func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg, error) { err := t.fetchServers() if err != nil { return nil, err } if len(t.transports) == 0 { return nil, E.New("dhcp: empty DNS servers from response") } var response *mDNS.Msg for _, transport := range t.transports { response, err = transport.Exchange(ctx, message) if err == nil { return response, nil } } return nil, err } func (t *Transport) fetchInterface() (*net.Interface, error) { interfaceName := t.interfaceName if t.autoInterface { if t.router.InterfaceMonitor() == nil { return nil, E.New("missing monitor for auto DHCP, set route.auto_detect_interface") } interfaceName = t.router.InterfaceMonitor().DefaultInterfaceName(netip.Addr{}) } if interfaceName == "" { return nil, E.New("missing default interface") } return net.InterfaceByName(interfaceName) } func (t *Transport) fetchServers() error { if time.Since(t.updatedAt) < C.DHCPTTL { return nil } t.updateAccess.Lock() defer t.updateAccess.Unlock() if time.Since(t.updatedAt) < C.DHCPTTL { return nil } return t.updateServers() } func (t *Transport) updateServers() error { iface, err := t.fetchInterface() if err != nil { return E.Cause(err, "dhcp: prepare interface") } t.options.Logger.Info("dhcp: query DNS servers on ", iface.Name) fetchCtx, cancel := context.WithTimeout(t.options.Context, C.DHCPTimeout) err = t.fetchServers0(fetchCtx, iface) cancel() if err != nil { return err } else if len(t.transports) == 0 { return E.New("dhcp: empty DNS servers response") } else { t.updatedAt = time.Now() return nil } } func (t *Transport) interfaceUpdated(int) { err := t.updateServers() if err != nil { t.options.Logger.Error("update servers: ", err) } } func (t *Transport) fetchServers0(ctx context.Context, iface *net.Interface) error { var listener net.ListenConfig listener.Control = control.Append(listener.Control, control.BindToInterface(t.router.InterfaceFinder(), iface.Name, iface.Index)) listener.Control = control.Append(listener.Control, control.ReuseAddr()) listenAddr := "0.0.0.0:68" if runtime.GOOS == "linux" || runtime.GOOS == "android" { listenAddr = "255.255.255.255:68" } packetConn, err := listener.ListenPacket(t.options.Context, "udp4", listenAddr) if err != nil { return err } defer packetConn.Close() discovery, err := dhcpv4.NewDiscovery(iface.HardwareAddr, dhcpv4.WithBroadcast(true), dhcpv4.WithRequestedOptions(dhcpv4.OptionDomainNameServer)) if err != nil { return err } _, err = packetConn.WriteTo(discovery.ToBytes(), &net.UDPAddr{IP: net.IPv4bcast, Port: 67}) if err != nil { return err } var group task.Group group.Append0(func(ctx context.Context) error { return t.fetchServersResponse(iface, packetConn, discovery.TransactionID) }) group.Cleanup(func() { packetConn.Close() }) return group.Run(ctx) } func (t *Transport) fetchServersResponse(iface *net.Interface, packetConn net.PacketConn, transactionID dhcpv4.TransactionID) error { buffer := buf.NewSize(dhcpv4.MaxMessageSize) defer buffer.Release() for { _, _, err := buffer.ReadPacketFrom(packetConn) if err != nil { return err } dhcpPacket, err := dhcpv4.FromBytes(buffer.Bytes()) if err != nil { t.options.Logger.Trace("dhcp: parse DHCP response: ", err) return err } if dhcpPacket.MessageType() != dhcpv4.MessageTypeOffer { t.options.Logger.Trace("dhcp: expected OFFER response, but got ", dhcpPacket.MessageType()) continue } if dhcpPacket.TransactionID != transactionID { t.options.Logger.Trace("dhcp: expected transaction ID ", transactionID, ", but got ", dhcpPacket.TransactionID) continue } dns := dhcpPacket.DNS() if len(dns) == 0 { return nil } var addrs []netip.Addr for _, ip := range dns { addr, _ := netip.AddrFromSlice(ip) addrs = append(addrs, addr.Unmap()) } return t.recreateServers(iface, addrs) } } func (t *Transport) recreateServers(iface *net.Interface, serverAddrs []netip.Addr) error { if len(serverAddrs) > 0 { t.options.Logger.Info("dhcp: updated DNS servers from ", iface.Name, ": [", strings.Join(common.Map(serverAddrs, func(it netip.Addr) string { return it.String() }), ","), "]") } serverDialer := common.Must1(dialer.NewDefault(t.router, option.DialerOptions{ BindInterface: iface.Name, UDPFragmentDefault: true, })) var transports []dns.Transport for _, serverAddr := range serverAddrs { newOptions := t.options newOptions.Address = serverAddr.String() newOptions.Dialer = serverDialer serverTransport, err := dns.NewUDPTransport(newOptions) if err != nil { return E.Cause(err, "create UDP transport from DHCP result: ", serverAddr) } transports = append(transports, serverTransport) } for _, transport := range t.transports { transport.Close() } t.transports = transports return nil } func (t *Transport) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) { return nil, os.ErrInvalid }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/client.go
Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/client.go
package v2raywebsocket import ( "context" "net" "net/http" "net/url" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/bufio" "github.com/sagernet/sing/common/bufio/deadline" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" sHTTP "github.com/sagernet/sing/protocol/http" "github.com/sagernet/ws" ) var _ adapter.V2RayClientTransport = (*Client)(nil) type Client struct { dialer N.Dialer tlsConfig tls.Config serverAddr M.Socksaddr requestURL url.URL headers http.Header maxEarlyData uint32 earlyDataHeaderName string } func NewClient(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayWebsocketOptions, tlsConfig tls.Config) (adapter.V2RayClientTransport, error) { if tlsConfig != nil { if len(tlsConfig.NextProtos()) == 0 { tlsConfig.SetNextProtos([]string{"http/1.1"}) } } var requestURL url.URL if tlsConfig == nil { requestURL.Scheme = "ws" } else { requestURL.Scheme = "wss" } requestURL.Host = serverAddr.String() requestURL.Path = options.Path err := sHTTP.URLSetPath(&requestURL, options.Path) if err != nil { return nil, E.Cause(err, "parse path") } if !strings.HasPrefix(requestURL.Path, "/") { requestURL.Path = "/" + requestURL.Path } headers := options.Headers.Build() if host := headers.Get("Host"); host != "" { headers.Del("Host") requestURL.Host = host } if headers.Get("User-Agent") == "" { headers.Set("User-Agent", "Go-http-client/1.1") } return &Client{ dialer, tlsConfig, serverAddr, requestURL, headers, options.MaxEarlyData, options.EarlyDataHeaderName, }, nil } func (c *Client) dialContext(ctx context.Context, requestURL *url.URL, headers http.Header) (*WebsocketConn, error) { conn, err := c.dialer.DialContext(ctx, N.NetworkTCP, c.serverAddr) if err != nil { return nil, err } if c.tlsConfig != nil { conn, err = tls.ClientHandshake(ctx, conn, c.tlsConfig) if err != nil { return nil, err } } var deadlineConn net.Conn if deadline.NeedAdditionalReadDeadline(conn) { deadlineConn = deadline.NewConn(conn) } else { deadlineConn = conn } err = deadlineConn.SetDeadline(time.Now().Add(C.TCPTimeout)) if err != nil { return nil, E.Cause(err, "set read deadline") } var protocols []string if protocolHeader := headers.Get("Sec-WebSocket-Protocol"); protocolHeader != "" { protocols = []string{protocolHeader} headers.Del("Sec-WebSocket-Protocol") } reader, _, err := ws.Dialer{Header: ws.HandshakeHeaderHTTP(headers), Protocols: protocols}.Upgrade(deadlineConn, requestURL) deadlineConn.SetDeadline(time.Time{}) if err != nil { return nil, err } if reader != nil { buffer := buf.NewSize(reader.Buffered()) _, err = buffer.ReadFullFrom(reader, buffer.Len()) if err != nil { return nil, err } conn = bufio.NewCachedConn(conn, buffer) } return NewConn(conn, nil, ws.StateClientSide), nil } func (c *Client) DialContext(ctx context.Context) (net.Conn, error) { if c.maxEarlyData <= 0 { conn, err := c.dialContext(ctx, &c.requestURL, c.headers) if err != nil { return nil, err } return conn, nil } else { return &EarlyWebsocketConn{Client: c, ctx: ctx, create: make(chan struct{})}, nil } } func (c *Client) Close() error { return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/deadline.go
Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/deadline.go
package v2raywebsocket import ( "net" "time" ) type deadConn struct { net.Conn } func (c *deadConn) SetDeadline(t time.Time) error { return nil } func (c *deadConn) SetReadDeadline(t time.Time) error { return nil } func (c *deadConn) SetWriteDeadline(t time.Time) error { return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/writer.go
Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/writer.go
package v2raywebsocket import ( "encoding/binary" "io" "math/rand" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/bufio" N "github.com/sagernet/sing/common/network" "github.com/sagernet/ws" ) type Writer struct { writer N.ExtendedWriter isServer bool } func NewWriter(writer io.Writer, state ws.State) *Writer { return &Writer{ bufio.NewExtendedWriter(writer), state == ws.StateServerSide, } } func (w *Writer) WriteBuffer(buffer *buf.Buffer) error { var payloadBitLength int dataLen := buffer.Len() data := buffer.Bytes() if dataLen < 126 { payloadBitLength = 1 } else if dataLen < 65536 { payloadBitLength = 3 } else { payloadBitLength = 9 } var headerLen int headerLen += 1 // FIN / RSV / OPCODE headerLen += payloadBitLength if !w.isServer { headerLen += 4 // MASK KEY } header := buffer.ExtendHeader(headerLen) header[0] = byte(ws.OpBinary) | 0x80 if w.isServer { header[1] = 0 } else { header[1] = 1 << 7 } if dataLen < 126 { header[1] |= byte(dataLen) } else if dataLen < 65536 { header[1] |= 126 binary.BigEndian.PutUint16(header[2:], uint16(dataLen)) } else { header[1] |= 127 binary.BigEndian.PutUint64(header[2:], uint64(dataLen)) } if !w.isServer { maskKey := rand.Uint32() binary.BigEndian.PutUint32(header[1+payloadBitLength:], maskKey) ws.Cipher(data, *(*[4]byte)(header[1+payloadBitLength:]), 0) } return w.writer.WriteBuffer(buffer) } func (w *Writer) FrontHeadroom() int { return 14 }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/conn.go
Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/conn.go
package v2raywebsocket import ( "context" "encoding/base64" "io" "net" "os" "sync" "time" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/debug" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/ws" "github.com/sagernet/ws/wsutil" ) type WebsocketConn struct { net.Conn *Writer state ws.State reader *wsutil.Reader controlHandler wsutil.FrameHandlerFunc remoteAddr net.Addr } func NewConn(conn net.Conn, remoteAddr net.Addr, state ws.State) *WebsocketConn { controlHandler := wsutil.ControlFrameHandler(conn, state) return &WebsocketConn{ Conn: conn, state: state, reader: &wsutil.Reader{ Source: conn, State: state, SkipHeaderCheck: !debug.Enabled, OnIntermediate: controlHandler, }, controlHandler: controlHandler, remoteAddr: remoteAddr, Writer: NewWriter(conn, state), } } func (c *WebsocketConn) Close() error { c.Conn.SetWriteDeadline(time.Now().Add(C.TCPTimeout)) frame := ws.NewCloseFrame(ws.NewCloseFrameBody( ws.StatusNormalClosure, "", )) if c.state == ws.StateClientSide { frame = ws.MaskFrameInPlace(frame) } ws.WriteFrame(c.Conn, frame) c.Conn.Close() return nil } func (c *WebsocketConn) Read(b []byte) (n int, err error) { var header ws.Header for { n, err = c.reader.Read(b) if n > 0 { err = nil return } if !E.IsMulti(err, io.EOF, wsutil.ErrNoFrameAdvance) { return } header, err = c.reader.NextFrame() if err != nil { return } if header.OpCode.IsControl() { err = c.controlHandler(header, c.reader) if err != nil { return } continue } if header.OpCode&ws.OpBinary == 0 { err = c.reader.Discard() if err != nil { return } continue } } } func (c *WebsocketConn) Write(p []byte) (n int, err error) { err = wsutil.WriteMessage(c.Conn, c.state, ws.OpBinary, p) if err != nil { return } n = len(p) return } func (c *WebsocketConn) RemoteAddr() net.Addr { if c.remoteAddr != nil { return c.remoteAddr } return c.Conn.RemoteAddr() } func (c *WebsocketConn) SetDeadline(t time.Time) error { return os.ErrInvalid } func (c *WebsocketConn) SetReadDeadline(t time.Time) error { return os.ErrInvalid } func (c *WebsocketConn) SetWriteDeadline(t time.Time) error { return os.ErrInvalid } func (c *WebsocketConn) NeedAdditionalReadDeadline() bool { return true } func (c *WebsocketConn) Upstream() any { return c.Conn } type EarlyWebsocketConn struct { *Client ctx context.Context conn *WebsocketConn access sync.Mutex create chan struct{} err error } func (c *EarlyWebsocketConn) Read(b []byte) (n int, err error) { if c.conn == nil { <-c.create if c.err != nil { return 0, c.err } } return c.conn.Read(b) } func (c *EarlyWebsocketConn) writeRequest(content []byte) error { var ( earlyData []byte lateData []byte conn *WebsocketConn err error ) if len(content) > int(c.maxEarlyData) { earlyData = content[:c.maxEarlyData] lateData = content[c.maxEarlyData:] } else { earlyData = content } if len(earlyData) > 0 { earlyDataString := base64.RawURLEncoding.EncodeToString(earlyData) if c.earlyDataHeaderName == "" { requestURL := c.requestURL requestURL.Path += earlyDataString conn, err = c.dialContext(c.ctx, &requestURL, c.headers) } else { headers := c.headers.Clone() headers.Set(c.earlyDataHeaderName, earlyDataString) conn, err = c.dialContext(c.ctx, &c.requestURL, headers) } } else { conn, err = c.dialContext(c.ctx, &c.requestURL, c.headers) } if err != nil { return err } if len(lateData) > 0 { _, err = conn.Write(lateData) if err != nil { return err } } c.conn = conn return nil } func (c *EarlyWebsocketConn) Write(b []byte) (n int, err error) { if c.conn != nil { return c.conn.Write(b) } c.access.Lock() defer c.access.Unlock() if c.err != nil { return 0, c.err } if c.conn != nil { return c.conn.Write(b) } err = c.writeRequest(b) c.err = err close(c.create) if err != nil { return } return len(b), nil } func (c *EarlyWebsocketConn) WriteBuffer(buffer *buf.Buffer) error { if c.conn != nil { return c.conn.WriteBuffer(buffer) } c.access.Lock() defer c.access.Unlock() if c.conn != nil { return c.conn.WriteBuffer(buffer) } if c.err != nil { return c.err } err := c.writeRequest(buffer.Bytes()) c.err = err close(c.create) return err } func (c *EarlyWebsocketConn) Close() error { if c.conn == nil { return nil } return c.conn.Close() } func (c *EarlyWebsocketConn) LocalAddr() net.Addr { if c.conn == nil { return M.Socksaddr{} } return c.conn.LocalAddr() } func (c *EarlyWebsocketConn) RemoteAddr() net.Addr { if c.conn == nil { return M.Socksaddr{} } return c.conn.RemoteAddr() } func (c *EarlyWebsocketConn) SetDeadline(t time.Time) error { return os.ErrInvalid } func (c *EarlyWebsocketConn) SetReadDeadline(t time.Time) error { return os.ErrInvalid } func (c *EarlyWebsocketConn) SetWriteDeadline(t time.Time) error { return os.ErrInvalid } func (c *EarlyWebsocketConn) NeedAdditionalReadDeadline() bool { return true } func (c *EarlyWebsocketConn) Upstream() any { return common.PtrOrNil(c.conn) } func (c *EarlyWebsocketConn) LazyHeadroom() bool { return c.conn == nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/server.go
Bcore/windows/resources/sing-box-main/transport/v2raywebsocket/server.go
package v2raywebsocket import ( "context" "encoding/base64" "net" "net/http" "os" "strings" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/bufio" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" aTLS "github.com/sagernet/sing/common/tls" sHttp "github.com/sagernet/sing/protocol/http" "github.com/sagernet/ws" ) var _ adapter.V2RayServerTransport = (*Server)(nil) type Server struct { ctx context.Context tlsConfig tls.ServerConfig handler adapter.V2RayServerTransportHandler httpServer *http.Server path string maxEarlyData uint32 earlyDataHeaderName string upgrader ws.HTTPUpgrader } func NewServer(ctx context.Context, options option.V2RayWebsocketOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (*Server, error) { server := &Server{ ctx: ctx, tlsConfig: tlsConfig, handler: handler, path: options.Path, maxEarlyData: options.MaxEarlyData, earlyDataHeaderName: options.EarlyDataHeaderName, upgrader: ws.HTTPUpgrader{ Timeout: C.TCPTimeout, Header: options.Headers.Build(), }, } if !strings.HasPrefix(server.path, "/") { server.path = "/" + server.path } server.httpServer = &http.Server{ Handler: server, ReadHeaderTimeout: C.TCPTimeout, MaxHeaderBytes: http.DefaultMaxHeaderBytes, BaseContext: func(net.Listener) context.Context { return ctx }, } return server, nil } func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) { if s.maxEarlyData == 0 || s.earlyDataHeaderName != "" { if request.URL.Path != s.path { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path)) return } } var ( earlyData []byte err error conn net.Conn ) if s.earlyDataHeaderName == "" { if strings.HasPrefix(request.URL.RequestURI(), s.path) { earlyDataStr := request.URL.RequestURI()[len(s.path):] earlyData, err = base64.RawURLEncoding.DecodeString(earlyDataStr) } else { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path)) return } } else { if request.URL.Path != s.path { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path)) return } earlyDataStr := request.Header.Get(s.earlyDataHeaderName) if earlyDataStr != "" { earlyData, err = base64.RawURLEncoding.DecodeString(earlyDataStr) } } if err != nil { s.invalidRequest(writer, request, http.StatusBadRequest, E.Cause(err, "decode early data")) return } wsConn, _, _, err := ws.UpgradeHTTP(request, writer) if err != nil { s.invalidRequest(writer, request, 0, E.Cause(err, "upgrade websocket connection")) return } var metadata M.Metadata metadata.Source = sHttp.SourceAddress(request) conn = NewConn(wsConn, metadata.Source.TCPAddr(), ws.StateServerSide) if len(earlyData) > 0 { conn = bufio.NewCachedConn(conn, buf.As(earlyData)) } s.handler.NewConnection(request.Context(), conn, metadata) } func (s *Server) invalidRequest(writer http.ResponseWriter, request *http.Request, statusCode int, err error) { if statusCode > 0 { writer.WriteHeader(statusCode) } s.handler.NewError(request.Context(), E.Cause(err, "process connection from ", request.RemoteAddr)) } func (s *Server) Network() []string { return []string{N.NetworkTCP} } func (s *Server) Serve(listener net.Listener) error { if s.tlsConfig != nil { listener = aTLS.NewListener(listener, s.tlsConfig) } return s.httpServer.Serve(listener) } func (s *Server) ServePacket(listener net.PacketConn) error { return os.ErrInvalid } func (s *Server) Close() error { return common.Close(common.PtrOrNil(s.httpServer)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/simple-obfs/http.go
Bcore/windows/resources/sing-box-main/transport/simple-obfs/http.go
package obfs import ( "bytes" "encoding/base64" "fmt" "io" "math/rand" "net" "net/http" B "github.com/sagernet/sing/common/buf" ) // HTTPObfs is shadowsocks http simple-obfs implementation type HTTPObfs struct { net.Conn host string port string buf []byte offset int firstRequest bool firstResponse bool } func (ho *HTTPObfs) Read(b []byte) (int, error) { if ho.buf != nil { n := copy(b, ho.buf[ho.offset:]) ho.offset += n if ho.offset == len(ho.buf) { B.Put(ho.buf) ho.buf = nil } return n, nil } if ho.firstResponse { buf := B.Get(B.BufferSize) n, err := ho.Conn.Read(buf) if err != nil { B.Put(buf) return 0, err } idx := bytes.Index(buf[:n], []byte("\r\n\r\n")) if idx == -1 { B.Put(buf) return 0, io.EOF } ho.firstResponse = false length := n - (idx + 4) n = copy(b, buf[idx+4:n]) if length > n { ho.buf = buf[:idx+4+length] ho.offset = idx + 4 + n } else { B.Put(buf) } return n, nil } return ho.Conn.Read(b) } func (ho *HTTPObfs) Write(b []byte) (int, error) { if ho.firstRequest { randBytes := make([]byte, 16) rand.Read(randBytes) req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s/", ho.host), bytes.NewBuffer(b[:])) req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", rand.Int()%54, rand.Int()%2)) req.Header.Set("Upgrade", "websocket") req.Header.Set("Connection", "Upgrade") req.Host = ho.host if ho.port != "80" { req.Host = fmt.Sprintf("%s:%s", ho.host, ho.port) } req.Header.Set("Sec-WebSocket-Key", base64.URLEncoding.EncodeToString(randBytes)) req.ContentLength = int64(len(b)) err := req.Write(ho.Conn) ho.firstRequest = false return len(b), err } return ho.Conn.Write(b) } // NewHTTPObfs return a HTTPObfs func NewHTTPObfs(conn net.Conn, host string, port string) net.Conn { return &HTTPObfs{ Conn: conn, firstRequest: true, firstResponse: true, host: host, port: port, } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/simple-obfs/tls.go
Bcore/windows/resources/sing-box-main/transport/simple-obfs/tls.go
package obfs import ( "bytes" "encoding/binary" "io" "math/rand" "net" "time" B "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/random" ) func init() { random.InitializeSeed() } const ( chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024 ) // TLSObfs is shadowsocks tls simple-obfs implementation type TLSObfs struct { net.Conn server string remain int firstRequest bool firstResponse bool } func (to *TLSObfs) read(b []byte, discardN int) (int, error) { buf := B.Get(discardN) _, err := io.ReadFull(to.Conn, buf) B.Put(buf) if err != nil { return 0, err } sizeBuf := make([]byte, 2) _, err = io.ReadFull(to.Conn, sizeBuf) if err != nil { return 0, nil } length := int(binary.BigEndian.Uint16(sizeBuf)) if length > len(b) { n, err := to.Conn.Read(b) if err != nil { return n, err } to.remain = length - n return n, nil } return io.ReadFull(to.Conn, b[:length]) } func (to *TLSObfs) Read(b []byte) (int, error) { if to.remain > 0 { length := to.remain if length > len(b) { length = len(b) } n, err := io.ReadFull(to.Conn, b[:length]) to.remain -= n return n, err } if to.firstResponse { // type + ver + lensize + 91 = 96 // type + ver + lensize + 1 = 6 // type + ver = 3 to.firstResponse = false return to.read(b, 105) } // type + ver = 3 return to.read(b, 3) } func (to *TLSObfs) Write(b []byte) (int, error) { length := len(b) for i := 0; i < length; i += chunkSize { end := i + chunkSize if end > length { end = length } n, err := to.write(b[i:end]) if err != nil { return n, err } } return length, nil } func (to *TLSObfs) write(b []byte) (int, error) { if to.firstRequest { helloMsg := makeClientHelloMsg(b, to.server) _, err := to.Conn.Write(helloMsg) to.firstRequest = false return len(b), err } buf := B.NewSize(5 + len(b)) defer buf.Release() buf.Write([]byte{0x17, 0x03, 0x03}) binary.Write(buf, binary.BigEndian, uint16(len(b))) buf.Write(b) _, err := to.Conn.Write(buf.Bytes()) return len(b), err } // NewTLSObfs return a SimpleObfs func NewTLSObfs(conn net.Conn, server string) net.Conn { return &TLSObfs{ Conn: conn, server: server, firstRequest: true, firstResponse: true, } } func makeClientHelloMsg(data []byte, server string) []byte { random := make([]byte, 28) sessionID := make([]byte, 32) rand.Read(random) rand.Read(sessionID) buf := &bytes.Buffer{} // handshake, TLS 1.0 version, length buf.WriteByte(22) buf.Write([]byte{0x03, 0x01}) length := uint16(212 + len(data) + len(server)) buf.WriteByte(byte(length >> 8)) buf.WriteByte(byte(length & 0xff)) // clientHello, length, TLS 1.2 version buf.WriteByte(1) buf.WriteByte(0) binary.Write(buf, binary.BigEndian, uint16(208+len(data)+len(server))) buf.Write([]byte{0x03, 0x03}) // random with timestamp, sid len, sid binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix())) buf.Write(random) buf.WriteByte(32) buf.Write(sessionID) // cipher suites buf.Write([]byte{0x00, 0x38}) buf.Write([]byte{ 0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f, 0x00, 0x9e, 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a, 0xc0, 0x14, 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0x9d, 0x00, 0x9c, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x35, 0x00, 0x2f, 0x00, 0xff, }) // compression buf.Write([]byte{0x01, 0x00}) // extension length binary.Write(buf, binary.BigEndian, uint16(79+len(data)+len(server))) // session ticket buf.Write([]byte{0x00, 0x23}) binary.Write(buf, binary.BigEndian, uint16(len(data))) buf.Write(data) // server name buf.Write([]byte{0x00, 0x00}) binary.Write(buf, binary.BigEndian, uint16(len(server)+5)) binary.Write(buf, binary.BigEndian, uint16(len(server)+3)) buf.WriteByte(0) binary.Write(buf, binary.BigEndian, uint16(len(server))) buf.Write([]byte(server)) // ec_point buf.Write([]byte{0x00, 0x0b, 0x00, 0x04, 0x03, 0x01, 0x00, 0x02}) // groups buf.Write([]byte{0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18}) // signature buf.Write([]byte{ 0x00, 0x0d, 0x00, 0x20, 0x00, 0x1e, 0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05, 0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0x03, 0x01, 0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03, }) // encrypt then mac buf.Write([]byte{0x00, 0x16, 0x00, 0x00}) // extended master secret buf.Write([]byte{0x00, 0x17, 0x00, 0x00}) return buf.Bytes() }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/client.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/client.go
package v2raygrpc import ( "context" "net" "sync" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "golang.org/x/net/http2" "google.golang.org/grpc" "google.golang.org/grpc/backoff" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/keepalive" ) var _ adapter.V2RayClientTransport = (*Client)(nil) type Client struct { ctx context.Context dialer N.Dialer serverAddr string serviceName string dialOptions []grpc.DialOption conn *grpc.ClientConn connAccess sync.Mutex } func NewClient(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayGRPCOptions, tlsConfig tls.Config) (adapter.V2RayClientTransport, error) { var dialOptions []grpc.DialOption if tlsConfig != nil { if len(tlsConfig.NextProtos()) == 0 { tlsConfig.SetNextProtos([]string{http2.NextProtoTLS}) } dialOptions = append(dialOptions, grpc.WithTransportCredentials(NewTLSTransportCredentials(tlsConfig))) } else { dialOptions = append(dialOptions, grpc.WithTransportCredentials(insecure.NewCredentials())) } if options.IdleTimeout > 0 { dialOptions = append(dialOptions, grpc.WithKeepaliveParams(keepalive.ClientParameters{ Time: time.Duration(options.IdleTimeout), Timeout: time.Duration(options.PingTimeout), PermitWithoutStream: options.PermitWithoutStream, })) } dialOptions = append(dialOptions, grpc.WithConnectParams(grpc.ConnectParams{ Backoff: backoff.Config{ BaseDelay: 500 * time.Millisecond, Multiplier: 1.5, Jitter: 0.2, MaxDelay: 19 * time.Second, }, MinConnectTimeout: 5 * time.Second, })) dialOptions = append(dialOptions, grpc.WithContextDialer(func(ctx context.Context, server string) (net.Conn, error) { return dialer.DialContext(ctx, N.NetworkTCP, M.ParseSocksaddr(server)) })) dialOptions = append(dialOptions, grpc.WithReturnConnectionError()) return &Client{ ctx: ctx, dialer: dialer, serverAddr: serverAddr.String(), serviceName: options.ServiceName, dialOptions: dialOptions, }, nil } func (c *Client) connect() (*grpc.ClientConn, error) { conn := c.conn if conn != nil && conn.GetState() != connectivity.Shutdown { return conn, nil } c.connAccess.Lock() defer c.connAccess.Unlock() conn = c.conn if conn != nil && conn.GetState() != connectivity.Shutdown { return conn, nil } //nolint:staticcheck //goland:noinspection GoDeprecation conn, err := grpc.DialContext(c.ctx, c.serverAddr, c.dialOptions...) if err != nil { return nil, err } c.conn = conn return conn, nil } func (c *Client) DialContext(ctx context.Context) (net.Conn, error) { clientConn, err := c.connect() if err != nil { return nil, err } client := NewGunServiceClient(clientConn).(GunServiceCustomNameClient) ctx, cancel := common.ContextWithCancelCause(ctx) stream, err := client.TunCustomName(ctx, c.serviceName) if err != nil { cancel(err) return nil, err } return NewGRPCConn(stream, cancel), nil } func (c *Client) Close() error { c.connAccess.Lock() defer c.connAccess.Unlock() if c.conn != nil { c.conn.Close() c.conn = nil } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/stream.pb.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/stream.pb.go
package v2raygrpc import ( reflect "reflect" sync "sync" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type Hunk struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` } func (x *Hunk) Reset() { *x = Hunk{} if protoimpl.UnsafeEnabled { mi := &file_transport_v2raygrpc_stream_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Hunk) String() string { return protoimpl.X.MessageStringOf(x) } func (*Hunk) ProtoMessage() {} func (x *Hunk) ProtoReflect() protoreflect.Message { mi := &file_transport_v2raygrpc_stream_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Hunk.ProtoReflect.Descriptor instead. func (*Hunk) Descriptor() ([]byte, []int) { return file_transport_v2raygrpc_stream_proto_rawDescGZIP(), []int{0} } func (x *Hunk) GetData() []byte { if x != nil { return x.Data } return nil } var File_transport_v2raygrpc_stream_proto protoreflect.FileDescriptor var file_transport_v2raygrpc_stream_proto_rawDesc = []byte{ 0x0a, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x13, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x67, 0x72, 0x70, 0x63, 0x22, 0x1a, 0x0a, 0x04, 0x48, 0x75, 0x6e, 0x6b, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x4d, 0x0a, 0x0a, 0x47, 0x75, 0x6e, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x3f, 0x0a, 0x03, 0x54, 0x75, 0x6e, 0x12, 0x19, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x75, 0x6e, 0x6b, 0x1a, 0x19, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x76, 0x32, 0x72, 0x61, 0x79, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x48, 0x75, 0x6e, 0x6b, 0x28, 0x01, 0x30, 0x01, 0x42, 0x32, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x61, 0x67, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2f, 0x73, 0x69, 0x6e, 0x67, 0x2d, 0x62, 0x6f, 0x78, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_transport_v2raygrpc_stream_proto_rawDescOnce sync.Once file_transport_v2raygrpc_stream_proto_rawDescData = file_transport_v2raygrpc_stream_proto_rawDesc ) func file_transport_v2raygrpc_stream_proto_rawDescGZIP() []byte { file_transport_v2raygrpc_stream_proto_rawDescOnce.Do(func() { file_transport_v2raygrpc_stream_proto_rawDescData = protoimpl.X.CompressGZIP(file_transport_v2raygrpc_stream_proto_rawDescData) }) return file_transport_v2raygrpc_stream_proto_rawDescData } var ( file_transport_v2raygrpc_stream_proto_msgTypes = make([]protoimpl.MessageInfo, 1) file_transport_v2raygrpc_stream_proto_goTypes = []interface{}{ (*Hunk)(nil), // 0: transport.v2raygrpc.Hunk } ) var file_transport_v2raygrpc_stream_proto_depIdxs = []int32{ 0, // 0: transport.v2raygrpc.GunService.Tun:input_type -> transport.v2raygrpc.Hunk 0, // 1: transport.v2raygrpc.GunService.Tun:output_type -> transport.v2raygrpc.Hunk 1, // [1:2] is the sub-list for method output_type 0, // [0:1] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_transport_v2raygrpc_stream_proto_init() } func file_transport_v2raygrpc_stream_proto_init() { if File_transport_v2raygrpc_stream_proto != nil { return } if !protoimpl.UnsafeEnabled { file_transport_v2raygrpc_stream_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Hunk); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_transport_v2raygrpc_stream_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 1, }, GoTypes: file_transport_v2raygrpc_stream_proto_goTypes, DependencyIndexes: file_transport_v2raygrpc_stream_proto_depIdxs, MessageInfos: file_transport_v2raygrpc_stream_proto_msgTypes, }.Build() File_transport_v2raygrpc_stream_proto = out.File file_transport_v2raygrpc_stream_proto_rawDesc = nil file_transport_v2raygrpc_stream_proto_goTypes = nil file_transport_v2raygrpc_stream_proto_depIdxs = nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/tls_credentials.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/tls_credentials.go
package v2raygrpc import ( "context" "net" "os" "github.com/sagernet/sing-box/common/tls" internal_credentials "github.com/sagernet/sing-box/transport/v2raygrpc/credentials" "google.golang.org/grpc/credentials" ) type TLSTransportCredentials struct { config tls.Config } func NewTLSTransportCredentials(config tls.Config) credentials.TransportCredentials { return &TLSTransportCredentials{config} } func (c *TLSTransportCredentials) Info() credentials.ProtocolInfo { return credentials.ProtocolInfo{ SecurityProtocol: "tls", SecurityVersion: "1.2", ServerName: c.config.ServerName(), } } func (c *TLSTransportCredentials) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { cfg := c.config.Clone() if cfg.ServerName() == "" { serverName, _, err := net.SplitHostPort(authority) if err != nil { serverName = authority } cfg.SetServerName(serverName) } conn, err := tls.ClientHandshake(ctx, rawConn, cfg) if err != nil { return nil, nil, err } tlsInfo := credentials.TLSInfo{ State: conn.ConnectionState(), CommonAuthInfo: credentials.CommonAuthInfo{ SecurityLevel: credentials.PrivacyAndIntegrity, }, } id := internal_credentials.SPIFFEIDFromState(conn.ConnectionState()) if id != nil { tlsInfo.SPIFFEID = id } return internal_credentials.WrapSyscallConn(rawConn, conn), tlsInfo, nil } func (c *TLSTransportCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { serverConfig, isServer := c.config.(tls.ServerConfig) if !isServer { return nil, nil, os.ErrInvalid } conn, err := tls.ServerHandshake(context.Background(), rawConn, serverConfig) if err != nil { rawConn.Close() return nil, nil, err } tlsInfo := credentials.TLSInfo{ State: conn.ConnectionState(), CommonAuthInfo: credentials.CommonAuthInfo{ SecurityLevel: credentials.PrivacyAndIntegrity, }, } id := internal_credentials.SPIFFEIDFromState(conn.ConnectionState()) if id != nil { tlsInfo.SPIFFEID = id } return internal_credentials.WrapSyscallConn(rawConn, conn), tlsInfo, nil } func (c *TLSTransportCredentials) Clone() credentials.TransportCredentials { return NewTLSTransportCredentials(c.config) } func (c *TLSTransportCredentials) OverrideServerName(serverNameOverride string) error { c.config.SetServerName(serverNameOverride) return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/conn.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/conn.go
package v2raygrpc import ( "net" "os" "time" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/baderror" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) var _ net.Conn = (*GRPCConn)(nil) type GRPCConn struct { GunService cancel common.ContextCancelCauseFunc cache []byte } func NewGRPCConn(service GunService, cancel common.ContextCancelCauseFunc) *GRPCConn { if client, isClient := service.(GunService_TunClient); isClient { service = &clientConnWrapper{client} } return &GRPCConn{ GunService: service, cancel: cancel, } } func (c *GRPCConn) Read(b []byte) (n int, err error) { if len(c.cache) > 0 { n = copy(b, c.cache) c.cache = c.cache[n:] return } hunk, err := c.Recv() err = baderror.WrapGRPC(err) if err != nil { c.cancel(err) return } n = copy(b, hunk.Data) if n < len(hunk.Data) { c.cache = hunk.Data[n:] } return } func (c *GRPCConn) Write(b []byte) (n int, err error) { err = baderror.WrapGRPC(c.Send(&Hunk{Data: b})) if err != nil { c.cancel(err) return } return len(b), nil } func (c *GRPCConn) Close() error { c.cancel(net.ErrClosed) return nil } func (c *GRPCConn) LocalAddr() net.Addr { return M.Socksaddr{} } func (c *GRPCConn) RemoteAddr() net.Addr { return M.Socksaddr{} } func (c *GRPCConn) SetDeadline(t time.Time) error { return os.ErrInvalid } func (c *GRPCConn) SetReadDeadline(t time.Time) error { return os.ErrInvalid } func (c *GRPCConn) SetWriteDeadline(t time.Time) error { return os.ErrInvalid } func (c *GRPCConn) NeedAdditionalReadDeadline() bool { return true } func (c *GRPCConn) Upstream() any { return c.GunService } var _ N.WriteCloser = (*clientConnWrapper)(nil) type clientConnWrapper struct { GunService_TunClient } func (c *clientConnWrapper) CloseWrite() error { return c.CloseSend() }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/server.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/server.go
package v2raygrpc import ( "context" "net" "os" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "golang.org/x/net/http2" "google.golang.org/grpc" "google.golang.org/grpc/keepalive" gM "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" ) var _ adapter.V2RayServerTransport = (*Server)(nil) type Server struct { ctx context.Context handler N.TCPConnectionHandler server *grpc.Server } func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig tls.ServerConfig, handler N.TCPConnectionHandler) (*Server, error) { var serverOptions []grpc.ServerOption if tlsConfig != nil { if !common.Contains(tlsConfig.NextProtos(), http2.NextProtoTLS) { tlsConfig.SetNextProtos(append([]string{"h2"}, tlsConfig.NextProtos()...)) } serverOptions = append(serverOptions, grpc.Creds(NewTLSTransportCredentials(tlsConfig))) } if options.IdleTimeout > 0 { serverOptions = append(serverOptions, grpc.KeepaliveParams(keepalive.ServerParameters{ Time: time.Duration(options.IdleTimeout), Timeout: time.Duration(options.PingTimeout), })) } server := &Server{ctx, handler, grpc.NewServer(serverOptions...)} RegisterGunServiceCustomNameServer(server.server, server, options.ServiceName) return server, nil } func (s *Server) Tun(server GunService_TunServer) error { ctx, cancel := common.ContextWithCancelCause(s.ctx) conn := NewGRPCConn(server, cancel) var metadata M.Metadata if remotePeer, loaded := peer.FromContext(server.Context()); loaded { metadata.Source = M.SocksaddrFromNet(remotePeer.Addr) } if grpcMetadata, loaded := gM.FromIncomingContext(server.Context()); loaded { forwardFrom := strings.Join(grpcMetadata.Get("X-Forwarded-For"), ",") if forwardFrom != "" { for _, from := range strings.Split(forwardFrom, ",") { originAddr := M.ParseSocksaddr(from) if originAddr.IsValid() { metadata.Source = originAddr.Unwrap() } } } } go s.handler.NewConnection(ctx, conn, metadata) <-ctx.Done() return nil } func (s *Server) mustEmbedUnimplementedGunServiceServer() { } func (s *Server) Network() []string { return []string{N.NetworkTCP} } func (s *Server) Serve(listener net.Listener) error { return s.server.Serve(listener) } func (s *Server) ServePacket(listener net.PacketConn) error { return os.ErrInvalid } func (s *Server) Close() error { s.server.Stop() return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/custom_name.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/custom_name.go
package v2raygrpc import ( "context" "google.golang.org/grpc" ) type GunService interface { Context() context.Context Send(*Hunk) error Recv() (*Hunk, error) } func ServerDesc(name string) grpc.ServiceDesc { return grpc.ServiceDesc{ ServiceName: name, HandlerType: (*GunServiceServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "Tun", Handler: _GunService_Tun_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "gun.proto", } } func (c *gunServiceClient) TunCustomName(ctx context.Context, name string, opts ...grpc.CallOption) (GunService_TunClient, error) { stream, err := c.cc.NewStream(ctx, &ServerDesc(name).Streams[0], "/"+name+"/Tun", opts...) if err != nil { return nil, err } x := &gunServiceTunClient{stream} return x, nil } var _ GunServiceCustomNameClient = (*gunServiceClient)(nil) type GunServiceCustomNameClient interface { TunCustomName(ctx context.Context, name string, opts ...grpc.CallOption) (GunService_TunClient, error) Tun(ctx context.Context, opts ...grpc.CallOption) (GunService_TunClient, error) } func RegisterGunServiceCustomNameServer(s *grpc.Server, srv GunServiceServer, name string) { desc := ServerDesc(name) s.RegisterService(&desc, srv) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/stream_grpc.pb.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/stream_grpc.pb.go
package v2raygrpc import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 const ( GunService_Tun_FullMethodName = "/transport.v2raygrpc.GunService/Tun" ) // GunServiceClient is the client API for GunService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type GunServiceClient interface { Tun(ctx context.Context, opts ...grpc.CallOption) (GunService_TunClient, error) } type gunServiceClient struct { cc grpc.ClientConnInterface } func NewGunServiceClient(cc grpc.ClientConnInterface) GunServiceClient { return &gunServiceClient{cc} } func (c *gunServiceClient) Tun(ctx context.Context, opts ...grpc.CallOption) (GunService_TunClient, error) { stream, err := c.cc.NewStream(ctx, &GunService_ServiceDesc.Streams[0], GunService_Tun_FullMethodName, opts...) if err != nil { return nil, err } x := &gunServiceTunClient{stream} return x, nil } type GunService_TunClient interface { Send(*Hunk) error Recv() (*Hunk, error) grpc.ClientStream } type gunServiceTunClient struct { grpc.ClientStream } func (x *gunServiceTunClient) Send(m *Hunk) error { return x.ClientStream.SendMsg(m) } func (x *gunServiceTunClient) Recv() (*Hunk, error) { m := new(Hunk) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // GunServiceServer is the server API for GunService service. // All implementations must embed UnimplementedGunServiceServer // for forward compatibility type GunServiceServer interface { Tun(GunService_TunServer) error mustEmbedUnimplementedGunServiceServer() } // UnimplementedGunServiceServer must be embedded to have forward compatible implementations. type UnimplementedGunServiceServer struct{} func (UnimplementedGunServiceServer) Tun(GunService_TunServer) error { return status.Errorf(codes.Unimplemented, "method Tun not implemented") } func (UnimplementedGunServiceServer) mustEmbedUnimplementedGunServiceServer() {} // UnsafeGunServiceServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to GunServiceServer will // result in compilation errors. type UnsafeGunServiceServer interface { mustEmbedUnimplementedGunServiceServer() } func RegisterGunServiceServer(s grpc.ServiceRegistrar, srv GunServiceServer) { s.RegisterService(&GunService_ServiceDesc, srv) } func _GunService_Tun_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(GunServiceServer).Tun(&gunServiceTunServer{stream}) } type GunService_TunServer interface { Send(*Hunk) error Recv() (*Hunk, error) grpc.ServerStream } type gunServiceTunServer struct { grpc.ServerStream } func (x *gunServiceTunServer) Send(m *Hunk) error { return x.ServerStream.SendMsg(m) } func (x *gunServiceTunServer) Recv() (*Hunk, error) { m := new(Hunk) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // GunService_ServiceDesc is the grpc.ServiceDesc for GunService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var GunService_ServiceDesc = grpc.ServiceDesc{ ServiceName: "transport.v2raygrpc.GunService", HandlerType: (*GunServiceServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{ { StreamName: "Tun", Handler: _GunService_Tun_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "transport/v2raygrpc/stream.proto", }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/spiffe.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/spiffe.go
/* * * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Package credentials defines APIs for parsing SPIFFE ID. // // All APIs in this package are experimental. package credentials import ( "crypto/tls" "crypto/x509" "net/url" "google.golang.org/grpc/grpclog" ) var logger = grpclog.Component("credentials") // SPIFFEIDFromState parses the SPIFFE ID from State. If the SPIFFE ID format // is invalid, return nil with warning. func SPIFFEIDFromState(state tls.ConnectionState) *url.URL { if len(state.PeerCertificates) == 0 || len(state.PeerCertificates[0].URIs) == 0 { return nil } return SPIFFEIDFromCert(state.PeerCertificates[0]) } // SPIFFEIDFromCert parses the SPIFFE ID from x509.Certificate. If the SPIFFE // ID format is invalid, return nil with warning. func SPIFFEIDFromCert(cert *x509.Certificate) *url.URL { if cert == nil || cert.URIs == nil { return nil } var spiffeID *url.URL for _, uri := range cert.URIs { if uri == nil || uri.Scheme != "spiffe" || uri.Opaque != "" || (uri.User != nil && uri.User.Username() != "") { continue } // From this point, we assume the uri is intended for a SPIFFE ID. if len(uri.String()) > 2048 { logger.Warning("invalid SPIFFE ID: total ID length larger than 2048 bytes") return nil } if len(uri.Host) == 0 || len(uri.Path) == 0 { logger.Warning("invalid SPIFFE ID: domain or workload ID is empty") return nil } if len(uri.Host) > 255 { logger.Warning("invalid SPIFFE ID: domain length larger than 255 characters") return nil } // A valid SPIFFE certificate can only have exactly one URI SAN field. if len(cert.URIs) > 1 { logger.Warning("invalid SPIFFE ID: multiple URI SANs") return nil } spiffeID = uri } return spiffeID }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/syscallconn.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/syscallconn.go
/* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package credentials import ( "net" "syscall" ) type sysConn = syscall.Conn // syscallConn keeps reference of rawConn to support syscall.Conn for channelz. // SyscallConn() (the method in interface syscall.Conn) is explicitly // implemented on this type, // // Interface syscall.Conn is implemented by most net.Conn implementations (e.g. // TCPConn, UnixConn), but is not part of net.Conn interface. So wrapper conns // that embed net.Conn don't implement syscall.Conn. (Side note: tls.Conn // doesn't embed net.Conn, so even if syscall.Conn is part of net.Conn, it won't // help here). type syscallConn struct { net.Conn // sysConn is a type alias of syscall.Conn. It's necessary because the name // `Conn` collides with `net.Conn`. sysConn } // WrapSyscallConn tries to wrap rawConn and newConn into a net.Conn that // implements syscall.Conn. rawConn will be used to support syscall, and newConn // will be used for read/write. // // This function returns newConn if rawConn doesn't implement syscall.Conn. func WrapSyscallConn(rawConn, newConn net.Conn) net.Conn { sysConn, ok := rawConn.(syscall.Conn) if !ok { return newConn } return &syscallConn{ Conn: newConn, sysConn: sysConn, } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/credentials.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/credentials.go
/* * Copyright 2021 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package credentials import ( "context" ) // requestInfoKey is a struct to be used as the key to store RequestInfo in a // context. type requestInfoKey struct{} // NewRequestInfoContext creates a context with ri. func NewRequestInfoContext(ctx context.Context, ri interface{}) context.Context { return context.WithValue(ctx, requestInfoKey{}, ri) } // RequestInfoFromContext extracts the RequestInfo from ctx. func RequestInfoFromContext(ctx context.Context) interface{} { return ctx.Value(requestInfoKey{}) } // clientHandshakeInfoKey is a struct used as the key to store // ClientHandshakeInfo in a context. type clientHandshakeInfoKey struct{} // ClientHandshakeInfoFromContext extracts the ClientHandshakeInfo from ctx. func ClientHandshakeInfoFromContext(ctx context.Context) interface{} { return ctx.Value(clientHandshakeInfoKey{}) } // NewClientHandshakeInfoContext creates a context with chi. func NewClientHandshakeInfoContext(ctx context.Context, chi interface{}) context.Context { return context.WithValue(ctx, clientHandshakeInfoKey{}, chi) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/util.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpc/credentials/util.go
/* * * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package credentials import ( "crypto/tls" ) const alpnProtoStrH2 = "h2" // AppendH2ToNextProtos appends h2 to next protos. func AppendH2ToNextProtos(ps []string) []string { for _, p := range ps { if p == alpnProtoStrH2 { return ps } } ret := make([]string, 0, len(ps)+1) ret = append(ret, ps...) return append(ret, alpnProtoStrH2) } // CloneTLSConfig returns a shallow clone of the exported // fields of cfg, ignoring the unexported sync.Once, which // contains a mutex and must not be copied. // // If cfg is nil, a new zero tls.Config is returned. // // TODO: inline this function if possible. func CloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return cfg.Clone() }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/fakeip/memory.go
Bcore/windows/resources/sing-box-main/transport/fakeip/memory.go
package fakeip import ( "net/netip" "sync" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing/common/logger" ) var _ adapter.FakeIPStorage = (*MemoryStorage)(nil) type MemoryStorage struct { addressAccess sync.RWMutex domainAccess sync.RWMutex addressCache map[netip.Addr]string domainCache4 map[string]netip.Addr domainCache6 map[string]netip.Addr } func NewMemoryStorage() *MemoryStorage { return &MemoryStorage{ addressCache: make(map[netip.Addr]string), domainCache4: make(map[string]netip.Addr), domainCache6: make(map[string]netip.Addr), } } func (s *MemoryStorage) FakeIPMetadata() *adapter.FakeIPMetadata { return nil } func (s *MemoryStorage) FakeIPSaveMetadata(metadata *adapter.FakeIPMetadata) error { return nil } func (s *MemoryStorage) FakeIPSaveMetadataAsync(metadata *adapter.FakeIPMetadata) { } func (s *MemoryStorage) FakeIPStore(address netip.Addr, domain string) error { s.addressAccess.Lock() s.domainAccess.Lock() if oldDomain, loaded := s.addressCache[address]; loaded { if address.Is4() { delete(s.domainCache4, oldDomain) } else { delete(s.domainCache6, oldDomain) } } s.addressCache[address] = domain if address.Is4() { s.domainCache4[domain] = address } else { s.domainCache6[domain] = address } s.domainAccess.Unlock() s.addressAccess.Unlock() return nil } func (s *MemoryStorage) FakeIPStoreAsync(address netip.Addr, domain string, logger logger.Logger) { _ = s.FakeIPStore(address, domain) } func (s *MemoryStorage) FakeIPLoad(address netip.Addr) (string, bool) { s.addressAccess.RLock() defer s.addressAccess.RUnlock() domain, loaded := s.addressCache[address] return domain, loaded } func (s *MemoryStorage) FakeIPLoadDomain(domain string, isIPv6 bool) (netip.Addr, bool) { s.domainAccess.RLock() defer s.domainAccess.RUnlock() if !isIPv6 { address, loaded := s.domainCache4[domain] return address, loaded } else { address, loaded := s.domainCache6[domain] return address, loaded } } func (s *MemoryStorage) FakeIPReset() error { s.addressCache = make(map[netip.Addr]string) s.domainCache4 = make(map[string]netip.Addr) s.domainCache6 = make(map[string]netip.Addr) return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/fakeip/store.go
Bcore/windows/resources/sing-box-main/transport/fakeip/store.go
package fakeip import ( "context" "net/netip" "github.com/sagernet/sing-box/adapter" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/logger" "github.com/sagernet/sing/service" ) var _ adapter.FakeIPStore = (*Store)(nil) type Store struct { ctx context.Context logger logger.Logger inet4Range netip.Prefix inet6Range netip.Prefix storage adapter.FakeIPStorage inet4Current netip.Addr inet6Current netip.Addr } func NewStore(ctx context.Context, logger logger.Logger, inet4Range netip.Prefix, inet6Range netip.Prefix) *Store { return &Store{ ctx: ctx, logger: logger, inet4Range: inet4Range, inet6Range: inet6Range, } } func (s *Store) Start() error { var storage adapter.FakeIPStorage cacheFile := service.FromContext[adapter.CacheFile](s.ctx) if cacheFile != nil && cacheFile.StoreFakeIP() { storage = cacheFile } if storage == nil { storage = NewMemoryStorage() } metadata := storage.FakeIPMetadata() if metadata != nil && metadata.Inet4Range == s.inet4Range && metadata.Inet6Range == s.inet6Range { s.inet4Current = metadata.Inet4Current s.inet6Current = metadata.Inet6Current } else { if s.inet4Range.IsValid() { s.inet4Current = s.inet4Range.Addr().Next().Next() } if s.inet6Range.IsValid() { s.inet6Current = s.inet6Range.Addr().Next().Next() } _ = storage.FakeIPReset() } s.storage = storage return nil } func (s *Store) Contains(address netip.Addr) bool { return s.inet4Range.Contains(address) || s.inet6Range.Contains(address) } func (s *Store) Close() error { if s.storage == nil { return nil } return s.storage.FakeIPSaveMetadata(&adapter.FakeIPMetadata{ Inet4Range: s.inet4Range, Inet6Range: s.inet6Range, Inet4Current: s.inet4Current, Inet6Current: s.inet6Current, }) } func (s *Store) Create(domain string, isIPv6 bool) (netip.Addr, error) { if address, loaded := s.storage.FakeIPLoadDomain(domain, isIPv6); loaded { return address, nil } var address netip.Addr if !isIPv6 { if !s.inet4Current.IsValid() { return netip.Addr{}, E.New("missing IPv4 fakeip address range") } nextAddress := s.inet4Current.Next() if !s.inet4Range.Contains(nextAddress) { nextAddress = s.inet4Range.Addr().Next().Next() } s.inet4Current = nextAddress address = nextAddress } else { if !s.inet6Current.IsValid() { return netip.Addr{}, E.New("missing IPv6 fakeip address range") } nextAddress := s.inet6Current.Next() if !s.inet6Range.Contains(nextAddress) { nextAddress = s.inet6Range.Addr().Next().Next() } s.inet6Current = nextAddress address = nextAddress } s.storage.FakeIPStoreAsync(address, domain, s.logger) s.storage.FakeIPSaveMetadataAsync(&adapter.FakeIPMetadata{ Inet4Range: s.inet4Range, Inet6Range: s.inet6Range, Inet4Current: s.inet4Current, Inet6Current: s.inet6Current, }) return address, nil } func (s *Store) Lookup(address netip.Addr) (string, bool) { return s.storage.FakeIPLoad(address) } func (s *Store) Reset() error { return s.storage.FakeIPReset() }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/fakeip/server.go
Bcore/windows/resources/sing-box-main/transport/fakeip/server.go
package fakeip import ( "context" "net/netip" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-dns" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/logger" mDNS "github.com/miekg/dns" ) var ( _ dns.Transport = (*Transport)(nil) _ adapter.FakeIPTransport = (*Transport)(nil) ) func init() { dns.RegisterTransport([]string{"fakeip"}, func(options dns.TransportOptions) (dns.Transport, error) { return NewTransport(options) }) } type Transport struct { name string router adapter.Router store adapter.FakeIPStore logger logger.ContextLogger } func NewTransport(options dns.TransportOptions) (*Transport, error) { router := adapter.RouterFromContext(options.Context) if router == nil { return nil, E.New("missing router in context") } return &Transport{ name: options.Name, router: router, logger: options.Logger, }, nil } func (s *Transport) Name() string { return s.name } func (s *Transport) Start() error { s.store = s.router.FakeIPStore() if s.store == nil { return E.New("fakeip not enabled") } return nil } func (s *Transport) Reset() { } func (s *Transport) Close() error { return nil } func (s *Transport) Raw() bool { return false } func (s *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg, error) { return nil, os.ErrInvalid } func (s *Transport) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) { var addresses []netip.Addr if strategy != dns.DomainStrategyUseIPv6 { inet4Address, err := s.store.Create(domain, false) if err != nil { return nil, err } addresses = append(addresses, inet4Address) } if strategy != dns.DomainStrategyUseIPv4 { inet6Address, err := s.store.Create(domain, true) if err != nil { return nil, err } addresses = append(addresses, inet6Address) } return addresses, nil } func (s *Transport) Store() adapter.FakeIPStore { return s.store }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpclite/client.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpclite/client.go
package v2raygrpclite import ( "context" "io" "net" "net/http" "net/url" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/transport/v2rayhttp" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "golang.org/x/net/http2" ) var _ adapter.V2RayClientTransport = (*Client)(nil) var defaultClientHeader = http.Header{ "Content-Type": []string{"application/grpc"}, "User-Agent": []string{"grpc-go/1.48.0"}, "TE": []string{"trailers"}, } type Client struct { ctx context.Context dialer N.Dialer serverAddr M.Socksaddr transport *http2.Transport options option.V2RayGRPCOptions url *url.URL host string } func NewClient(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayGRPCOptions, tlsConfig tls.Config) adapter.V2RayClientTransport { var host string if tlsConfig != nil && tlsConfig.ServerName() != "" { host = M.ParseSocksaddrHostPort(tlsConfig.ServerName(), serverAddr.Port).String() } else { host = serverAddr.String() } client := &Client{ ctx: ctx, dialer: dialer, serverAddr: serverAddr, options: options, transport: &http2.Transport{ ReadIdleTimeout: time.Duration(options.IdleTimeout), PingTimeout: time.Duration(options.PingTimeout), DisableCompression: true, }, url: &url.URL{ Scheme: "https", Host: serverAddr.String(), Path: "/" + options.ServiceName + "/Tun", RawPath: "/" + url.PathEscape(options.ServiceName) + "/Tun", }, host: host, } if tlsConfig == nil { client.transport.DialTLSContext = func(ctx context.Context, network, addr string, cfg *tls.STDConfig) (net.Conn, error) { return dialer.DialContext(ctx, network, M.ParseSocksaddr(addr)) } } else { if len(tlsConfig.NextProtos()) == 0 { tlsConfig.SetNextProtos([]string{http2.NextProtoTLS}) } client.transport.DialTLSContext = func(ctx context.Context, network, addr string, cfg *tls.STDConfig) (net.Conn, error) { conn, err := dialer.DialContext(ctx, network, M.ParseSocksaddr(addr)) if err != nil { return nil, err } return tls.ClientHandshake(ctx, conn, tlsConfig) } } return client } func (c *Client) DialContext(ctx context.Context) (net.Conn, error) { pipeInReader, pipeInWriter := io.Pipe() request := &http.Request{ Method: http.MethodPost, Body: pipeInReader, URL: c.url, Header: defaultClientHeader, Host: c.host, } request = request.WithContext(ctx) conn := newLateGunConn(pipeInWriter) go func() { response, err := c.transport.RoundTrip(request) if err != nil { conn.setup(nil, err) } else if response.StatusCode != 200 { response.Body.Close() conn.setup(nil, E.New("v2ray-grpc: unexpected status: ", response.Status)) } else { conn.setup(response.Body, nil) } }() return conn, nil } func (c *Client) Close() error { v2rayhttp.ResetTransport(c.transport) return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpclite/conn.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpclite/conn.go
package v2raygrpclite import ( std_bufio "bufio" "encoding/binary" "io" "net" "net/http" "os" "time" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/baderror" "github.com/sagernet/sing/common/buf" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/varbin" ) // kanged from: https://github.com/Qv2ray/gun-lite var _ net.Conn = (*GunConn)(nil) type GunConn struct { reader *std_bufio.Reader writer io.Writer flusher http.Flusher create chan struct{} err error readRemaining int } func newGunConn(reader io.Reader, writer io.Writer, flusher http.Flusher) *GunConn { return &GunConn{ reader: std_bufio.NewReader(reader), writer: writer, flusher: flusher, } } func newLateGunConn(writer io.Writer) *GunConn { return &GunConn{ create: make(chan struct{}), writer: writer, } } func (c *GunConn) setup(reader io.Reader, err error) { if reader != nil { c.reader = std_bufio.NewReader(reader) } c.err = err close(c.create) } func (c *GunConn) Read(b []byte) (n int, err error) { n, err = c.read(b) return n, baderror.WrapH2(err) } func (c *GunConn) read(b []byte) (n int, err error) { if c.reader == nil { <-c.create if c.err != nil { return 0, c.err } } if c.readRemaining > 0 { if len(b) > c.readRemaining { b = b[:c.readRemaining] } n, err = c.reader.Read(b) c.readRemaining -= n return } _, err = c.reader.Discard(6) if err != nil { return } dataLen, err := binary.ReadUvarint(c.reader) if err != nil { return } readLen := int(dataLen) c.readRemaining = readLen if len(b) > readLen { b = b[:readLen] } n, err = c.reader.Read(b) c.readRemaining -= n return } func (c *GunConn) Write(b []byte) (n int, err error) { varLen := varbin.UvarintLen(uint64(len(b))) buffer := buf.NewSize(6 + varLen + len(b)) header := buffer.Extend(6 + varLen) header[0] = 0x00 binary.BigEndian.PutUint32(header[1:5], uint32(1+varLen+len(b))) header[5] = 0x0A binary.PutUvarint(header[6:], uint64(len(b))) common.Must1(buffer.Write(b)) _, err = c.writer.Write(buffer.Bytes()) if err != nil { return 0, baderror.WrapH2(err) } if c.flusher != nil { c.flusher.Flush() } return len(b), nil } func (c *GunConn) WriteBuffer(buffer *buf.Buffer) error { defer buffer.Release() dataLen := buffer.Len() varLen := varbin.UvarintLen(uint64(dataLen)) header := buffer.ExtendHeader(6 + varLen) header[0] = 0x00 binary.BigEndian.PutUint32(header[1:5], uint32(1+varLen+dataLen)) header[5] = 0x0A binary.PutUvarint(header[6:], uint64(dataLen)) err := common.Error(c.writer.Write(buffer.Bytes())) if err != nil { return baderror.WrapH2(err) } if c.flusher != nil { c.flusher.Flush() } return nil } func (c *GunConn) FrontHeadroom() int { return 6 + binary.MaxVarintLen64 } func (c *GunConn) Close() error { return common.Close(c.reader, c.writer) } func (c *GunConn) LocalAddr() net.Addr { return M.Socksaddr{} } func (c *GunConn) RemoteAddr() net.Addr { return M.Socksaddr{} } func (c *GunConn) SetDeadline(t time.Time) error { return os.ErrInvalid } func (c *GunConn) SetReadDeadline(t time.Time) error { return os.ErrInvalid } func (c *GunConn) SetWriteDeadline(t time.Time) error { return os.ErrInvalid } func (c *GunConn) NeedAdditionalReadDeadline() bool { return true }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2raygrpclite/server.go
Bcore/windows/resources/sing-box-main/transport/v2raygrpclite/server.go
package v2raygrpclite import ( "context" "net" "net/http" "os" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/transport/v2rayhttp" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" aTLS "github.com/sagernet/sing/common/tls" sHttp "github.com/sagernet/sing/protocol/http" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) var _ adapter.V2RayServerTransport = (*Server)(nil) type Server struct { tlsConfig tls.ServerConfig handler adapter.V2RayServerTransportHandler errorHandler E.Handler httpServer *http.Server h2Server *http2.Server h2cHandler http.Handler path string } func NewServer(ctx context.Context, options option.V2RayGRPCOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (*Server, error) { server := &Server{ tlsConfig: tlsConfig, handler: handler, path: "/" + options.ServiceName + "/Tun", h2Server: &http2.Server{ IdleTimeout: time.Duration(options.IdleTimeout), }, } server.httpServer = &http.Server{ Handler: server, BaseContext: func(net.Listener) context.Context { return ctx }, } server.h2cHandler = h2c.NewHandler(server, server.h2Server) return server, nil } func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) { if request.Method == "PRI" && len(request.Header) == 0 && request.URL.Path == "*" && request.Proto == "HTTP/2.0" { s.h2cHandler.ServeHTTP(writer, request) return } if request.URL.Path != s.path { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path)) return } if request.Method != http.MethodPost { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad method: ", request.Method)) return } if ct := request.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/grpc") { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad content type: ", ct)) return } writer.Header().Set("Content-Type", "application/grpc") writer.Header().Set("TE", "trailers") writer.WriteHeader(http.StatusOK) var metadata M.Metadata metadata.Source = sHttp.SourceAddress(request) conn := v2rayhttp.NewHTTP2Wrapper(newGunConn(request.Body, writer, writer.(http.Flusher))) s.handler.NewConnection(request.Context(), conn, metadata) conn.CloseWrapper() } func (s *Server) invalidRequest(writer http.ResponseWriter, request *http.Request, statusCode int, err error) { if statusCode > 0 { writer.WriteHeader(statusCode) } s.handler.NewError(request.Context(), E.Cause(err, "process connection from ", request.RemoteAddr)) } func (s *Server) Network() []string { return []string{N.NetworkTCP} } func (s *Server) Serve(listener net.Listener) error { if s.tlsConfig != nil { if !common.Contains(s.tlsConfig.NextProtos(), http2.NextProtoTLS) { s.tlsConfig.SetNextProtos(append([]string{"h2"}, s.tlsConfig.NextProtos()...)) } listener = aTLS.NewListener(listener, s.tlsConfig) } return s.httpServer.Serve(listener) } func (s *Server) ServePacket(listener net.PacketConn) error { return os.ErrInvalid } func (s *Server) Close() error { return common.Close(common.PtrOrNil(s.httpServer)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttp/client.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttp/client.go
package v2rayhttp import ( "context" "io" "math/rand" "net" "net/http" "net/url" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" sHTTP "github.com/sagernet/sing/protocol/http" "golang.org/x/net/http2" ) var _ adapter.V2RayClientTransport = (*Client)(nil) type Client struct { ctx context.Context dialer N.Dialer serverAddr M.Socksaddr transport http.RoundTripper http2 bool requestURL url.URL host []string method string headers http.Header } func NewClient(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayHTTPOptions, tlsConfig tls.Config) (adapter.V2RayClientTransport, error) { var transport http.RoundTripper if tlsConfig == nil { transport = &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return dialer.DialContext(ctx, network, M.ParseSocksaddr(addr)) }, } } else { if len(tlsConfig.NextProtos()) == 0 { tlsConfig.SetNextProtos([]string{http2.NextProtoTLS}) } transport = &http2.Transport{ ReadIdleTimeout: time.Duration(options.IdleTimeout), PingTimeout: time.Duration(options.PingTimeout), DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.STDConfig) (net.Conn, error) { conn, err := dialer.DialContext(ctx, network, M.ParseSocksaddr(addr)) if err != nil { return nil, err } return tls.ClientHandshake(ctx, conn, tlsConfig) }, } } if options.Method == "" { options.Method = http.MethodPut } var requestURL url.URL if tlsConfig == nil { requestURL.Scheme = "http" } else { requestURL.Scheme = "https" } requestURL.Host = serverAddr.String() requestURL.Path = options.Path err := sHTTP.URLSetPath(&requestURL, options.Path) if err != nil { return nil, E.Cause(err, "parse path") } if !strings.HasPrefix(requestURL.Path, "/") { requestURL.Path = "/" + requestURL.Path } return &Client{ ctx: ctx, dialer: dialer, serverAddr: serverAddr, requestURL: requestURL, host: options.Host, method: options.Method, headers: options.Headers.Build(), transport: transport, http2: tlsConfig != nil, }, nil } func (c *Client) DialContext(ctx context.Context) (net.Conn, error) { if !c.http2 { return c.dialHTTP(ctx) } else { return c.dialHTTP2(ctx) } } func (c *Client) dialHTTP(ctx context.Context) (net.Conn, error) { conn, err := c.dialer.DialContext(ctx, N.NetworkTCP, c.serverAddr) if err != nil { return nil, err } request := &http.Request{ Method: c.method, URL: &c.requestURL, Header: c.headers.Clone(), } switch hostLen := len(c.host); hostLen { case 0: request.Host = c.serverAddr.AddrString() case 1: request.Host = c.host[0] default: request.Host = c.host[rand.Intn(hostLen)] } return NewHTTP1Conn(conn, request), nil } func (c *Client) dialHTTP2(ctx context.Context) (net.Conn, error) { pipeInReader, pipeInWriter := io.Pipe() request := &http.Request{ Method: c.method, Body: pipeInReader, URL: &c.requestURL, Header: c.headers.Clone(), } request = request.WithContext(ctx) switch hostLen := len(c.host); hostLen { case 0: // https://github.com/v2fly/v2ray-core/blob/master/transport/internet/http/config.go#L13 request.Host = "www.example.com" case 1: request.Host = c.host[0] default: request.Host = c.host[rand.Intn(hostLen)] } conn := NewLateHTTPConn(pipeInWriter) go func() { response, err := c.transport.RoundTrip(request) if err != nil { conn.Setup(nil, err) } else if response.StatusCode != 200 { response.Body.Close() conn.Setup(nil, E.New("v2ray-http: unexpected status: ", response.Status)) } else { conn.Setup(response.Body, nil) } }() return conn, nil } func (c *Client) Close() error { c.transport = ResetTransport(c.transport) return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttp/force_close.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttp/force_close.go
package v2rayhttp import ( "net/http" "reflect" "sync" "unsafe" E "github.com/sagernet/sing/common/exceptions" "golang.org/x/net/http2" ) type clientConnPool struct { t *http2.Transport mu sync.Mutex conns map[string][]*http2.ClientConn // key is host:port } type efaceWords struct { typ unsafe.Pointer data unsafe.Pointer } func ResetTransport(rawTransport http.RoundTripper) http.RoundTripper { switch transport := rawTransport.(type) { case *http.Transport: transport.CloseIdleConnections() return transport.Clone() case *http2.Transport: connPool := transportConnPool(transport) p := (*clientConnPool)((*efaceWords)(unsafe.Pointer(&connPool)).data) p.mu.Lock() defer p.mu.Unlock() for _, vv := range p.conns { for _, cc := range vv { cc.Close() } } return transport default: panic(E.New("unknown transport type: ", reflect.TypeOf(transport))) } } //go:linkname transportConnPool golang.org/x/net/http2.(*Transport).connPool func transportConnPool(t *http2.Transport) http2.ClientConnPool
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttp/conn.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttp/conn.go
package v2rayhttp import ( std_bufio "bufio" "io" "net" "net/http" "os" "strings" "sync" "time" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/baderror" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/bufio" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type HTTPConn struct { net.Conn request *http.Request requestWritten bool responseRead bool responseCache *buf.Buffer } func NewHTTP1Conn(conn net.Conn, request *http.Request) *HTTPConn { return &HTTPConn{ Conn: conn, request: request, } } func (c *HTTPConn) Read(b []byte) (n int, err error) { if !c.responseRead { reader := std_bufio.NewReader(c.Conn) response, err := http.ReadResponse(reader, c.request) if err != nil { return 0, E.Cause(err, "read response") } if response.StatusCode != 200 { return 0, E.New("v2ray-http: unexpected status: ", response.Status) } if cacheLen := reader.Buffered(); cacheLen > 0 { c.responseCache = buf.NewSize(cacheLen) _, err = c.responseCache.ReadFullFrom(reader, cacheLen) if err != nil { c.responseCache.Release() return 0, E.Cause(err, "read cache") } } c.responseRead = true } if c.responseCache != nil { n, err = c.responseCache.Read(b) if err == io.EOF { c.responseCache.Release() c.responseCache = nil } if n > 0 { return n, nil } } return c.Conn.Read(b) } func (c *HTTPConn) Write(b []byte) (int, error) { if !c.requestWritten { err := c.writeRequest(b) if err != nil { return 0, E.Cause(err, "write request") } c.requestWritten = true return len(b), nil } return c.Conn.Write(b) } func (c *HTTPConn) writeRequest(payload []byte) error { writer := bufio.NewBufferedWriter(c.Conn, buf.New()) const CRLF = "\r\n" _, err := writer.Write([]byte(F.ToString(c.request.Method, " ", c.request.URL.RequestURI(), " HTTP/1.1", CRLF))) if err != nil { return err } if c.request.Header.Get("Host") == "" { c.request.Header.Set("Host", c.request.Host) } for key, value := range c.request.Header { _, err = writer.Write([]byte(F.ToString(key, ": ", strings.Join(value, ", "), CRLF))) if err != nil { return err } } _, err = writer.Write([]byte(CRLF)) if err != nil { return err } _, err = writer.Write(payload) if err != nil { return err } err = writer.Fallthrough() if err != nil { return err } return nil } func (c *HTTPConn) ReaderReplaceable() bool { return c.responseRead } func (c *HTTPConn) WriterReplaceable() bool { return c.requestWritten } func (c *HTTPConn) NeedHandshake() bool { return !c.requestWritten } func (c *HTTPConn) Upstream() any { return c.Conn } type HTTP2Conn struct { reader io.Reader writer io.Writer create chan struct{} err error } func NewHTTPConn(reader io.Reader, writer io.Writer) HTTP2Conn { return HTTP2Conn{ reader: reader, writer: writer, } } func NewLateHTTPConn(writer io.Writer) *HTTP2Conn { return &HTTP2Conn{ create: make(chan struct{}), writer: writer, } } func (c *HTTP2Conn) Setup(reader io.Reader, err error) { c.reader = reader c.err = err close(c.create) } func (c *HTTP2Conn) Read(b []byte) (n int, err error) { if c.reader == nil { <-c.create if c.err != nil { return 0, c.err } } n, err = c.reader.Read(b) return n, baderror.WrapH2(err) } func (c *HTTP2Conn) Write(b []byte) (n int, err error) { n, err = c.writer.Write(b) return n, baderror.WrapH2(err) } func (c *HTTP2Conn) Close() error { return common.Close(c.reader, c.writer) } func (c *HTTP2Conn) LocalAddr() net.Addr { return M.Socksaddr{} } func (c *HTTP2Conn) RemoteAddr() net.Addr { return M.Socksaddr{} } func (c *HTTP2Conn) SetDeadline(t time.Time) error { return os.ErrInvalid } func (c *HTTP2Conn) SetReadDeadline(t time.Time) error { return os.ErrInvalid } func (c *HTTP2Conn) SetWriteDeadline(t time.Time) error { return os.ErrInvalid } func (c *HTTP2Conn) NeedAdditionalReadDeadline() bool { return true } type ServerHTTPConn struct { HTTP2Conn Flusher http.Flusher } func (c *ServerHTTPConn) Write(b []byte) (n int, err error) { n, err = c.writer.Write(b) if err == nil { c.Flusher.Flush() } return } type HTTP2ConnWrapper struct { N.ExtendedConn access sync.Mutex closed bool } func NewHTTP2Wrapper(conn net.Conn) *HTTP2ConnWrapper { return &HTTP2ConnWrapper{ ExtendedConn: bufio.NewExtendedConn(conn), } } func (w *HTTP2ConnWrapper) Write(p []byte) (n int, err error) { w.access.Lock() defer w.access.Unlock() if w.closed { return 0, net.ErrClosed } return w.ExtendedConn.Write(p) } func (w *HTTP2ConnWrapper) WriteBuffer(buffer *buf.Buffer) error { w.access.Lock() defer w.access.Unlock() if w.closed { return net.ErrClosed } return w.ExtendedConn.WriteBuffer(buffer) } func (w *HTTP2ConnWrapper) CloseWrapper() { w.access.Lock() defer w.access.Unlock() w.closed = true } func (w *HTTP2ConnWrapper) Close() error { w.CloseWrapper() return w.ExtendedConn.Close() } func (w *HTTP2ConnWrapper) Upstream() any { return w.ExtendedConn }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttp/pool.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttp/pool.go
package v2rayhttp import "net/http" type ConnectionPool interface { CloseIdleConnections() } func CloseIdleConnections(transport http.RoundTripper) { if connectionPool, ok := transport.(ConnectionPool); ok { connectionPool.CloseIdleConnections() } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/transport/v2rayhttp/server.go
Bcore/windows/resources/sing-box-main/transport/v2rayhttp/server.go
package v2rayhttp import ( "context" "net" "net/http" "os" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/bufio" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" aTLS "github.com/sagernet/sing/common/tls" sHttp "github.com/sagernet/sing/protocol/http" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) var _ adapter.V2RayServerTransport = (*Server)(nil) type Server struct { ctx context.Context tlsConfig tls.ServerConfig handler adapter.V2RayServerTransportHandler httpServer *http.Server h2Server *http2.Server h2cHandler http.Handler host []string path string method string headers http.Header } func NewServer(ctx context.Context, options option.V2RayHTTPOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (*Server, error) { server := &Server{ ctx: ctx, tlsConfig: tlsConfig, handler: handler, h2Server: &http2.Server{ IdleTimeout: time.Duration(options.IdleTimeout), }, host: options.Host, path: options.Path, method: options.Method, headers: options.Headers.Build(), } if !strings.HasPrefix(server.path, "/") { server.path = "/" + server.path } server.httpServer = &http.Server{ Handler: server, ReadHeaderTimeout: C.TCPTimeout, MaxHeaderBytes: http.DefaultMaxHeaderBytes, BaseContext: func(net.Listener) context.Context { return ctx }, } server.h2cHandler = h2c.NewHandler(server, server.h2Server) return server, nil } func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request) { if request.Method == "PRI" && len(request.Header) == 0 && request.URL.Path == "*" && request.Proto == "HTTP/2.0" { s.h2cHandler.ServeHTTP(writer, request) return } host := request.Host if len(s.host) > 0 && !common.Contains(s.host, host) { s.invalidRequest(writer, request, http.StatusBadRequest, E.New("bad host: ", host)) return } if !strings.HasPrefix(request.URL.Path, s.path) { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad path: ", request.URL.Path)) return } if s.method != "" && request.Method != s.method { s.invalidRequest(writer, request, http.StatusNotFound, E.New("bad method: ", request.Method)) return } writer.Header().Set("Cache-Control", "no-store") for key, values := range s.headers { for _, value := range values { writer.Header().Set(key, value) } } var metadata M.Metadata metadata.Source = sHttp.SourceAddress(request) if h, ok := writer.(http.Hijacker); ok { var requestBody *buf.Buffer if contentLength := int(request.ContentLength); contentLength > 0 { requestBody = buf.NewSize(contentLength) _, err := requestBody.ReadFullFrom(request.Body, contentLength) if err != nil { s.invalidRequest(writer, request, 0, E.Cause(err, "read request")) return } } writer.WriteHeader(http.StatusOK) writer.(http.Flusher).Flush() conn, reader, err := h.Hijack() if err != nil { s.invalidRequest(writer, request, 0, E.Cause(err, "hijack conn")) return } if cacheLen := reader.Reader.Buffered(); cacheLen > 0 { cache := buf.NewSize(cacheLen) _, err = cache.ReadFullFrom(reader.Reader, cacheLen) if err != nil { conn.Close() s.invalidRequest(writer, request, 0, E.Cause(err, "read cache")) return } conn = bufio.NewCachedConn(conn, cache) } if requestBody != nil { conn = bufio.NewCachedConn(conn, requestBody) } s.handler.NewConnection(request.Context(), conn, metadata) } else { writer.WriteHeader(http.StatusOK) conn := NewHTTP2Wrapper(&ServerHTTPConn{ NewHTTPConn(request.Body, writer), writer.(http.Flusher), }) s.handler.NewConnection(request.Context(), conn, metadata) conn.CloseWrapper() } } func (s *Server) invalidRequest(writer http.ResponseWriter, request *http.Request, statusCode int, err error) { if statusCode > 0 { writer.WriteHeader(statusCode) } s.handler.NewError(request.Context(), E.Cause(err, "process connection from ", request.RemoteAddr)) } func (s *Server) Network() []string { return []string{N.NetworkTCP} } func (s *Server) Serve(listener net.Listener) error { if s.tlsConfig != nil { if len(s.tlsConfig.NextProtos()) == 0 { s.tlsConfig.SetNextProtos([]string{http2.NextProtoTLS, "http/1.1"}) } else if !common.Contains(s.tlsConfig.NextProtos(), http2.NextProtoTLS) { s.tlsConfig.SetNextProtos(append([]string{"h2"}, s.tlsConfig.NextProtos()...)) } listener = aTLS.NewListener(listener, s.tlsConfig) } return s.httpServer.Serve(listener) } func (s *Server) ServePacket(listener net.PacketConn) error { return os.ErrInvalid } func (s *Server) Close() error { return common.Close(common.PtrOrNil(s.httpServer)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/level.go
Bcore/windows/resources/sing-box-main/log/level.go
package log import ( E "github.com/sagernet/sing/common/exceptions" ) type Level = uint8 const ( LevelPanic Level = iota LevelFatal LevelError LevelWarn LevelInfo LevelDebug LevelTrace ) func FormatLevel(level Level) string { switch level { case LevelTrace: return "trace" case LevelDebug: return "debug" case LevelInfo: return "info" case LevelWarn: return "warn" case LevelError: return "error" case LevelFatal: return "fatal" case LevelPanic: return "panic" default: return "unknown" } } func ParseLevel(level string) (Level, error) { switch level { case "trace": return LevelTrace, nil case "debug": return LevelDebug, nil case "info": return LevelInfo, nil case "warn", "warning": return LevelWarn, nil case "error": return LevelError, nil case "fatal": return LevelFatal, nil case "panic": return LevelPanic, nil default: return LevelTrace, E.New("unknown log level: ", level) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/nop.go
Bcore/windows/resources/sing-box-main/log/nop.go
package log import ( "context" "os" "github.com/sagernet/sing/common/observable" ) var _ ObservableFactory = (*nopFactory)(nil) type nopFactory struct{} func NewNOPFactory() ObservableFactory { return (*nopFactory)(nil) } func (f *nopFactory) Start() error { return nil } func (f *nopFactory) Close() error { return nil } func (f *nopFactory) Level() Level { return LevelTrace } func (f *nopFactory) SetLevel(level Level) { } func (f *nopFactory) Logger() ContextLogger { return f } func (f *nopFactory) NewLogger(tag string) ContextLogger { return f } func (f *nopFactory) Trace(args ...any) { } func (f *nopFactory) Debug(args ...any) { } func (f *nopFactory) Info(args ...any) { } func (f *nopFactory) Warn(args ...any) { } func (f *nopFactory) Error(args ...any) { } func (f *nopFactory) Fatal(args ...any) { } func (f *nopFactory) Panic(args ...any) { } func (f *nopFactory) TraceContext(ctx context.Context, args ...any) { } func (f *nopFactory) DebugContext(ctx context.Context, args ...any) { } func (f *nopFactory) InfoContext(ctx context.Context, args ...any) { } func (f *nopFactory) WarnContext(ctx context.Context, args ...any) { } func (f *nopFactory) ErrorContext(ctx context.Context, args ...any) { } func (f *nopFactory) FatalContext(ctx context.Context, args ...any) { } func (f *nopFactory) PanicContext(ctx context.Context, args ...any) { } func (f *nopFactory) Subscribe() (subscription observable.Subscription[Entry], done <-chan struct{}, err error) { return nil, nil, os.ErrInvalid } func (f *nopFactory) UnSubscribe(subscription observable.Subscription[Entry]) { }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/id.go
Bcore/windows/resources/sing-box-main/log/id.go
package log import ( "context" "math/rand" "time" "github.com/sagernet/sing/common/random" ) func init() { random.InitializeSeed() } type idKey struct{} type ID struct { ID uint32 CreatedAt time.Time } func ContextWithNewID(ctx context.Context) context.Context { return context.WithValue(ctx, (*idKey)(nil), ID{ ID: rand.Uint32(), CreatedAt: time.Now(), }) } func IDFromContext(ctx context.Context) (ID, bool) { id, loaded := ctx.Value((*idKey)(nil)).(ID) return id, loaded }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/format.go
Bcore/windows/resources/sing-box-main/log/format.go
package log import ( "context" "strconv" "strings" "time" F "github.com/sagernet/sing/common/format" "github.com/logrusorgru/aurora" ) type Formatter struct { BaseTime time.Time DisableColors bool DisableTimestamp bool FullTimestamp bool TimestampFormat string DisableLineBreak bool } func (f Formatter) Format(ctx context.Context, level Level, tag string, message string, timestamp time.Time) string { levelString := strings.ToUpper(FormatLevel(level)) if !f.DisableColors { switch level { case LevelDebug, LevelTrace: levelString = aurora.White(levelString).String() case LevelInfo: levelString = aurora.Cyan(levelString).String() case LevelWarn: levelString = aurora.Yellow(levelString).String() case LevelError, LevelFatal, LevelPanic: levelString = aurora.Red(levelString).String() } } if tag != "" { message = tag + ": " + message } var id ID var hasId bool if ctx != nil { id, hasId = IDFromContext(ctx) } if hasId { activeDuration := FormatDuration(time.Since(id.CreatedAt)) if !f.DisableColors { var color aurora.Color color = aurora.Color(uint8(id.ID)) color %= 215 row := uint(color / 36) column := uint(color % 36) var r, g, b float32 r = float32(row * 51) g = float32(column / 6 * 51) b = float32((column % 6) * 51) luma := 0.2126*r + 0.7152*g + 0.0722*b if luma < 60 { row = 5 - row column = 35 - column color = aurora.Color(row*36 + column) } color += 16 color = color << 16 color |= 1 << 14 message = F.ToString("[", aurora.Colorize(id.ID, color).String(), " ", activeDuration, "] ", message) } else { message = F.ToString("[", id.ID, " ", activeDuration, "] ", message) } } switch { case f.DisableTimestamp: message = levelString + " " + message case f.FullTimestamp: message = timestamp.Format(f.TimestampFormat) + " " + levelString + " " + message default: message = levelString + "[" + xd(int(timestamp.Sub(f.BaseTime)/time.Second), 4) + "] " + message } if f.DisableLineBreak { if message[len(message)-1] == '\n' { message = message[:len(message)-1] } } else { if message[len(message)-1] != '\n' { message += "\n" } } return message } func (f Formatter) FormatWithSimple(ctx context.Context, level Level, tag string, message string, timestamp time.Time) (string, string) { levelString := strings.ToUpper(FormatLevel(level)) if !f.DisableColors { switch level { case LevelDebug, LevelTrace: levelString = aurora.White(levelString).String() case LevelInfo: levelString = aurora.Cyan(levelString).String() case LevelWarn: levelString = aurora.Yellow(levelString).String() case LevelError, LevelFatal, LevelPanic: levelString = aurora.Red(levelString).String() } } if tag != "" { message = tag + ": " + message } messageSimple := message var id ID var hasId bool if ctx != nil { id, hasId = IDFromContext(ctx) } if hasId { activeDuration := FormatDuration(time.Since(id.CreatedAt)) if !f.DisableColors { var color aurora.Color color = aurora.Color(uint8(id.ID)) color %= 215 row := uint(color / 36) column := uint(color % 36) var r, g, b float32 r = float32(row * 51) g = float32(column / 6 * 51) b = float32((column % 6) * 51) luma := 0.2126*r + 0.7152*g + 0.0722*b if luma < 60 { row = 5 - row column = 35 - column color = aurora.Color(row*36 + column) } color += 16 color = color << 16 color |= 1 << 14 message = F.ToString("[", aurora.Colorize(id.ID, color).String(), " ", activeDuration, "] ", message) } else { message = F.ToString("[", id.ID, " ", activeDuration, "] ", message) } messageSimple = F.ToString("[", id.ID, " ", activeDuration, "] ", messageSimple) } switch { case f.DisableTimestamp: message = levelString + " " + message case f.FullTimestamp: message = timestamp.Format(f.TimestampFormat) + " " + levelString + " " + message default: message = levelString + "[" + xd(int(timestamp.Sub(f.BaseTime)/time.Second), 4) + "] " + message } if message[len(message)-1] != '\n' { message += "\n" } return message, messageSimple } func xd(value int, x int) string { message := strconv.Itoa(value) for len(message) < x { message = "0" + message } return message } func FormatDuration(duration time.Duration) string { if duration < time.Second { return F.ToString(duration.Milliseconds(), "ms") } else if duration < time.Minute { return F.ToString(int64(duration.Seconds()), ".", int64(duration.Seconds()*100)%100, "s") } else { return F.ToString(int64(duration.Minutes()), "m", int64(duration.Seconds())%60, "s") } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/log.go
Bcore/windows/resources/sing-box-main/log/log.go
package log import ( "context" "io" "os" "time" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) type Options struct { Context context.Context Options option.LogOptions Observable bool DefaultWriter io.Writer BaseTime time.Time PlatformWriter PlatformWriter } func New(options Options) (Factory, error) { logOptions := options.Options if logOptions.Disabled { return NewNOPFactory(), nil } var logWriter io.Writer var logFilePath string switch logOptions.Output { case "": logWriter = options.DefaultWriter if logWriter == nil { logWriter = os.Stderr } case "stderr": logWriter = os.Stderr case "stdout": logWriter = os.Stdout default: logFilePath = logOptions.Output } logFormatter := Formatter{ BaseTime: options.BaseTime, DisableColors: logOptions.DisableColor || logFilePath != "", DisableTimestamp: !logOptions.Timestamp && logFilePath != "", FullTimestamp: logOptions.Timestamp, TimestampFormat: "-0700 2006-01-02 15:04:05", } factory := NewDefaultFactory( options.Context, logFormatter, logWriter, logFilePath, options.PlatformWriter, options.Observable, ) if logOptions.Level != "" { logLevel, err := ParseLevel(logOptions.Level) if err != nil { return nil, E.Cause(err, "parse log level") } factory.SetLevel(logLevel) } else { factory.SetLevel(LevelTrace) } return factory, nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/observable.go
Bcore/windows/resources/sing-box-main/log/observable.go
package log import ( "context" "io" "os" "time" "github.com/sagernet/sing/common" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/common/observable" "github.com/sagernet/sing/service/filemanager" ) var _ Factory = (*defaultFactory)(nil) type defaultFactory struct { ctx context.Context formatter Formatter platformFormatter Formatter writer io.Writer file *os.File filePath string platformWriter PlatformWriter needObservable bool level Level subscriber *observable.Subscriber[Entry] observer *observable.Observer[Entry] } func NewDefaultFactory( ctx context.Context, formatter Formatter, writer io.Writer, filePath string, platformWriter PlatformWriter, needObservable bool, ) ObservableFactory { factory := &defaultFactory{ ctx: ctx, formatter: formatter, platformFormatter: Formatter{ BaseTime: formatter.BaseTime, DisableLineBreak: true, }, writer: writer, filePath: filePath, platformWriter: platformWriter, needObservable: needObservable, level: LevelTrace, subscriber: observable.NewSubscriber[Entry](128), } if platformWriter != nil { factory.platformFormatter.DisableColors = platformWriter.DisableColors() } if needObservable { factory.observer = observable.NewObserver[Entry](factory.subscriber, 64) } return factory } func (f *defaultFactory) Start() error { if f.filePath != "" { logFile, err := filemanager.OpenFile(f.ctx, f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) if err != nil { return err } f.writer = logFile f.file = logFile } return nil } func (f *defaultFactory) Close() error { return common.Close( common.PtrOrNil(f.file), f.subscriber, ) } func (f *defaultFactory) Level() Level { return f.level } func (f *defaultFactory) SetLevel(level Level) { f.level = level } func (f *defaultFactory) Logger() ContextLogger { return f.NewLogger("") } func (f *defaultFactory) NewLogger(tag string) ContextLogger { return &observableLogger{f, tag} } func (f *defaultFactory) Subscribe() (subscription observable.Subscription[Entry], done <-chan struct{}, err error) { return f.observer.Subscribe() } func (f *defaultFactory) UnSubscribe(sub observable.Subscription[Entry]) { f.observer.UnSubscribe(sub) } var _ ContextLogger = (*observableLogger)(nil) type observableLogger struct { *defaultFactory tag string } func (l *observableLogger) Log(ctx context.Context, level Level, args []any) { level = OverrideLevelFromContext(level, ctx) if level > l.level { return } nowTime := time.Now() if l.needObservable { message, messageSimple := l.formatter.FormatWithSimple(ctx, level, l.tag, F.ToString(args...), nowTime) if level == LevelPanic { panic(message) } l.writer.Write([]byte(message)) if level == LevelFatal { os.Exit(1) } l.subscriber.Emit(Entry{level, messageSimple}) } else { message := l.formatter.Format(ctx, level, l.tag, F.ToString(args...), nowTime) if level == LevelPanic { panic(message) } l.writer.Write([]byte(message)) if level == LevelFatal { os.Exit(1) } } if l.platformWriter != nil { l.platformWriter.WriteMessage(level, l.platformFormatter.Format(ctx, level, l.tag, F.ToString(args...), nowTime)) } } func (l *observableLogger) Trace(args ...any) { l.TraceContext(context.Background(), args...) } func (l *observableLogger) Debug(args ...any) { l.DebugContext(context.Background(), args...) } func (l *observableLogger) Info(args ...any) { l.InfoContext(context.Background(), args...) } func (l *observableLogger) Warn(args ...any) { l.WarnContext(context.Background(), args...) } func (l *observableLogger) Error(args ...any) { l.ErrorContext(context.Background(), args...) } func (l *observableLogger) Fatal(args ...any) { l.FatalContext(context.Background(), args...) } func (l *observableLogger) Panic(args ...any) { l.PanicContext(context.Background(), args...) } func (l *observableLogger) TraceContext(ctx context.Context, args ...any) { l.Log(ctx, LevelTrace, args) } func (l *observableLogger) DebugContext(ctx context.Context, args ...any) { l.Log(ctx, LevelDebug, args) } func (l *observableLogger) InfoContext(ctx context.Context, args ...any) { l.Log(ctx, LevelInfo, args) } func (l *observableLogger) WarnContext(ctx context.Context, args ...any) { l.Log(ctx, LevelWarn, args) } func (l *observableLogger) ErrorContext(ctx context.Context, args ...any) { l.Log(ctx, LevelError, args) } func (l *observableLogger) FatalContext(ctx context.Context, args ...any) { l.Log(ctx, LevelFatal, args) } func (l *observableLogger) PanicContext(ctx context.Context, args ...any) { l.Log(ctx, LevelPanic, args) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/factory.go
Bcore/windows/resources/sing-box-main/log/factory.go
package log import ( "github.com/sagernet/sing/common/logger" "github.com/sagernet/sing/common/observable" ) type ( Logger logger.Logger ContextLogger logger.ContextLogger ) type Factory interface { Start() error Close() error Level() Level SetLevel(level Level) Logger() ContextLogger NewLogger(tag string) ContextLogger } type ObservableFactory interface { Factory observable.Observable[Entry] } type Entry struct { Level Level Message string }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/platform.go
Bcore/windows/resources/sing-box-main/log/platform.go
package log type PlatformWriter interface { DisableColors() bool WriteMessage(level Level, message string) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/export.go
Bcore/windows/resources/sing-box-main/log/export.go
package log import ( "context" "os" "time" ) var std ContextLogger func init() { std = NewDefaultFactory( context.Background(), Formatter{BaseTime: time.Now()}, os.Stderr, "", nil, false, ).Logger() } func StdLogger() ContextLogger { return std } func SetStdLogger(logger ContextLogger) { std = logger } func Trace(args ...any) { std.Trace(args...) } func Debug(args ...any) { std.Debug(args...) } func Info(args ...any) { std.Info(args...) } func Warn(args ...any) { std.Warn(args...) } func Error(args ...any) { std.Error(args...) } func Fatal(args ...any) { std.Fatal(args...) } func Panic(args ...any) { std.Panic(args...) } func TraceContext(ctx context.Context, args ...any) { std.TraceContext(ctx, args...) } func DebugContext(ctx context.Context, args ...any) { std.DebugContext(ctx, args...) } func InfoContext(ctx context.Context, args ...any) { std.InfoContext(ctx, args...) } func WarnContext(ctx context.Context, args ...any) { std.WarnContext(ctx, args...) } func ErrorContext(ctx context.Context, args ...any) { std.ErrorContext(ctx, args...) } func FatalContext(ctx context.Context, args ...any) { std.FatalContext(ctx, args...) } func PanicContext(ctx context.Context, args ...any) { std.PanicContext(ctx, args...) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/log/override.go
Bcore/windows/resources/sing-box-main/log/override.go
package log import ( "context" ) type overrideLevelKey struct{} func ContextWithOverrideLevel(ctx context.Context, level Level) context.Context { return context.WithValue(ctx, (*overrideLevelKey)(nil), level) } func OverrideLevelFromContext(origin Level, ctx context.Context) Level { level, loaded := ctx.Value((*overrideLevelKey)(nil)).(Level) if !loaded || origin > level { return origin } return level }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/prestart.go
Bcore/windows/resources/sing-box-main/adapter/prestart.go
package adapter type PreStarter interface { PreStart() error } type PostStarter interface { PostStart() error }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/experimental.go
Bcore/windows/resources/sing-box-main/adapter/experimental.go
package adapter import ( "bytes" "context" "encoding/binary" "net" "time" "github.com/sagernet/sing-box/common/urltest" "github.com/sagernet/sing-dns" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/varbin" ) type ClashServer interface { Service PreStarter Mode() string ModeList() []string HistoryStorage() *urltest.HistoryStorage RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule) (net.Conn, Tracker) RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext, matchedRule Rule) (N.PacketConn, Tracker) } type CacheFile interface { Service PreStarter StoreFakeIP() bool FakeIPStorage StoreRDRC() bool dns.RDRCStore LoadMode() string StoreMode(mode string) error LoadSelected(group string) string StoreSelected(group string, selected string) error LoadGroupExpand(group string) (isExpand bool, loaded bool) StoreGroupExpand(group string, expand bool) error LoadRuleSet(tag string) *SavedRuleSet SaveRuleSet(tag string, set *SavedRuleSet) error } type SavedRuleSet struct { Content []byte LastUpdated time.Time LastEtag string } func (s *SavedRuleSet) MarshalBinary() ([]byte, error) { var buffer bytes.Buffer err := binary.Write(&buffer, binary.BigEndian, uint8(1)) if err != nil { return nil, err } err = varbin.Write(&buffer, binary.BigEndian, s.Content) if err != nil { return nil, err } err = binary.Write(&buffer, binary.BigEndian, s.LastUpdated.Unix()) if err != nil { return nil, err } err = varbin.Write(&buffer, binary.BigEndian, s.LastEtag) if err != nil { return nil, err } return buffer.Bytes(), nil } func (s *SavedRuleSet) UnmarshalBinary(data []byte) error { reader := bytes.NewReader(data) var version uint8 err := binary.Read(reader, binary.BigEndian, &version) if err != nil { return err } err = varbin.Read(reader, binary.BigEndian, &s.Content) if err != nil { return err } var lastUpdated int64 err = binary.Read(reader, binary.BigEndian, &lastUpdated) if err != nil { return err } s.LastUpdated = time.Unix(lastUpdated, 0) err = varbin.Read(reader, binary.BigEndian, &s.LastEtag) if err != nil { return err } return nil } type Tracker interface { Leave() } type OutboundGroup interface { Outbound Now() string All() []string } type URLTestGroup interface { OutboundGroup URLTest(ctx context.Context) (map[string]uint16, error) } func OutboundTag(detour Outbound) string { if group, isGroup := detour.(OutboundGroup); isGroup { return group.Now() } return detour.Tag() } type V2RayServer interface { Service StatsService() V2RayStatsService } type V2RayStatsService interface { RoutedConnection(inbound string, outbound string, user string, conn net.Conn) net.Conn RoutedPacketConnection(inbound string, outbound string, user string, conn N.PacketConn) N.PacketConn }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/time.go
Bcore/windows/resources/sing-box-main/adapter/time.go
package adapter import "time" type TimeService interface { Service TimeFunc() func() time.Time }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/inbound.go
Bcore/windows/resources/sing-box-main/adapter/inbound.go
package adapter import ( "context" "net" "net/netip" "github.com/sagernet/sing-box/common/process" "github.com/sagernet/sing-box/option" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type Inbound interface { Service Type() string Tag() string } type InjectableInbound interface { Inbound Network() []string NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error } type InboundContext struct { Inbound string InboundType string IPVersion uint8 Network string Source M.Socksaddr Destination M.Socksaddr User string Outbound string // sniffer Protocol string Domain string Client string SniffContext any // cache InboundDetour string LastInbound string OriginDestination M.Socksaddr InboundOptions option.InboundOptions DestinationAddresses []netip.Addr SourceGeoIPCode string GeoIPCode string ProcessInfo *process.Info QueryType uint16 FakeIP bool // rule cache IPCIDRMatchSource bool IPCIDRAcceptEmpty bool SourceAddressMatch bool SourcePortMatch bool DestinationAddressMatch bool DestinationPortMatch bool DidMatch bool IgnoreDestinationIPCIDRMatch bool } func (c *InboundContext) ResetRuleCache() { c.IPCIDRMatchSource = false c.IPCIDRAcceptEmpty = false c.SourceAddressMatch = false c.SourcePortMatch = false c.DestinationAddressMatch = false c.DestinationPortMatch = false c.DidMatch = false } type inboundContextKey struct{} func WithContext(ctx context.Context, inboundContext *InboundContext) context.Context { return context.WithValue(ctx, (*inboundContextKey)(nil), inboundContext) } func ContextFrom(ctx context.Context) *InboundContext { metadata := ctx.Value((*inboundContextKey)(nil)) if metadata == nil { return nil } return metadata.(*InboundContext) } func AppendContext(ctx context.Context) (context.Context, *InboundContext) { metadata := ContextFrom(ctx) if metadata != nil { return ctx, metadata } metadata = new(InboundContext) return WithContext(ctx, metadata), metadata } func ExtendContext(ctx context.Context) (context.Context, *InboundContext) { var newMetadata InboundContext if metadata := ContextFrom(ctx); metadata != nil { newMetadata = *metadata } return WithContext(ctx, &newMetadata), &newMetadata } func OverrideContext(ctx context.Context) context.Context { if metadata := ContextFrom(ctx); metadata != nil { var newMetadata InboundContext newMetadata = *metadata return WithContext(ctx, &newMetadata) } return ctx }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/fakeip_metadata.go
Bcore/windows/resources/sing-box-main/adapter/fakeip_metadata.go
package adapter import ( "bytes" "encoding" "encoding/binary" "io" "net/netip" "github.com/sagernet/sing/common" ) type FakeIPMetadata struct { Inet4Range netip.Prefix Inet6Range netip.Prefix Inet4Current netip.Addr Inet6Current netip.Addr } func (m *FakeIPMetadata) MarshalBinary() (data []byte, err error) { var buffer bytes.Buffer for _, marshaler := range []encoding.BinaryMarshaler{m.Inet4Range, m.Inet6Range, m.Inet4Current, m.Inet6Current} { data, err = marshaler.MarshalBinary() if err != nil { return } common.Must(binary.Write(&buffer, binary.BigEndian, uint16(len(data)))) buffer.Write(data) } data = buffer.Bytes() return } func (m *FakeIPMetadata) UnmarshalBinary(data []byte) error { reader := bytes.NewReader(data) for _, unmarshaler := range []encoding.BinaryUnmarshaler{&m.Inet4Range, &m.Inet6Range, &m.Inet4Current, &m.Inet6Current} { var length uint16 common.Must(binary.Read(reader, binary.BigEndian, &length)) element := make([]byte, length) _, err := io.ReadFull(reader, element) if err != nil { return err } err = unmarshaler.UnmarshalBinary(element) if err != nil { return err } } return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/service.go
Bcore/windows/resources/sing-box-main/adapter/service.go
package adapter type Service interface { Start() error Close() error }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/upstream.go
Bcore/windows/resources/sing-box-main/adapter/upstream.go
package adapter import ( "context" "net" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type ( ConnectionHandlerFunc = func(ctx context.Context, conn net.Conn, metadata InboundContext) error PacketConnectionHandlerFunc = func(ctx context.Context, conn N.PacketConn, metadata InboundContext) error ) func NewUpstreamHandler( metadata InboundContext, connectionHandler ConnectionHandlerFunc, packetHandler PacketConnectionHandlerFunc, errorHandler E.Handler, ) UpstreamHandlerAdapter { return &myUpstreamHandlerWrapper{ metadata: metadata, connectionHandler: connectionHandler, packetHandler: packetHandler, errorHandler: errorHandler, } } var _ UpstreamHandlerAdapter = (*myUpstreamHandlerWrapper)(nil) type myUpstreamHandlerWrapper struct { metadata InboundContext connectionHandler ConnectionHandlerFunc packetHandler PacketConnectionHandlerFunc errorHandler E.Handler } func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { myMetadata := w.metadata if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.connectionHandler(ctx, conn, myMetadata) } func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { myMetadata := w.metadata if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.packetHandler(ctx, conn, myMetadata) } func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) { w.errorHandler.NewError(ctx, err) } func UpstreamMetadata(metadata InboundContext) M.Metadata { return M.Metadata{ Source: metadata.Source, Destination: metadata.Destination, } } type myUpstreamContextHandlerWrapper struct { connectionHandler ConnectionHandlerFunc packetHandler PacketConnectionHandlerFunc errorHandler E.Handler } func NewUpstreamContextHandler( connectionHandler ConnectionHandlerFunc, packetHandler PacketConnectionHandlerFunc, errorHandler E.Handler, ) UpstreamHandlerAdapter { return &myUpstreamContextHandlerWrapper{ connectionHandler: connectionHandler, packetHandler: packetHandler, errorHandler: errorHandler, } } func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { myMetadata := ContextFrom(ctx) if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.connectionHandler(ctx, conn, *myMetadata) } func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { myMetadata := ContextFrom(ctx) if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.packetHandler(ctx, conn, *myMetadata) } func (w *myUpstreamContextHandlerWrapper) NewError(ctx context.Context, err error) { w.errorHandler.NewError(ctx, err) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/router.go
Bcore/windows/resources/sing-box-main/adapter/router.go
package adapter import ( "context" "net/http" "net/netip" "github.com/sagernet/sing-box/common/geoip" "github.com/sagernet/sing-dns" "github.com/sagernet/sing-tun" "github.com/sagernet/sing/common/control" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/x/list" "github.com/sagernet/sing/service" mdns "github.com/miekg/dns" "go4.org/netipx" ) type Router interface { Service PreStarter PostStarter Cleanup() error Outbounds() []Outbound Outbound(tag string) (Outbound, bool) DefaultOutbound(network string) (Outbound, error) FakeIPStore() FakeIPStore ConnectionRouter GeoIPReader() *geoip.Reader LoadGeosite(code string) (Rule, error) RuleSet(tag string) (RuleSet, bool) NeedWIFIState() bool Exchange(ctx context.Context, message *mdns.Msg) (*mdns.Msg, error) Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error) LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error) ClearDNSCache() InterfaceFinder() control.InterfaceFinder UpdateInterfaces() error DefaultInterface() string AutoDetectInterface() bool AutoDetectInterfaceFunc() control.Func DefaultMark() uint32 RegisterAutoRedirectOutputMark(mark uint32) error AutoRedirectOutputMark() uint32 NetworkMonitor() tun.NetworkUpdateMonitor InterfaceMonitor() tun.DefaultInterfaceMonitor PackageManager() tun.PackageManager WIFIState() WIFIState Rules() []Rule ClashServer() ClashServer SetClashServer(server ClashServer) V2RayServer() V2RayServer SetV2RayServer(server V2RayServer) ResetNetwork() error } func ContextWithRouter(ctx context.Context, router Router) context.Context { return service.ContextWith(ctx, router) } func RouterFromContext(ctx context.Context) Router { return service.FromContext[Router](ctx) } type HeadlessRule interface { Match(metadata *InboundContext) bool String() string } type Rule interface { HeadlessRule Service Type() string UpdateGeosite() error Outbound() string } type DNSRule interface { Rule DisableCache() bool RewriteTTL() *uint32 ClientSubnet() *netip.Prefix WithAddressLimit() bool MatchAddressLimit(metadata *InboundContext) bool } type RuleSet interface { Name() string StartContext(ctx context.Context, startContext RuleSetStartContext) error PostStart() error Metadata() RuleSetMetadata ExtractIPSet() []*netipx.IPSet IncRef() DecRef() Cleanup() RegisterCallback(callback RuleSetUpdateCallback) *list.Element[RuleSetUpdateCallback] UnregisterCallback(element *list.Element[RuleSetUpdateCallback]) Close() error HeadlessRule } type RuleSetUpdateCallback func(it RuleSet) type RuleSetMetadata struct { ContainsProcessRule bool ContainsWIFIRule bool ContainsIPCIDRRule bool } type RuleSetStartContext interface { HTTPClient(detour string, dialer N.Dialer) *http.Client Close() } type InterfaceUpdateListener interface { InterfaceUpdated() } type WIFIState struct { SSID string BSSID string }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/v2ray.go
Bcore/windows/resources/sing-box-main/adapter/v2ray.go
package adapter import ( "context" "net" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" ) type V2RayServerTransport interface { Network() []string Serve(listener net.Listener) error ServePacket(listener net.PacketConn) error Close() error } type V2RayServerTransportHandler interface { N.TCPConnectionHandler E.Handler } type V2RayClientTransport interface { DialContext(ctx context.Context) (net.Conn, error) Close() error }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/fakeip.go
Bcore/windows/resources/sing-box-main/adapter/fakeip.go
package adapter import ( "net/netip" "github.com/sagernet/sing-dns" "github.com/sagernet/sing/common/logger" ) type FakeIPStore interface { Service Contains(address netip.Addr) bool Create(domain string, isIPv6 bool) (netip.Addr, error) Lookup(address netip.Addr) (string, bool) Reset() error } type FakeIPStorage interface { FakeIPMetadata() *FakeIPMetadata FakeIPSaveMetadata(metadata *FakeIPMetadata) error FakeIPSaveMetadataAsync(metadata *FakeIPMetadata) FakeIPStore(address netip.Addr, domain string) error FakeIPStoreAsync(address netip.Addr, domain string, logger logger.Logger) FakeIPLoad(address netip.Addr) (string, bool) FakeIPLoadDomain(domain string, isIPv6 bool) (netip.Addr, bool) FakeIPReset() error } type FakeIPTransport interface { dns.Transport Store() FakeIPStore }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/outbound.go
Bcore/windows/resources/sing-box-main/adapter/outbound.go
package adapter import ( "context" "net" N "github.com/sagernet/sing/common/network" ) // Note: for proxy protocols, outbound creates early connections by default. type Outbound interface { Type() string Tag() string Network() []string Dependencies() []string N.Dialer NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/handler.go
Bcore/windows/resources/sing-box-main/adapter/handler.go
package adapter import ( "context" "net" "github.com/sagernet/sing/common/buf" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" ) type ConnectionHandler interface { NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error } type PacketHandler interface { NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata InboundContext) error } type OOBPacketHandler interface { NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, oob []byte, metadata InboundContext) error } type PacketConnectionHandler interface { NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error } type UpstreamHandlerAdapter interface { N.TCPConnectionHandler N.UDPConnectionHandler E.Handler }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/adapter/conn_router.go
Bcore/windows/resources/sing-box-main/adapter/conn_router.go
package adapter import ( "context" "net" "github.com/sagernet/sing/common/logger" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type ConnectionRouter interface { RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error } func NewRouteHandler( metadata InboundContext, router ConnectionRouter, logger logger.ContextLogger, ) UpstreamHandlerAdapter { return &routeHandlerWrapper{ metadata: metadata, router: router, logger: logger, } } func NewRouteContextHandler( router ConnectionRouter, logger logger.ContextLogger, ) UpstreamHandlerAdapter { return &routeContextHandlerWrapper{ router: router, logger: logger, } } var _ UpstreamHandlerAdapter = (*routeHandlerWrapper)(nil) type routeHandlerWrapper struct { metadata InboundContext router ConnectionRouter logger logger.ContextLogger } func (w *routeHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { myMetadata := w.metadata if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.router.RouteConnection(ctx, conn, myMetadata) } func (w *routeHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { myMetadata := w.metadata if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.router.RoutePacketConnection(ctx, conn, myMetadata) } func (w *routeHandlerWrapper) NewError(ctx context.Context, err error) { w.logger.ErrorContext(ctx, err) } var _ UpstreamHandlerAdapter = (*routeContextHandlerWrapper)(nil) type routeContextHandlerWrapper struct { router ConnectionRouter logger logger.ContextLogger } func (w *routeContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { myMetadata := ContextFrom(ctx) if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.router.RouteConnection(ctx, conn, *myMetadata) } func (w *routeContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error { myMetadata := ContextFrom(ctx) if metadata.Source.IsValid() { myMetadata.Source = metadata.Source } if metadata.Destination.IsValid() { myMetadata.Destination = metadata.Destination } return w.router.RoutePacketConnection(ctx, conn, *myMetadata) } func (w *routeContextHandlerWrapper) NewError(ctx context.Context, err error) { w.logger.ErrorContext(ctx, err) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default_tcp_nongo1.21.go
Bcore/windows/resources/sing-box-main/inbound/default_tcp_nongo1.21.go
//go:build !go1.21 package inbound import "net" const go121Available = false func setMultiPathTCP(listenConfig *net.ListenConfig) { }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/hysteria.go
Bcore/windows/resources/sing-box-main/inbound/hysteria.go
//go:build with_quic package inbound import ( "context" "net" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/humanize" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-quic/hysteria" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" ) var _ adapter.Inbound = (*Hysteria)(nil) type Hysteria struct { myInboundAdapter tlsConfig tls.ServerConfig service *hysteria.Service[int] userNameList []string } func NewHysteria(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HysteriaInboundOptions) (*Hysteria, error) { options.UDPFragmentDefault = true if options.TLS == nil || !options.TLS.Enabled { return nil, C.ErrTLSRequired } tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } inbound := &Hysteria{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeHysteria, network: []string{N.NetworkUDP}, ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, tlsConfig: tlsConfig, } var sendBps, receiveBps uint64 if len(options.Up) > 0 { sendBps, err = humanize.ParseBytes(options.Up) if err != nil { return nil, E.Cause(err, "invalid up speed format: ", options.Up) } } else { sendBps = uint64(options.UpMbps) * hysteria.MbpsToBps } if len(options.Down) > 0 { receiveBps, err = humanize.ParseBytes(options.Down) if receiveBps == 0 { return nil, E.New("invalid down speed format: ", options.Down) } } else { receiveBps = uint64(options.DownMbps) * hysteria.MbpsToBps } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } service, err := hysteria.NewService[int](hysteria.ServiceOptions{ Context: ctx, Logger: logger, SendBPS: sendBps, ReceiveBPS: receiveBps, XPlusPassword: options.Obfs, TLSConfig: tlsConfig, UDPTimeout: udpTimeout, Handler: adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, nil), // Legacy options ConnReceiveWindow: options.ReceiveWindowConn, StreamReceiveWindow: options.ReceiveWindowClient, MaxIncomingStreams: int64(options.MaxConnClient), DisableMTUDiscovery: options.DisableMTUDiscovery, }) if err != nil { return nil, err } userList := make([]int, 0, len(options.Users)) userNameList := make([]string, 0, len(options.Users)) userPasswordList := make([]string, 0, len(options.Users)) for index, user := range options.Users { userList = append(userList, index) userNameList = append(userNameList, user.Name) var password string if user.AuthString != "" { password = user.AuthString } else { password = string(user.Auth) } userPasswordList = append(userPasswordList, password) } service.UpdateUsers(userList, userPasswordList) inbound.service = service inbound.userNameList = userNameList return inbound, nil } func (h *Hysteria) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) metadata = h.createMetadata(conn, metadata) h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) } return h.router.RouteConnection(ctx, conn, metadata) } func (h *Hysteria) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) metadata = h.createPacketMetadata(conn, metadata) h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) } return h.router.RoutePacketConnection(ctx, conn, metadata) } func (h *Hysteria) Start() error { if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return err } } packetConn, err := h.myInboundAdapter.ListenUDP() if err != nil { return err } return h.service.Start(packetConn) } func (h *Hysteria) Close() error { return common.Close( &h.myInboundAdapter, h.tlsConfig, common.PtrOrNil(h.service), ) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/socks.go
Bcore/windows/resources/sing-box-main/inbound/socks.go
package inbound import ( "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/auth" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/protocol/socks" ) var ( _ adapter.Inbound = (*Socks)(nil) _ adapter.InjectableInbound = (*Socks)(nil) ) type Socks struct { myInboundAdapter authenticator *auth.Authenticator } func NewSocks(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SocksInboundOptions) *Socks { inbound := &Socks{ myInboundAdapter{ protocol: C.TypeSOCKS, network: []string{N.NetworkTCP}, ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, auth.NewAuthenticator(options.Users), } inbound.connHandler = inbound return inbound } func (h *Socks) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { return socks.HandleConnection(ctx, conn, h.authenticator, h.upstreamUserHandler(metadata), adapter.UpstreamMetadata(metadata)) } func (h *Socks) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default_tcp_go1.20.go
Bcore/windows/resources/sing-box-main/inbound/default_tcp_go1.20.go
//go:build go1.20 package inbound import ( "context" "net" "github.com/metacubex/tfo-go" ) const go120Available = true func listenTFO(listenConfig net.ListenConfig, ctx context.Context, network string, address string) (net.Listener, error) { var tfoConfig tfo.ListenConfig tfoConfig.ListenConfig = listenConfig return tfoConfig.Listen(ctx, network, address) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/tproxy.go
Bcore/windows/resources/sing-box-main/inbound/tproxy.go
package inbound import ( "context" "net" "net/netip" "syscall" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/redir" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/control" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/udpnat" ) type TProxy struct { myInboundAdapter udpNat *udpnat.Service[netip.AddrPort] } func NewTProxy(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TProxyInboundOptions) *TProxy { tproxy := &TProxy{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeTProxy, network: options.Network.Build(), ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } tproxy.connHandler = tproxy tproxy.oobPacketHandler = tproxy tproxy.udpNat = udpnat.New[netip.AddrPort](int64(udpTimeout.Seconds()), tproxy.upstreamContextHandler()) tproxy.packetUpstream = tproxy.udpNat return tproxy } func (t *TProxy) Start() error { err := t.myInboundAdapter.Start() if err != nil { return err } if t.tcpListener != nil { err = control.Conn(common.MustCast[syscall.Conn](t.tcpListener), func(fd uintptr) error { return redir.TProxy(fd, M.SocksaddrFromNet(t.tcpListener.Addr()).Addr.Is6()) }) if err != nil { return E.Cause(err, "configure tproxy TCP listener") } } if t.udpConn != nil { err = control.Conn(t.udpConn, func(fd uintptr) error { return redir.TProxy(fd, M.SocksaddrFromNet(t.udpConn.LocalAddr()).Addr.Is6()) }) if err != nil { return E.Cause(err, "configure tproxy UDP listener") } } return nil } func (t *TProxy) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { metadata.Destination = M.SocksaddrFromNet(conn.LocalAddr()).Unwrap() return t.newConnection(ctx, conn, metadata) } func (t *TProxy) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, oob []byte, metadata adapter.InboundContext) error { destination, err := redir.GetOriginalDestinationFromOOB(oob) if err != nil { return E.Cause(err, "get tproxy destination") } metadata.Destination = M.SocksaddrFromNetIP(destination).Unwrap() t.udpNat.NewContextPacket(ctx, metadata.Source.AddrPort(), buffer, adapter.UpstreamMetadata(metadata), func(natConn N.PacketConn) (context.Context, N.PacketWriter) { return adapter.WithContext(log.ContextWithNewID(ctx), &metadata), &tproxyPacketWriter{ctx: ctx, source: natConn, destination: metadata.Destination} }) return nil } type tproxyPacketWriter struct { ctx context.Context source N.PacketConn destination M.Socksaddr conn *net.UDPConn } func (w *tproxyPacketWriter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error { defer buffer.Release() conn := w.conn if w.destination == destination && conn != nil { _, err := conn.WriteToUDPAddrPort(buffer.Bytes(), M.AddrPortFromNet(w.source.LocalAddr())) if err != nil { w.conn = nil } return err } var listener net.ListenConfig listener.Control = control.Append(listener.Control, control.ReuseAddr()) listener.Control = control.Append(listener.Control, redir.TProxyWriteBack()) packetConn, err := listener.ListenPacket(w.ctx, "udp", destination.String()) if err != nil { return err } udpConn := packetConn.(*net.UDPConn) if w.destination == destination { w.conn = udpConn } else { defer udpConn.Close() } return common.Error(udpConn.WriteToUDPAddrPort(buffer.Bytes(), M.AddrPortFromNet(w.source.LocalAddr()))) } func (w *tproxyPacketWriter) Close() error { return common.Close(common.PtrOrNil(w.conn)) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default.go
Bcore/windows/resources/sing-box-main/inbound/default.go
package inbound import ( "context" "net" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/settings" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/atomic" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) var _ adapter.Inbound = (*myInboundAdapter)(nil) type myInboundAdapter struct { protocol string network []string ctx context.Context router adapter.ConnectionRouter logger log.ContextLogger tag string listenOptions option.ListenOptions connHandler adapter.ConnectionHandler packetHandler adapter.PacketHandler oobPacketHandler adapter.OOBPacketHandler packetUpstream any // http mixed setSystemProxy bool systemProxy settings.SystemProxy // internal tcpListener net.Listener udpConn *net.UDPConn udpAddr M.Socksaddr packetOutboundClosed chan struct{} packetOutbound chan *myInboundPacket inShutdown atomic.Bool } func (a *myInboundAdapter) Type() string { return a.protocol } func (a *myInboundAdapter) Tag() string { return a.tag } func (a *myInboundAdapter) Network() []string { return a.network } func (a *myInboundAdapter) Start() error { var err error if common.Contains(a.network, N.NetworkTCP) { _, err = a.ListenTCP() if err != nil { return err } go a.loopTCPIn() } if common.Contains(a.network, N.NetworkUDP) { _, err = a.ListenUDP() if err != nil { return err } a.packetOutboundClosed = make(chan struct{}) a.packetOutbound = make(chan *myInboundPacket) if a.oobPacketHandler != nil { if _, threadUnsafeHandler := common.Cast[N.ThreadUnsafeWriter](a.packetUpstream); !threadUnsafeHandler { go a.loopUDPOOBIn() } else { go a.loopUDPOOBInThreadSafe() } } else { if _, threadUnsafeHandler := common.Cast[N.ThreadUnsafeWriter](a.packetUpstream); !threadUnsafeHandler { go a.loopUDPIn() } else { go a.loopUDPInThreadSafe() } go a.loopUDPOut() } } if a.setSystemProxy { listenPort := M.SocksaddrFromNet(a.tcpListener.Addr()).Port var listenAddrString string listenAddr := a.listenOptions.Listen.Build() if listenAddr.IsUnspecified() { listenAddrString = "127.0.0.1" } else { listenAddrString = listenAddr.String() } var systemProxy settings.SystemProxy systemProxy, err = settings.NewSystemProxy(a.ctx, M.ParseSocksaddrHostPort(listenAddrString, listenPort), a.protocol == C.TypeMixed) if err != nil { return E.Cause(err, "initialize system proxy") } err = systemProxy.Enable() if err != nil { return E.Cause(err, "set system proxy") } a.systemProxy = systemProxy } return nil } func (a *myInboundAdapter) Close() error { a.inShutdown.Store(true) var err error if a.systemProxy != nil && a.systemProxy.IsEnabled() { err = a.systemProxy.Disable() } return E.Errors(err, common.Close( a.tcpListener, common.PtrOrNil(a.udpConn), )) } func (a *myInboundAdapter) upstreamHandler(metadata adapter.InboundContext) adapter.UpstreamHandlerAdapter { return adapter.NewUpstreamHandler(metadata, a.newConnection, a.streamPacketConnection, a) } func (a *myInboundAdapter) upstreamContextHandler() adapter.UpstreamHandlerAdapter { return adapter.NewUpstreamContextHandler(a.newConnection, a.newPacketConnection, a) } func (a *myInboundAdapter) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { a.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) return a.router.RouteConnection(ctx, conn, metadata) } func (a *myInboundAdapter) streamPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) return a.router.RoutePacketConnection(ctx, conn, metadata) } func (a *myInboundAdapter) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) a.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) return a.router.RoutePacketConnection(ctx, conn, metadata) } func (a *myInboundAdapter) createMetadata(conn net.Conn, metadata adapter.InboundContext) adapter.InboundContext { metadata.Inbound = a.tag metadata.InboundType = a.protocol metadata.InboundDetour = a.listenOptions.Detour metadata.InboundOptions = a.listenOptions.InboundOptions if !metadata.Source.IsValid() { metadata.Source = M.SocksaddrFromNet(conn.RemoteAddr()).Unwrap() } if !metadata.Destination.IsValid() { metadata.Destination = M.SocksaddrFromNet(conn.LocalAddr()).Unwrap() } if tcpConn, isTCP := common.Cast[*net.TCPConn](conn); isTCP { metadata.OriginDestination = M.SocksaddrFromNet(tcpConn.LocalAddr()).Unwrap() } return metadata } func (a *myInboundAdapter) createPacketMetadata(conn N.PacketConn, metadata adapter.InboundContext) adapter.InboundContext { metadata.Inbound = a.tag metadata.InboundType = a.protocol metadata.InboundDetour = a.listenOptions.Detour metadata.InboundOptions = a.listenOptions.InboundOptions if !metadata.Destination.IsValid() { metadata.Destination = M.SocksaddrFromNet(conn.LocalAddr()).Unwrap() } return metadata } func (a *myInboundAdapter) newError(err error) { a.logger.Error(err) } func (a *myInboundAdapter) NewError(ctx context.Context, err error) { NewError(a.logger, ctx, err) } func NewError(logger log.ContextLogger, ctx context.Context, err error) { common.Close(err) if E.IsClosedOrCanceled(err) { logger.DebugContext(ctx, "connection closed: ", err) return } logger.ErrorContext(ctx, err) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/naive_quic.go
Bcore/windows/resources/sing-box-main/inbound/naive_quic.go
//go:build with_quic package inbound import ( "github.com/sagernet/quic-go" "github.com/sagernet/quic-go/http3" "github.com/sagernet/sing-quic" E "github.com/sagernet/sing/common/exceptions" ) func (n *Naive) configureHTTP3Listener() error { err := qtls.ConfigureHTTP3(n.tlsConfig) if err != nil { return err } udpConn, err := n.ListenUDP() if err != nil { return err } quicListener, err := qtls.ListenEarly(udpConn, n.tlsConfig, &quic.Config{ MaxIncomingStreams: 1 << 60, Allow0RTT: true, }) if err != nil { udpConn.Close() return err } h3Server := &http3.Server{ Port: int(n.listenOptions.ListenPort), Handler: n, } go func() { sErr := h3Server.ServeListener(quicListener) udpConn.Close() if sErr != nil && !E.IsClosedOrCanceled(sErr) { n.logger.Error("http3 server serve error: ", sErr) } }() n.h3Server = h3Server return nil }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/vmess.go
Bcore/windows/resources/sing-box-main/inbound/vmess.go
package inbound import ( "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/mux" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/transport/v2ray" "github.com/sagernet/sing-vmess" "github.com/sagernet/sing-vmess/packetaddr" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/ntp" ) var ( _ adapter.Inbound = (*VMess)(nil) _ adapter.InjectableInbound = (*VMess)(nil) ) type VMess struct { myInboundAdapter ctx context.Context service *vmess.Service[int] users []option.VMessUser tlsConfig tls.ServerConfig transport adapter.V2RayServerTransport } func NewVMess(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.VMessInboundOptions) (*VMess, error) { inbound := &VMess{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeVMess, network: []string{N.NetworkTCP}, ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, ctx: ctx, users: options.Users, } var err error inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex)) if err != nil { return nil, err } var serviceOptions []vmess.ServiceOption if timeFunc := ntp.TimeFuncFromContext(ctx); timeFunc != nil { serviceOptions = append(serviceOptions, vmess.ServiceWithTimeFunc(timeFunc)) } if options.Transport != nil && options.Transport.Type != "" { serviceOptions = append(serviceOptions, vmess.ServiceWithDisableHeaderProtection()) } service := vmess.NewService[int](adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound), serviceOptions...) inbound.service = service err = service.UpdateUsers(common.MapIndexed(options.Users, func(index int, it option.VMessUser) int { return index }), common.Map(options.Users, func(it option.VMessUser) string { return it.UUID }), common.Map(options.Users, func(it option.VMessUser) int { return it.AlterId })) if err != nil { return nil, err } if options.TLS != nil { inbound.tlsConfig, err = tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } } if options.Transport != nil { inbound.transport, err = v2ray.NewServerTransport(ctx, common.PtrValueOrDefault(options.Transport), inbound.tlsConfig, (*vmessTransportHandler)(inbound)) if err != nil { return nil, E.Cause(err, "create server transport: ", options.Transport.Type) } } inbound.connHandler = inbound return inbound, nil } func (h *VMess) Start() error { err := h.service.Start() if err != nil { return err } if h.tlsConfig != nil { err = h.tlsConfig.Start() if err != nil { return err } } if h.transport == nil { return h.myInboundAdapter.Start() } if common.Contains(h.transport.Network(), N.NetworkTCP) { tcpListener, err := h.myInboundAdapter.ListenTCP() if err != nil { return err } go func() { sErr := h.transport.Serve(tcpListener) if sErr != nil && !E.IsClosed(sErr) { h.logger.Error("transport serve error: ", sErr) } }() } if common.Contains(h.transport.Network(), N.NetworkUDP) { udpConn, err := h.myInboundAdapter.ListenUDP() if err != nil { return err } go func() { sErr := h.transport.ServePacket(udpConn) if sErr != nil && !E.IsClosed(sErr) { h.logger.Error("transport serve error: ", sErr) } }() } return nil } func (h *VMess) Close() error { return common.Close( h.service, &h.myInboundAdapter, h.tlsConfig, h.transport, ) } func (h *VMess) newTransportConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { h.injectTCP(conn, metadata) return nil } func (h *VMess) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { var err error if h.tlsConfig != nil && h.transport == nil { conn, err = tls.ServerHandshake(ctx, conn, h.tlsConfig) if err != nil { return err } } return h.service.NewConnection(adapter.WithContext(log.ContextWithNewID(ctx), &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *VMess) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid } func (h *VMess) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination) return h.router.RouteConnection(ctx, conn, metadata) } func (h *VMess) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } if metadata.Destination.Fqdn == packetaddr.SeqPacketMagicAddress { metadata.Destination = M.Socksaddr{} conn = packetaddr.NewConn(conn.(vmess.PacketConn), metadata.Destination) h.logger.InfoContext(ctx, "[", user, "] inbound packet addr connection") } else { h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination) } return h.router.RoutePacketConnection(ctx, conn, metadata) } var _ adapter.V2RayServerTransportHandler = (*vmessTransportHandler)(nil) type vmessTransportHandler VMess func (t *vmessTransportHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { return (*VMess)(t).newTransportConnection(ctx, conn, adapter.InboundContext{ Source: metadata.Source, Destination: metadata.Destination, }) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default_tcp_go1.21.go
Bcore/windows/resources/sing-box-main/inbound/default_tcp_go1.21.go
//go:build go1.21 package inbound import "net" const go121Available = true func setMultiPathTCP(listenConfig *net.ListenConfig) { listenConfig.SetMultipathTCP(true) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/shadowsocks.go
Bcore/windows/resources/sing-box-main/inbound/shadowsocks.go
package inbound import ( "context" "net" "os" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/mux" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks" "github.com/sagernet/sing-shadowsocks/shadowaead" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/ntp" ) func NewShadowsocks(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (adapter.Inbound, error) { if len(options.Users) > 0 && len(options.Destinations) > 0 { return nil, E.New("users and destinations options must not be combined") } if len(options.Users) > 0 { return newShadowsocksMulti(ctx, router, logger, tag, options) } else if len(options.Destinations) > 0 { return newShadowsocksRelay(ctx, router, logger, tag, options) } else { return newShadowsocks(ctx, router, logger, tag, options) } } var ( _ adapter.Inbound = (*Shadowsocks)(nil) _ adapter.InjectableInbound = (*Shadowsocks)(nil) ) type Shadowsocks struct { myInboundAdapter service shadowsocks.Service } func newShadowsocks(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (*Shadowsocks, error) { inbound := &Shadowsocks{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeShadowsocks, network: options.Network.Build(), ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, } inbound.connHandler = inbound inbound.packetHandler = inbound var err error inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex)) if err != nil { return nil, err } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } switch { case options.Method == shadowsocks.MethodNone: inbound.service = shadowsocks.NewNoneService(int64(udpTimeout.Seconds()), inbound.upstreamContextHandler()) case common.Contains(shadowaead.List, options.Method): inbound.service, err = shadowaead.NewService(options.Method, nil, options.Password, int64(udpTimeout.Seconds()), inbound.upstreamContextHandler()) case common.Contains(shadowaead_2022.List, options.Method): inbound.service, err = shadowaead_2022.NewServiceWithPassword(options.Method, options.Password, int64(udpTimeout.Seconds()), inbound.upstreamContextHandler(), ntp.TimeFuncFromContext(ctx)) default: err = E.New("unsupported method: ", options.Method) } inbound.packetUpstream = inbound.service return inbound, err } func (h *Shadowsocks) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { return h.service.NewConnection(adapter.WithContext(log.ContextWithNewID(ctx), &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *Shadowsocks) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error { return h.service.NewPacket(adapter.WithContext(ctx, &metadata), conn, buffer, adapter.UpstreamMetadata(metadata)) } func (h *Shadowsocks) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/shadowsocks_multi.go
Bcore/windows/resources/sing-box-main/inbound/shadowsocks_multi.go
package inbound import ( "context" "net" "os" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/mux" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks" "github.com/sagernet/sing-shadowsocks/shadowaead" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" "github.com/sagernet/sing/common/buf" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/ntp" ) var ( _ adapter.Inbound = (*ShadowsocksMulti)(nil) _ adapter.InjectableInbound = (*ShadowsocksMulti)(nil) ) type ShadowsocksMulti struct { myInboundAdapter service shadowsocks.MultiService[int] users []option.ShadowsocksUser } func newShadowsocksMulti(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (*ShadowsocksMulti, error) { inbound := &ShadowsocksMulti{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeShadowsocks, network: options.Network.Build(), ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, } inbound.connHandler = inbound inbound.packetHandler = inbound var err error inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex)) if err != nil { return nil, err } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } var service shadowsocks.MultiService[int] if common.Contains(shadowaead_2022.List, options.Method) { service, err = shadowaead_2022.NewMultiServiceWithPassword[int]( options.Method, options.Password, int64(udpTimeout.Seconds()), adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound), ntp.TimeFuncFromContext(ctx), ) } else if common.Contains(shadowaead.List, options.Method) { service, err = shadowaead.NewMultiService[int]( options.Method, int64(udpTimeout.Seconds()), adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound)) } else { return nil, E.New("unsupported method: " + options.Method) } if err != nil { return nil, err } err = service.UpdateUsersWithPasswords(common.MapIndexed(options.Users, func(index int, user option.ShadowsocksUser) int { return index }), common.Map(options.Users, func(user option.ShadowsocksUser) string { return user.Password })) if err != nil { return nil, err } inbound.service = service inbound.packetUpstream = service inbound.users = options.Users return inbound, err } func (h *ShadowsocksMulti) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { return h.service.NewConnection(adapter.WithContext(log.ContextWithNewID(ctx), &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *ShadowsocksMulti) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error { return h.service.NewPacket(adapter.WithContext(ctx, &metadata), conn, buffer, adapter.UpstreamMetadata(metadata)) } func (h *ShadowsocksMulti) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid } func (h *ShadowsocksMulti) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination) return h.router.RouteConnection(ctx, conn, metadata) } func (h *ShadowsocksMulti) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } ctx = log.ContextWithNewID(ctx) h.logger.InfoContext(ctx, "[", user, "] inbound packet connection from ", metadata.Source) h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination) return h.router.RoutePacketConnection(ctx, conn, metadata) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/shadowsocks_relay.go
Bcore/windows/resources/sing-box-main/inbound/shadowsocks_relay.go
package inbound import ( "context" "net" "os" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/mux" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowsocks/shadowaead_2022" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" "github.com/sagernet/sing/common/buf" F "github.com/sagernet/sing/common/format" N "github.com/sagernet/sing/common/network" ) var ( _ adapter.Inbound = (*ShadowsocksRelay)(nil) _ adapter.InjectableInbound = (*ShadowsocksRelay)(nil) ) type ShadowsocksRelay struct { myInboundAdapter service *shadowaead_2022.RelayService[int] destinations []option.ShadowsocksDestination } func newShadowsocksRelay(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowsocksInboundOptions) (*ShadowsocksRelay, error) { inbound := &ShadowsocksRelay{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeShadowsocks, network: options.Network.Build(), ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, destinations: options.Destinations, } inbound.connHandler = inbound inbound.packetHandler = inbound var err error inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex)) if err != nil { return nil, err } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } service, err := shadowaead_2022.NewRelayServiceWithPassword[int]( options.Method, options.Password, int64(udpTimeout.Seconds()), adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound), ) if err != nil { return nil, err } err = service.UpdateUsersWithPasswords(common.MapIndexed(options.Destinations, func(index int, user option.ShadowsocksDestination) int { return index }), common.Map(options.Destinations, func(user option.ShadowsocksDestination) string { return user.Password }), common.Map(options.Destinations, option.ShadowsocksDestination.Build)) if err != nil { return nil, err } inbound.service = service inbound.packetUpstream = service return inbound, err } func (h *ShadowsocksRelay) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { return h.service.NewConnection(adapter.WithContext(log.ContextWithNewID(ctx), &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *ShadowsocksRelay) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error { return h.service.NewPacket(adapter.WithContext(ctx, &metadata), conn, buffer, adapter.UpstreamMetadata(metadata)) } func (h *ShadowsocksRelay) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid } func (h *ShadowsocksRelay) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { destinationIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } destination := h.destinations[destinationIndex].Name if destination == "" { destination = F.ToString(destinationIndex) } else { metadata.User = destination } h.logger.InfoContext(ctx, "[", destination, "] inbound connection to ", metadata.Destination) return h.router.RouteConnection(ctx, conn, metadata) } func (h *ShadowsocksRelay) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { destinationIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } destination := h.destinations[destinationIndex].Name if destination == "" { destination = F.ToString(destinationIndex) } else { metadata.User = destination } ctx = log.ContextWithNewID(ctx) h.logger.InfoContext(ctx, "[", destination, "] inbound packet connection from ", metadata.Source) h.logger.InfoContext(ctx, "[", destination, "] inbound packet connection to ", metadata.Destination) return h.router.RoutePacketConnection(ctx, conn, metadata) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/vless.go
Bcore/windows/resources/sing-box-main/inbound/vless.go
package inbound import ( "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/mux" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/transport/v2ray" "github.com/sagernet/sing-vmess" "github.com/sagernet/sing-vmess/packetaddr" "github.com/sagernet/sing-vmess/vless" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) var ( _ adapter.Inbound = (*VLESS)(nil) _ adapter.InjectableInbound = (*VLESS)(nil) ) type VLESS struct { myInboundAdapter ctx context.Context users []option.VLESSUser service *vless.Service[int] tlsConfig tls.ServerConfig transport adapter.V2RayServerTransport } func NewVLESS(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.VLESSInboundOptions) (*VLESS, error) { inbound := &VLESS{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeVLESS, network: []string{N.NetworkTCP}, ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, ctx: ctx, users: options.Users, } var err error inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex)) if err != nil { return nil, err } service := vless.NewService[int](logger, adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound)) service.UpdateUsers(common.MapIndexed(inbound.users, func(index int, _ option.VLESSUser) int { return index }), common.Map(inbound.users, func(it option.VLESSUser) string { return it.UUID }), common.Map(inbound.users, func(it option.VLESSUser) string { return it.Flow })) inbound.service = service if options.TLS != nil { inbound.tlsConfig, err = tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } } if options.Transport != nil { inbound.transport, err = v2ray.NewServerTransport(ctx, common.PtrValueOrDefault(options.Transport), inbound.tlsConfig, (*vlessTransportHandler)(inbound)) if err != nil { return nil, E.Cause(err, "create server transport: ", options.Transport.Type) } } inbound.connHandler = inbound return inbound, nil } func (h *VLESS) Start() error { if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return err } } if h.transport == nil { return h.myInboundAdapter.Start() } if common.Contains(h.transport.Network(), N.NetworkTCP) { tcpListener, err := h.myInboundAdapter.ListenTCP() if err != nil { return err } go func() { sErr := h.transport.Serve(tcpListener) if sErr != nil && !E.IsClosed(sErr) { h.logger.Error("transport serve error: ", sErr) } }() } if common.Contains(h.transport.Network(), N.NetworkUDP) { udpConn, err := h.myInboundAdapter.ListenUDP() if err != nil { return err } go func() { sErr := h.transport.ServePacket(udpConn) if sErr != nil && !E.IsClosed(sErr) { h.logger.Error("transport serve error: ", sErr) } }() } return nil } func (h *VLESS) Close() error { return common.Close( h.service, &h.myInboundAdapter, h.tlsConfig, h.transport, ) } func (h *VLESS) newTransportConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { h.injectTCP(conn, metadata) return nil } func (h *VLESS) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { var err error if h.tlsConfig != nil && h.transport == nil { conn, err = tls.ServerHandshake(ctx, conn, h.tlsConfig) if err != nil { return err } } return h.service.NewConnection(adapter.WithContext(log.ContextWithNewID(ctx), &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *VLESS) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid } func (h *VLESS) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination) return h.router.RouteConnection(ctx, conn, metadata) } func (h *VLESS) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } if metadata.Destination.Fqdn == packetaddr.SeqPacketMagicAddress { metadata.Destination = M.Socksaddr{} conn = packetaddr.NewConn(conn.(vmess.PacketConn), metadata.Destination) h.logger.InfoContext(ctx, "[", user, "] inbound packet addr connection") } else { h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination) } return h.router.RoutePacketConnection(ctx, conn, metadata) } var _ adapter.V2RayServerTransportHandler = (*vlessTransportHandler)(nil) type vlessTransportHandler VLESS func (t *vlessTransportHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { return (*VLESS)(t).newTransportConnection(ctx, conn, adapter.InboundContext{ Source: metadata.Source, Destination: metadata.Destination, }) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/naive_quic_stub.go
Bcore/windows/resources/sing-box-main/inbound/naive_quic_stub.go
//go:build !with_quic package inbound import ( C "github.com/sagernet/sing-box/constant" ) func (n *Naive) configureHTTP3Listener() error { return C.ErrQUICNotIncluded }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/naive.go
Bcore/windows/resources/sing-box-main/inbound/naive.go
package inbound import ( "context" "encoding/binary" "io" "math/rand" "net" "net/http" "os" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" "github.com/sagernet/sing/common/buf" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/rw" sHttp "github.com/sagernet/sing/protocol/http" ) var _ adapter.Inbound = (*Naive)(nil) type Naive struct { myInboundAdapter authenticator *auth.Authenticator tlsConfig tls.ServerConfig httpServer *http.Server h3Server any } func NewNaive(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.NaiveInboundOptions) (*Naive, error) { inbound := &Naive{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeNaive, network: options.Network.Build(), ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, authenticator: auth.NewAuthenticator(options.Users), } if common.Contains(inbound.network, N.NetworkUDP) { if options.TLS == nil || !options.TLS.Enabled { return nil, E.New("TLS is required for QUIC server") } } if len(options.Users) == 0 { return nil, E.New("missing users") } if options.TLS != nil { tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } inbound.tlsConfig = tlsConfig } return inbound, nil } func (n *Naive) Start() error { var tlsConfig *tls.STDConfig if n.tlsConfig != nil { err := n.tlsConfig.Start() if err != nil { return E.Cause(err, "create TLS config") } tlsConfig, err = n.tlsConfig.Config() if err != nil { return err } } if common.Contains(n.network, N.NetworkTCP) { tcpListener, err := n.ListenTCP() if err != nil { return err } n.httpServer = &http.Server{ Handler: n, TLSConfig: tlsConfig, BaseContext: func(listener net.Listener) context.Context { return n.ctx }, } go func() { var sErr error if tlsConfig != nil { sErr = n.httpServer.ServeTLS(tcpListener, "", "") } else { sErr = n.httpServer.Serve(tcpListener) } if sErr != nil && !E.IsClosedOrCanceled(sErr) { n.logger.Error("http server serve error: ", sErr) } }() } if common.Contains(n.network, N.NetworkUDP) { err := n.configureHTTP3Listener() if !C.WithQUIC && len(n.network) > 1 { n.logger.Warn(E.Cause(err, "naive http3 disabled")) } else if err != nil { return err } } return nil } func (n *Naive) Close() error { return common.Close( &n.myInboundAdapter, common.PtrOrNil(n.httpServer), n.h3Server, n.tlsConfig, ) } func (n *Naive) ServeHTTP(writer http.ResponseWriter, request *http.Request) { ctx := log.ContextWithNewID(request.Context()) if request.Method != "CONNECT" { rejectHTTP(writer, http.StatusBadRequest) n.badRequest(ctx, request, E.New("not CONNECT request")) return } else if request.Header.Get("Padding") == "" { rejectHTTP(writer, http.StatusBadRequest) n.badRequest(ctx, request, E.New("missing naive padding")) return } userName, password, authOk := sHttp.ParseBasicAuth(request.Header.Get("Proxy-Authorization")) if authOk { authOk = n.authenticator.Verify(userName, password) } if !authOk { rejectHTTP(writer, http.StatusProxyAuthRequired) n.badRequest(ctx, request, E.New("authorization failed")) return } writer.Header().Set("Padding", generateNaivePaddingHeader()) writer.WriteHeader(http.StatusOK) writer.(http.Flusher).Flush() hostPort := request.URL.Host if hostPort == "" { hostPort = request.Host } source := sHttp.SourceAddress(request) destination := M.ParseSocksaddr(hostPort) if hijacker, isHijacker := writer.(http.Hijacker); isHijacker { conn, _, err := hijacker.Hijack() if err != nil { n.badRequest(ctx, request, E.New("hijack failed")) return } n.newConnection(ctx, &naiveH1Conn{Conn: conn}, userName, source, destination) } else { n.newConnection(ctx, &naiveH2Conn{reader: request.Body, writer: writer, flusher: writer.(http.Flusher)}, userName, source, destination) } } func (n *Naive) newConnection(ctx context.Context, conn net.Conn, userName string, source, destination M.Socksaddr) { if userName != "" { n.logger.InfoContext(ctx, "[", userName, "] inbound connection from ", source) n.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", destination) } else { n.logger.InfoContext(ctx, "inbound connection from ", source) n.logger.InfoContext(ctx, "inbound connection to ", destination) } hErr := n.router.RouteConnection(ctx, conn, n.createMetadata(conn, adapter.InboundContext{ Source: source, Destination: destination, User: userName, })) if hErr != nil { conn.Close() n.NewError(ctx, E.Cause(hErr, "process connection from ", source)) } } func (n *Naive) badRequest(ctx context.Context, request *http.Request, err error) { n.NewError(ctx, E.Cause(err, "process connection from ", request.RemoteAddr)) } func rejectHTTP(writer http.ResponseWriter, statusCode int) { hijacker, ok := writer.(http.Hijacker) if !ok { writer.WriteHeader(statusCode) return } conn, _, err := hijacker.Hijack() if err != nil { writer.WriteHeader(statusCode) return } if tcpConn, isTCP := common.Cast[*net.TCPConn](conn); isTCP { tcpConn.SetLinger(0) } conn.Close() } func generateNaivePaddingHeader() string { paddingLen := rand.Intn(32) + 30 padding := make([]byte, paddingLen) bits := rand.Uint64() for i := 0; i < 16; i++ { // Codes that won't be Huffman coded. padding[i] = "!#$()+<>?@[]^`{}"[bits&15] bits >>= 4 } for i := 16; i < paddingLen; i++ { padding[i] = '~' } return string(padding) } const kFirstPaddings = 8 type naiveH1Conn struct { net.Conn readPadding int writePadding int readRemaining int paddingRemaining int } func (c *naiveH1Conn) Read(p []byte) (n int, err error) { n, err = c.read(p) return n, wrapHttpError(err) } func (c *naiveH1Conn) read(p []byte) (n int, err error) { if c.readRemaining > 0 { if len(p) > c.readRemaining { p = p[:c.readRemaining] } n, err = c.Conn.Read(p) if err != nil { return } c.readRemaining -= n return } if c.paddingRemaining > 0 { err = rw.SkipN(c.Conn, c.paddingRemaining) if err != nil { return } c.paddingRemaining = 0 } if c.readPadding < kFirstPaddings { var paddingHdr []byte if len(p) >= 3 { paddingHdr = p[:3] } else { paddingHdr = make([]byte, 3) } _, err = io.ReadFull(c.Conn, paddingHdr) if err != nil { return } originalDataSize := int(binary.BigEndian.Uint16(paddingHdr[:2])) paddingSize := int(paddingHdr[2]) if len(p) > originalDataSize { p = p[:originalDataSize] } n, err = c.Conn.Read(p) if err != nil { return } c.readPadding++ c.readRemaining = originalDataSize - n c.paddingRemaining = paddingSize return } return c.Conn.Read(p) } func (c *naiveH1Conn) Write(p []byte) (n int, err error) { for pLen := len(p); pLen > 0; { var data []byte if pLen > 65535 { data = p[:65535] p = p[65535:] pLen -= 65535 } else { data = p pLen = 0 } var writeN int writeN, err = c.write(data) n += writeN if err != nil { break } } return n, wrapHttpError(err) } func (c *naiveH1Conn) write(p []byte) (n int, err error) { if c.writePadding < kFirstPaddings { paddingSize := rand.Intn(256) buffer := buf.NewSize(3 + len(p) + paddingSize) defer buffer.Release() header := buffer.Extend(3) binary.BigEndian.PutUint16(header, uint16(len(p))) header[2] = byte(paddingSize) common.Must1(buffer.Write(p)) _, err = c.Conn.Write(buffer.Bytes()) if err == nil { n = len(p) } c.writePadding++ return } return c.Conn.Write(p) } func (c *naiveH1Conn) FrontHeadroom() int { if c.writePadding < kFirstPaddings { return 3 } return 0 } func (c *naiveH1Conn) RearHeadroom() int { if c.writePadding < kFirstPaddings { return 255 } return 0 } func (c *naiveH1Conn) WriterMTU() int { if c.writePadding < kFirstPaddings { return 65535 } return 0 } func (c *naiveH1Conn) WriteBuffer(buffer *buf.Buffer) error { defer buffer.Release() if c.writePadding < kFirstPaddings { bufferLen := buffer.Len() if bufferLen > 65535 { return common.Error(c.Write(buffer.Bytes())) } paddingSize := rand.Intn(256) header := buffer.ExtendHeader(3) binary.BigEndian.PutUint16(header, uint16(bufferLen)) header[2] = byte(paddingSize) buffer.Extend(paddingSize) c.writePadding++ } return wrapHttpError(common.Error(c.Conn.Write(buffer.Bytes()))) } // FIXME /*func (c *naiveH1Conn) WriteTo(w io.Writer) (n int64, err error) { if c.readPadding < kFirstPaddings { n, err = bufio.WriteToN(c, w, kFirstPaddings-c.readPadding) } else { n, err = bufio.Copy(w, c.Conn) } return n, wrapHttpError(err) } func (c *naiveH1Conn) ReadFrom(r io.Reader) (n int64, err error) { if c.writePadding < kFirstPaddings { n, err = bufio.ReadFromN(c, r, kFirstPaddings-c.writePadding) } else { n, err = bufio.Copy(c.Conn, r) } return n, wrapHttpError(err) } */ func (c *naiveH1Conn) Upstream() any { return c.Conn } func (c *naiveH1Conn) ReaderReplaceable() bool { return c.readPadding == kFirstPaddings } func (c *naiveH1Conn) WriterReplaceable() bool { return c.writePadding == kFirstPaddings } type naiveH2Conn struct { reader io.Reader writer io.Writer flusher http.Flusher rAddr net.Addr readPadding int writePadding int readRemaining int paddingRemaining int } func (c *naiveH2Conn) Read(p []byte) (n int, err error) { n, err = c.read(p) return n, wrapHttpError(err) } func (c *naiveH2Conn) read(p []byte) (n int, err error) { if c.readRemaining > 0 { if len(p) > c.readRemaining { p = p[:c.readRemaining] } n, err = c.reader.Read(p) if err != nil { return } c.readRemaining -= n return } if c.paddingRemaining > 0 { err = rw.SkipN(c.reader, c.paddingRemaining) if err != nil { return } c.paddingRemaining = 0 } if c.readPadding < kFirstPaddings { var paddingHdr []byte if len(p) >= 3 { paddingHdr = p[:3] } else { paddingHdr = make([]byte, 3) } _, err = io.ReadFull(c.reader, paddingHdr) if err != nil { return } originalDataSize := int(binary.BigEndian.Uint16(paddingHdr[:2])) paddingSize := int(paddingHdr[2]) if len(p) > originalDataSize { p = p[:originalDataSize] } n, err = c.reader.Read(p) if err != nil { return } c.readPadding++ c.readRemaining = originalDataSize - n c.paddingRemaining = paddingSize return } return c.reader.Read(p) } func (c *naiveH2Conn) Write(p []byte) (n int, err error) { for pLen := len(p); pLen > 0; { var data []byte if pLen > 65535 { data = p[:65535] p = p[65535:] pLen -= 65535 } else { data = p pLen = 0 } var writeN int writeN, err = c.write(data) n += writeN if err != nil { break } } if err == nil { c.flusher.Flush() } return n, wrapHttpError(err) } func (c *naiveH2Conn) write(p []byte) (n int, err error) { if c.writePadding < kFirstPaddings { paddingSize := rand.Intn(256) buffer := buf.NewSize(3 + len(p) + paddingSize) defer buffer.Release() header := buffer.Extend(3) binary.BigEndian.PutUint16(header, uint16(len(p))) header[2] = byte(paddingSize) common.Must1(buffer.Write(p)) _, err = c.writer.Write(buffer.Bytes()) if err == nil { n = len(p) } c.writePadding++ return } return c.writer.Write(p) } func (c *naiveH2Conn) FrontHeadroom() int { if c.writePadding < kFirstPaddings { return 3 } return 0 } func (c *naiveH2Conn) RearHeadroom() int { if c.writePadding < kFirstPaddings { return 255 } return 0 } func (c *naiveH2Conn) WriterMTU() int { if c.writePadding < kFirstPaddings { return 65535 } return 0 } func (c *naiveH2Conn) WriteBuffer(buffer *buf.Buffer) error { defer buffer.Release() if c.writePadding < kFirstPaddings { bufferLen := buffer.Len() if bufferLen > 65535 { return common.Error(c.Write(buffer.Bytes())) } paddingSize := rand.Intn(256) header := buffer.ExtendHeader(3) binary.BigEndian.PutUint16(header, uint16(bufferLen)) header[2] = byte(paddingSize) buffer.Extend(paddingSize) c.writePadding++ } err := common.Error(c.writer.Write(buffer.Bytes())) if err == nil { c.flusher.Flush() } return wrapHttpError(err) } // FIXME /*func (c *naiveH2Conn) WriteTo(w io.Writer) (n int64, err error) { if c.readPadding < kFirstPaddings { n, err = bufio.WriteToN(c, w, kFirstPaddings-c.readPadding) } else { n, err = bufio.Copy(w, c.reader) } return n, wrapHttpError(err) } func (c *naiveH2Conn) ReadFrom(r io.Reader) (n int64, err error) { if c.writePadding < kFirstPaddings { n, err = bufio.ReadFromN(c, r, kFirstPaddings-c.writePadding) } else { n, err = bufio.Copy(c.writer, r) } return n, wrapHttpError(err) }*/ func (c *naiveH2Conn) Close() error { return common.Close( c.reader, c.writer, ) } func (c *naiveH2Conn) LocalAddr() net.Addr { return M.Socksaddr{} } func (c *naiveH2Conn) RemoteAddr() net.Addr { return c.rAddr } func (c *naiveH2Conn) SetDeadline(t time.Time) error { return os.ErrInvalid } func (c *naiveH2Conn) SetReadDeadline(t time.Time) error { return os.ErrInvalid } func (c *naiveH2Conn) SetWriteDeadline(t time.Time) error { return os.ErrInvalid } func (c *naiveH2Conn) NeedAdditionalReadDeadline() bool { return true } func (c *naiveH2Conn) UpstreamReader() any { return c.reader } func (c *naiveH2Conn) UpstreamWriter() any { return c.writer } func (c *naiveH2Conn) ReaderReplaceable() bool { return c.readPadding == kFirstPaddings } func (c *naiveH2Conn) WriterReplaceable() bool { return c.writePadding == kFirstPaddings } func wrapHttpError(err error) error { if err == nil { return err } if strings.Contains(err.Error(), "client disconnected") { return net.ErrClosed } if strings.Contains(err.Error(), "body closed by handler") { return net.ErrClosed } if strings.Contains(err.Error(), "canceled with error code 268") { return io.EOF } return err }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default_tcp_nongo1.20.go
Bcore/windows/resources/sing-box-main/inbound/default_tcp_nongo1.20.go
//go:build !go1.20 package inbound import ( "context" "net" "os" ) const go120Available = false func listenTFO(listenConfig net.ListenConfig, ctx context.Context, network string, address string) (net.Listener, error) { return nil, os.ErrInvalid }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default_tcp.go
Bcore/windows/resources/sing-box-main/inbound/default_tcp.go
package inbound import ( "context" "net" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing/common/control" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) func (a *myInboundAdapter) ListenTCP() (net.Listener, error) { var err error bindAddr := M.SocksaddrFrom(a.listenOptions.Listen.Build(), a.listenOptions.ListenPort) var tcpListener net.Listener var listenConfig net.ListenConfig // TODO: Add an option to customize the keep alive period listenConfig.KeepAlive = C.TCPKeepAliveInitial listenConfig.Control = control.Append(listenConfig.Control, control.SetKeepAlivePeriod(C.TCPKeepAliveInitial, C.TCPKeepAliveInterval)) if a.listenOptions.TCPMultiPath { if !go121Available { return nil, E.New("MultiPath TCP requires go1.21, please recompile your binary.") } setMultiPathTCP(&listenConfig) } if a.listenOptions.TCPFastOpen { if !go120Available { return nil, E.New("TCP Fast Open requires go1.20, please recompile your binary.") } tcpListener, err = listenTFO(listenConfig, a.ctx, M.NetworkFromNetAddr(N.NetworkTCP, bindAddr.Addr), bindAddr.String()) } else { tcpListener, err = listenConfig.Listen(a.ctx, M.NetworkFromNetAddr(N.NetworkTCP, bindAddr.Addr), bindAddr.String()) } if err == nil { a.logger.Info("tcp server started at ", tcpListener.Addr()) } if a.listenOptions.ProxyProtocol || a.listenOptions.ProxyProtocolAcceptNoHeader { return nil, E.New("Proxy Protocol is deprecated and removed in sing-box 1.6.0") } a.tcpListener = tcpListener return tcpListener, err } func (a *myInboundAdapter) loopTCPIn() { tcpListener := a.tcpListener for { conn, err := tcpListener.Accept() if err != nil { //goland:noinspection GoDeprecation //nolint:staticcheck if netError, isNetError := err.(net.Error); isNetError && netError.Temporary() { a.logger.Error(err) continue } if a.inShutdown.Load() && E.IsClosed(err) { return } a.tcpListener.Close() a.logger.Error("serve error: ", err) continue } go a.injectTCP(conn, adapter.InboundContext{}) } } func (a *myInboundAdapter) injectTCP(conn net.Conn, metadata adapter.InboundContext) { ctx := log.ContextWithNewID(a.ctx) metadata = a.createMetadata(conn, metadata) a.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) hErr := a.connHandler.NewConnection(ctx, conn, metadata) if hErr != nil { conn.Close() a.NewError(ctx, E.Cause(hErr, "process connection from ", metadata.Source)) } } func (a *myInboundAdapter) routeTCP(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) { a.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) hErr := a.newConnection(ctx, conn, metadata) if hErr != nil { conn.Close() a.NewError(ctx, E.Cause(hErr, "process connection from ", metadata.Source)) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/tuic_stub.go
Bcore/windows/resources/sing-box-main/inbound/tuic_stub.go
//go:build !with_quic package inbound import ( "context" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" ) func NewTUIC(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TUICInboundOptions) (adapter.Inbound, error) { return nil, C.ErrQUICNotIncluded }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/default_udp.go
Bcore/windows/resources/sing-box-main/inbound/default_udp.go
package inbound import ( "net" "os" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/buf" "github.com/sagernet/sing/common/control" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) func (a *myInboundAdapter) ListenUDP() (net.PacketConn, error) { bindAddr := M.SocksaddrFrom(a.listenOptions.Listen.Build(), a.listenOptions.ListenPort) var lc net.ListenConfig var udpFragment bool if a.listenOptions.UDPFragment != nil { udpFragment = *a.listenOptions.UDPFragment } else { udpFragment = a.listenOptions.UDPFragmentDefault } if !udpFragment { lc.Control = control.Append(lc.Control, control.DisableUDPFragment()) } udpConn, err := lc.ListenPacket(a.ctx, M.NetworkFromNetAddr(N.NetworkUDP, bindAddr.Addr), bindAddr.String()) if err != nil { return nil, err } a.udpConn = udpConn.(*net.UDPConn) a.udpAddr = bindAddr a.logger.Info("udp server started at ", udpConn.LocalAddr()) return udpConn, err } func (a *myInboundAdapter) loopUDPIn() { defer close(a.packetOutboundClosed) buffer := buf.NewPacket() defer buffer.Release() buffer.IncRef() defer buffer.DecRef() packetService := (*myInboundPacketAdapter)(a) for { buffer.Reset() n, addr, err := a.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes()) if err != nil { return } buffer.Truncate(n) var metadata adapter.InboundContext metadata.Inbound = a.tag metadata.InboundType = a.protocol metadata.InboundOptions = a.listenOptions.InboundOptions metadata.Source = M.SocksaddrFromNetIP(addr).Unwrap() metadata.OriginDestination = a.udpAddr err = a.packetHandler.NewPacket(a.ctx, packetService, buffer, metadata) if err != nil { a.newError(E.Cause(err, "process packet from ", metadata.Source)) } } } func (a *myInboundAdapter) loopUDPOOBIn() { defer close(a.packetOutboundClosed) buffer := buf.NewPacket() defer buffer.Release() buffer.IncRef() defer buffer.DecRef() packetService := (*myInboundPacketAdapter)(a) oob := make([]byte, 1024) for { buffer.Reset() n, oobN, _, addr, err := a.udpConn.ReadMsgUDPAddrPort(buffer.FreeBytes(), oob) if err != nil { return } buffer.Truncate(n) var metadata adapter.InboundContext metadata.Inbound = a.tag metadata.InboundType = a.protocol metadata.InboundOptions = a.listenOptions.InboundOptions metadata.Source = M.SocksaddrFromNetIP(addr).Unwrap() metadata.OriginDestination = a.udpAddr err = a.oobPacketHandler.NewPacket(a.ctx, packetService, buffer, oob[:oobN], metadata) if err != nil { a.newError(E.Cause(err, "process packet from ", metadata.Source)) } } } func (a *myInboundAdapter) loopUDPInThreadSafe() { defer close(a.packetOutboundClosed) packetService := (*myInboundPacketAdapter)(a) for { buffer := buf.NewPacket() n, addr, err := a.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes()) if err != nil { buffer.Release() return } buffer.Truncate(n) var metadata adapter.InboundContext metadata.Inbound = a.tag metadata.InboundType = a.protocol metadata.InboundOptions = a.listenOptions.InboundOptions metadata.Source = M.SocksaddrFromNetIP(addr).Unwrap() metadata.OriginDestination = a.udpAddr err = a.packetHandler.NewPacket(a.ctx, packetService, buffer, metadata) if err != nil { buffer.Release() a.newError(E.Cause(err, "process packet from ", metadata.Source)) } } } func (a *myInboundAdapter) loopUDPOOBInThreadSafe() { defer close(a.packetOutboundClosed) packetService := (*myInboundPacketAdapter)(a) oob := make([]byte, 1024) for { buffer := buf.NewPacket() n, oobN, _, addr, err := a.udpConn.ReadMsgUDPAddrPort(buffer.FreeBytes(), oob) if err != nil { buffer.Release() return } buffer.Truncate(n) var metadata adapter.InboundContext metadata.Inbound = a.tag metadata.InboundType = a.protocol metadata.InboundOptions = a.listenOptions.InboundOptions metadata.Source = M.SocksaddrFromNetIP(addr).Unwrap() metadata.OriginDestination = a.udpAddr err = a.oobPacketHandler.NewPacket(a.ctx, packetService, buffer, oob[:oobN], metadata) if err != nil { buffer.Release() a.newError(E.Cause(err, "process packet from ", metadata.Source)) } } } func (a *myInboundAdapter) loopUDPOut() { for { select { case packet := <-a.packetOutbound: err := a.writePacket(packet.buffer, packet.destination) if err != nil && !E.IsClosed(err) { a.newError(E.New("write back udp: ", err)) } continue case <-a.packetOutboundClosed: } for { select { case packet := <-a.packetOutbound: packet.buffer.Release() default: return } } } } func (a *myInboundAdapter) writePacket(buffer *buf.Buffer, destination M.Socksaddr) error { defer buffer.Release() if destination.IsFqdn() { udpAddr, err := net.ResolveUDPAddr(N.NetworkUDP, destination.String()) if err != nil { return err } return common.Error(a.udpConn.WriteTo(buffer.Bytes(), udpAddr)) } return common.Error(a.udpConn.WriteToUDPAddrPort(buffer.Bytes(), destination.AddrPort())) } type myInboundPacketAdapter myInboundAdapter func (s *myInboundPacketAdapter) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) { n, addr, err := s.udpConn.ReadFromUDPAddrPort(buffer.FreeBytes()) if err != nil { return M.Socksaddr{}, err } buffer.Truncate(n) return M.SocksaddrFromNetIP(addr), nil } func (s *myInboundPacketAdapter) WriteIsThreadUnsafe() { } type myInboundPacket struct { buffer *buf.Buffer destination M.Socksaddr } func (s *myInboundPacketAdapter) Upstream() any { return s.udpConn } func (s *myInboundPacketAdapter) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error { select { case s.packetOutbound <- &myInboundPacket{buffer, destination}: return nil case <-s.packetOutboundClosed: return os.ErrClosed } } func (s *myInboundPacketAdapter) Close() error { return s.udpConn.Close() } func (s *myInboundPacketAdapter) LocalAddr() net.Addr { return s.udpConn.LocalAddr() } func (s *myInboundPacketAdapter) SetDeadline(t time.Time) error { return s.udpConn.SetDeadline(t) } func (s *myInboundPacketAdapter) SetReadDeadline(t time.Time) error { return s.udpConn.SetReadDeadline(t) } func (s *myInboundPacketAdapter) SetWriteDeadline(t time.Time) error { return s.udpConn.SetWriteDeadline(t) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/builder.go
Bcore/windows/resources/sing-box-main/inbound/builder.go
package inbound import ( "context" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/experimental/libbox/platform" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) func New(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Inbound, platformInterface platform.Interface) (adapter.Inbound, error) { if options.Type == "" { return nil, E.New("missing inbound type") } switch options.Type { case C.TypeTun: return NewTun(ctx, router, logger, tag, options.TunOptions, platformInterface) case C.TypeRedirect: return NewRedirect(ctx, router, logger, tag, options.RedirectOptions), nil case C.TypeTProxy: return NewTProxy(ctx, router, logger, tag, options.TProxyOptions), nil case C.TypeDirect: return NewDirect(ctx, router, logger, tag, options.DirectOptions), nil case C.TypeSOCKS: return NewSocks(ctx, router, logger, tag, options.SocksOptions), nil case C.TypeHTTP: return NewHTTP(ctx, router, logger, tag, options.HTTPOptions) case C.TypeMixed: return NewMixed(ctx, router, logger, tag, options.MixedOptions), nil case C.TypeShadowsocks: return NewShadowsocks(ctx, router, logger, tag, options.ShadowsocksOptions) case C.TypeVMess: return NewVMess(ctx, router, logger, tag, options.VMessOptions) case C.TypeTrojan: return NewTrojan(ctx, router, logger, tag, options.TrojanOptions) case C.TypeNaive: return NewNaive(ctx, router, logger, tag, options.NaiveOptions) case C.TypeHysteria: return NewHysteria(ctx, router, logger, tag, options.HysteriaOptions) case C.TypeShadowTLS: return NewShadowTLS(ctx, router, logger, tag, options.ShadowTLSOptions) case C.TypeVLESS: return NewVLESS(ctx, router, logger, tag, options.VLESSOptions) case C.TypeTUIC: return NewTUIC(ctx, router, logger, tag, options.TUICOptions) case C.TypeHysteria2: return NewHysteria2(ctx, router, logger, tag, options.Hysteria2Options) default: return nil, E.New("unknown inbound type: ", options.Type) } }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/http.go
Bcore/windows/resources/sing-box-main/inbound/http.go
package inbound import ( std_bufio "bufio" "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/protocol/http" ) var ( _ adapter.Inbound = (*HTTP)(nil) _ adapter.InjectableInbound = (*HTTP)(nil) ) type HTTP struct { myInboundAdapter authenticator *auth.Authenticator tlsConfig tls.ServerConfig } func NewHTTP(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPMixedInboundOptions) (*HTTP, error) { inbound := &HTTP{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeHTTP, network: []string{N.NetworkTCP}, ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, setSystemProxy: options.SetSystemProxy, }, authenticator: auth.NewAuthenticator(options.Users), } if options.TLS != nil { tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } inbound.tlsConfig = tlsConfig } inbound.connHandler = inbound return inbound, nil } func (h *HTTP) Start() error { if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return E.Cause(err, "create TLS config") } } return h.myInboundAdapter.Start() } func (h *HTTP) Close() error { return common.Close( &h.myInboundAdapter, h.tlsConfig, ) } func (h *HTTP) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { var err error if h.tlsConfig != nil { conn, err = tls.ServerHandshake(ctx, conn, h.tlsConfig) if err != nil { return err } } return http.HandleConnection(ctx, conn, std_bufio.NewReader(conn), h.authenticator, h.upstreamUserHandler(metadata), adapter.UpstreamMetadata(metadata)) } func (h *HTTP) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid } func (a *myInboundAdapter) upstreamUserHandler(metadata adapter.InboundContext) adapter.UpstreamHandlerAdapter { return adapter.NewUpstreamHandler(metadata, a.newUserConnection, a.streamUserPacketConnection, a) } func (a *myInboundAdapter) newUserConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { user, loaded := auth.UserFromContext[string](ctx) if !loaded { a.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) return a.router.RouteConnection(ctx, conn, metadata) } metadata.User = user a.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination) return a.router.RouteConnection(ctx, conn, metadata) } func (a *myInboundAdapter) streamUserPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { user, loaded := auth.UserFromContext[string](ctx) if !loaded { a.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) return a.router.RoutePacketConnection(ctx, conn, metadata) } metadata.User = user a.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination) return a.router.RoutePacketConnection(ctx, conn, metadata) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/mixed.go
Bcore/windows/resources/sing-box-main/inbound/mixed.go
package inbound import ( std_bufio "bufio" "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/auth" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/protocol/http" "github.com/sagernet/sing/protocol/socks" "github.com/sagernet/sing/protocol/socks/socks4" "github.com/sagernet/sing/protocol/socks/socks5" ) var ( _ adapter.Inbound = (*Mixed)(nil) _ adapter.InjectableInbound = (*Mixed)(nil) ) type Mixed struct { myInboundAdapter authenticator *auth.Authenticator } func NewMixed(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HTTPMixedInboundOptions) *Mixed { inbound := &Mixed{ myInboundAdapter{ protocol: C.TypeMixed, network: []string{N.NetworkTCP}, ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, setSystemProxy: options.SetSystemProxy, }, auth.NewAuthenticator(options.Users), } inbound.connHandler = inbound return inbound } func (h *Mixed) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { reader := std_bufio.NewReader(conn) headerBytes, err := reader.Peek(1) if err != nil { return err } switch headerBytes[0] { case socks4.Version, socks5.Version: return socks.HandleConnection0(ctx, conn, reader, h.authenticator, h.upstreamUserHandler(metadata), adapter.UpstreamMetadata(metadata)) default: return http.HandleConnection(ctx, conn, reader, h.authenticator, h.upstreamUserHandler(metadata), adapter.UpstreamMetadata(metadata)) } } func (h *Mixed) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/redirect.go
Bcore/windows/resources/sing-box-main/inbound/redirect.go
package inbound import ( "context" "net" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/redir" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type Redirect struct { myInboundAdapter } func NewRedirect(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.RedirectInboundOptions) *Redirect { redirect := &Redirect{ myInboundAdapter{ protocol: C.TypeRedirect, network: []string{N.NetworkTCP}, ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, } redirect.connHandler = redirect return redirect } func (r *Redirect) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { destination, err := redir.GetOriginalDestination(conn) if err != nil { return E.Cause(err, "get redirect destination") } metadata.Destination = M.SocksaddrFromNetIP(destination) return r.newConnection(ctx, conn, metadata) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/shadowtls.go
Bcore/windows/resources/sing-box-main/inbound/shadowtls.go
package inbound import ( "context" "net" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/dialer" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-shadowtls" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" N "github.com/sagernet/sing/common/network" ) type ShadowTLS struct { myInboundAdapter service *shadowtls.Service } func NewShadowTLS(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.ShadowTLSInboundOptions) (*ShadowTLS, error) { inbound := &ShadowTLS{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeShadowTLS, network: []string{N.NetworkTCP}, ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, } if options.Version == 0 { options.Version = 1 } var handshakeForServerName map[string]shadowtls.HandshakeConfig if options.Version > 1 { handshakeForServerName = make(map[string]shadowtls.HandshakeConfig) for serverName, serverOptions := range options.HandshakeForServerName { handshakeDialer, err := dialer.New(router, serverOptions.DialerOptions) if err != nil { return nil, err } handshakeForServerName[serverName] = shadowtls.HandshakeConfig{ Server: serverOptions.ServerOptions.Build(), Dialer: handshakeDialer, } } } handshakeDialer, err := dialer.New(router, options.Handshake.DialerOptions) if err != nil { return nil, err } service, err := shadowtls.NewService(shadowtls.ServiceConfig{ Version: options.Version, Password: options.Password, Users: common.Map(options.Users, func(it option.ShadowTLSUser) shadowtls.User { return (shadowtls.User)(it) }), Handshake: shadowtls.HandshakeConfig{ Server: options.Handshake.ServerOptions.Build(), Dialer: handshakeDialer, }, HandshakeForServerName: handshakeForServerName, StrictMode: options.StrictMode, Handler: adapter.NewUpstreamContextHandler(inbound.newConnection, nil, inbound), Logger: logger, }) if err != nil { return nil, err } inbound.service = service inbound.connHandler = inbound return inbound, nil } func (h *ShadowTLS) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { return h.service.NewConnection(adapter.WithContext(log.ContextWithNewID(ctx), &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *ShadowTLS) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { if userName, _ := auth.UserFromContext[string](ctx); userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) } return h.router.RouteConnection(ctx, conn, metadata) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/trojan.go
Bcore/windows/resources/sing-box-main/inbound/trojan.go
package inbound import ( "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/mux" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/transport/trojan" "github.com/sagernet/sing-box/transport/v2ray" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) var ( _ adapter.Inbound = (*Trojan)(nil) _ adapter.InjectableInbound = (*Trojan)(nil) ) type Trojan struct { myInboundAdapter service *trojan.Service[int] users []option.TrojanUser tlsConfig tls.ServerConfig fallbackAddr M.Socksaddr fallbackAddrTLSNextProto map[string]M.Socksaddr transport adapter.V2RayServerTransport } func NewTrojan(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TrojanInboundOptions) (*Trojan, error) { inbound := &Trojan{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeTrojan, network: []string{N.NetworkTCP}, ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, users: options.Users, } if options.TLS != nil { tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } inbound.tlsConfig = tlsConfig } var fallbackHandler N.TCPConnectionHandler if options.Fallback != nil && options.Fallback.Server != "" || len(options.FallbackForALPN) > 0 { if options.Fallback != nil && options.Fallback.Server != "" { inbound.fallbackAddr = options.Fallback.Build() if !inbound.fallbackAddr.IsValid() { return nil, E.New("invalid fallback address: ", inbound.fallbackAddr) } } if len(options.FallbackForALPN) > 0 { if inbound.tlsConfig == nil { return nil, E.New("fallback for ALPN is not supported without TLS") } fallbackAddrNextProto := make(map[string]M.Socksaddr) for nextProto, destination := range options.FallbackForALPN { fallbackAddr := destination.Build() if !fallbackAddr.IsValid() { return nil, E.New("invalid fallback address for ALPN ", nextProto, ": ", fallbackAddr) } fallbackAddrNextProto[nextProto] = fallbackAddr } inbound.fallbackAddrTLSNextProto = fallbackAddrNextProto } fallbackHandler = adapter.NewUpstreamContextHandler(inbound.fallbackConnection, nil, nil) } service := trojan.NewService[int](adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound), fallbackHandler) err := service.UpdateUsers(common.MapIndexed(options.Users, func(index int, it option.TrojanUser) int { return index }), common.Map(options.Users, func(it option.TrojanUser) string { return it.Password })) if err != nil { return nil, err } if options.Transport != nil { inbound.transport, err = v2ray.NewServerTransport(ctx, common.PtrValueOrDefault(options.Transport), inbound.tlsConfig, (*trojanTransportHandler)(inbound)) if err != nil { return nil, E.Cause(err, "create server transport: ", options.Transport.Type) } } inbound.router, err = mux.NewRouterWithOptions(inbound.router, logger, common.PtrValueOrDefault(options.Multiplex)) if err != nil { return nil, err } inbound.service = service inbound.connHandler = inbound return inbound, nil } func (h *Trojan) Start() error { if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return E.Cause(err, "create TLS config") } } if h.transport == nil { return h.myInboundAdapter.Start() } if common.Contains(h.transport.Network(), N.NetworkTCP) { tcpListener, err := h.myInboundAdapter.ListenTCP() if err != nil { return err } go func() { sErr := h.transport.Serve(tcpListener) if sErr != nil && !E.IsClosed(sErr) { h.logger.Error("transport serve error: ", sErr) } }() } if common.Contains(h.transport.Network(), N.NetworkUDP) { udpConn, err := h.myInboundAdapter.ListenUDP() if err != nil { return err } go func() { sErr := h.transport.ServePacket(udpConn) if sErr != nil && !E.IsClosed(sErr) { h.logger.Error("transport serve error: ", sErr) } }() } return nil } func (h *Trojan) Close() error { return common.Close( &h.myInboundAdapter, h.tlsConfig, h.transport, ) } func (h *Trojan) newTransportConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { h.injectTCP(conn, metadata) return nil } func (h *Trojan) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { var err error if h.tlsConfig != nil && h.transport == nil { conn, err = tls.ServerHandshake(ctx, conn, h.tlsConfig) if err != nil { return err } } return h.service.NewConnection(adapter.WithContext(ctx, &metadata), conn, adapter.UpstreamMetadata(metadata)) } func (h *Trojan) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return os.ErrInvalid } func (h *Trojan) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } h.logger.InfoContext(ctx, "[", user, "] inbound connection to ", metadata.Destination) return h.router.RouteConnection(ctx, conn, metadata) } func (h *Trojan) fallbackConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { var fallbackAddr M.Socksaddr if len(h.fallbackAddrTLSNextProto) > 0 { if tlsConn, loaded := common.Cast[tls.Conn](conn); loaded { connectionState := tlsConn.ConnectionState() if connectionState.NegotiatedProtocol != "" { if fallbackAddr, loaded = h.fallbackAddrTLSNextProto[connectionState.NegotiatedProtocol]; !loaded { return E.New("fallback disabled for ALPN: ", connectionState.NegotiatedProtocol) } } } } if !fallbackAddr.IsValid() { if !h.fallbackAddr.IsValid() { return E.New("fallback disabled by default") } fallbackAddr = h.fallbackAddr } h.logger.InfoContext(ctx, "fallback connection to ", fallbackAddr) metadata.Destination = fallbackAddr return h.router.RouteConnection(ctx, conn, metadata) } func (h *Trojan) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { userIndex, loaded := auth.UserFromContext[int](ctx) if !loaded { return os.ErrInvalid } user := h.users[userIndex].Name if user == "" { user = F.ToString(userIndex) } else { metadata.User = user } h.logger.InfoContext(ctx, "[", user, "] inbound packet connection to ", metadata.Destination) return h.router.RoutePacketConnection(ctx, conn, metadata) } var _ adapter.V2RayServerTransportHandler = (*trojanTransportHandler)(nil) type trojanTransportHandler Trojan func (t *trojanTransportHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error { return (*Trojan)(t).newTransportConnection(ctx, conn, adapter.InboundContext{ Source: metadata.Source, Destination: metadata.Destination, }) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/tuic.go
Bcore/windows/resources/sing-box-main/inbound/tuic.go
//go:build with_quic package inbound import ( "context" "net" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" "github.com/sagernet/sing-box/common/uot" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-quic/tuic" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" "github.com/gofrs/uuid/v5" ) var _ adapter.Inbound = (*TUIC)(nil) type TUIC struct { myInboundAdapter tlsConfig tls.ServerConfig server *tuic.Service[int] userNameList []string } func NewTUIC(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TUICInboundOptions) (*TUIC, error) { options.UDPFragmentDefault = true if options.TLS == nil || !options.TLS.Enabled { return nil, C.ErrTLSRequired } tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } inbound := &TUIC{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeTUIC, network: []string{N.NetworkUDP}, ctx: ctx, router: uot.NewRouter(router, logger), logger: logger, tag: tag, listenOptions: options.ListenOptions, }, tlsConfig: tlsConfig, } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } service, err := tuic.NewService[int](tuic.ServiceOptions{ Context: ctx, Logger: logger, TLSConfig: tlsConfig, CongestionControl: options.CongestionControl, AuthTimeout: time.Duration(options.AuthTimeout), ZeroRTTHandshake: options.ZeroRTTHandshake, Heartbeat: time.Duration(options.Heartbeat), UDPTimeout: udpTimeout, Handler: adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, nil), }) if err != nil { return nil, err } var userList []int var userNameList []string var userUUIDList [][16]byte var userPasswordList []string for index, user := range options.Users { if user.UUID == "" { return nil, E.New("missing uuid for user ", index) } userUUID, err := uuid.FromString(user.UUID) if err != nil { return nil, E.Cause(err, "invalid uuid for user ", index) } userList = append(userList, index) userNameList = append(userNameList, user.Name) userUUIDList = append(userUUIDList, userUUID) userPasswordList = append(userPasswordList, user.Password) } service.UpdateUsers(userList, userUUIDList, userPasswordList) inbound.server = service inbound.userNameList = userNameList return inbound, nil } func (h *TUIC) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) metadata = h.createMetadata(conn, metadata) h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) } return h.router.RouteConnection(ctx, conn, metadata) } func (h *TUIC) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) metadata = h.createPacketMetadata(conn, metadata) h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) } return h.router.RoutePacketConnection(ctx, conn, metadata) } func (h *TUIC) Start() error { if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return err } } packetConn, err := h.myInboundAdapter.ListenUDP() if err != nil { return err } return h.server.Start(packetConn) } func (h *TUIC) Close() error { return common.Close( &h.myInboundAdapter, h.tlsConfig, common.PtrOrNil(h.server), ) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/hysteria_stub.go
Bcore/windows/resources/sing-box-main/inbound/hysteria_stub.go
//go:build !with_quic package inbound import ( "context" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" ) func NewHysteria(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.HysteriaInboundOptions) (adapter.Inbound, error) { return nil, C.ErrQUICNotIncluded } func NewHysteria2(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2InboundOptions) (adapter.Inbound, error) { return nil, C.ErrQUICNotIncluded }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/tun.go
Bcore/windows/resources/sing-box-main/inbound/tun.go
package inbound import ( "context" "net" "net/netip" "os" "runtime" "strconv" "strings" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/taskmonitor" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/experimental/libbox/platform" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-tun" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/ranges" "github.com/sagernet/sing/common/x/list" "go4.org/netipx" ) var _ adapter.Inbound = (*Tun)(nil) type Tun struct { tag string ctx context.Context router adapter.Router logger log.ContextLogger inboundOptions option.InboundOptions tunOptions tun.Options endpointIndependentNat bool udpTimeout int64 stack string tunIf tun.Tun tunStack tun.Stack platformInterface platform.Interface platformOptions option.TunPlatformOptions autoRedirect tun.AutoRedirect routeRuleSet []adapter.RuleSet routeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback] routeExcludeRuleSet []adapter.RuleSet routeExcludeRuleSetCallback []*list.Element[adapter.RuleSetUpdateCallback] routeAddressSet []*netipx.IPSet routeExcludeAddressSet []*netipx.IPSet } func NewTun(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.TunInboundOptions, platformInterface platform.Interface) (*Tun, error) { address := options.Address //nolint:staticcheck //goland:noinspection GoDeprecation if len(options.Inet4Address) > 0 { address = append(address, options.Inet4Address...) } //nolint:staticcheck //goland:noinspection GoDeprecation if len(options.Inet6Address) > 0 { address = append(address, options.Inet6Address...) } inet4Address := common.Filter(address, func(it netip.Prefix) bool { return it.Addr().Is4() }) inet6Address := common.Filter(address, func(it netip.Prefix) bool { return it.Addr().Is6() }) routeAddress := options.RouteAddress //nolint:staticcheck //goland:noinspection GoDeprecation if len(options.Inet4RouteAddress) > 0 { routeAddress = append(routeAddress, options.Inet4RouteAddress...) } //nolint:staticcheck //goland:noinspection GoDeprecation if len(options.Inet6RouteAddress) > 0 { routeAddress = append(routeAddress, options.Inet6RouteAddress...) } inet4RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool { return it.Addr().Is4() }) inet6RouteAddress := common.Filter(routeAddress, func(it netip.Prefix) bool { return it.Addr().Is6() }) routeExcludeAddress := options.RouteExcludeAddress //nolint:staticcheck //goland:noinspection GoDeprecation if len(options.Inet4RouteExcludeAddress) > 0 { routeExcludeAddress = append(routeExcludeAddress, options.Inet4RouteExcludeAddress...) } //nolint:staticcheck //goland:noinspection GoDeprecation if len(options.Inet6RouteExcludeAddress) > 0 { routeExcludeAddress = append(routeExcludeAddress, options.Inet6RouteExcludeAddress...) } inet4RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool { return it.Addr().Is4() }) inet6RouteExcludeAddress := common.Filter(routeExcludeAddress, func(it netip.Prefix) bool { return it.Addr().Is6() }) tunMTU := options.MTU if tunMTU == 0 { tunMTU = 9000 } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } var err error includeUID := uidToRange(options.IncludeUID) if len(options.IncludeUIDRange) > 0 { includeUID, err = parseRange(includeUID, options.IncludeUIDRange) if err != nil { return nil, E.Cause(err, "parse include_uid_range") } } excludeUID := uidToRange(options.ExcludeUID) if len(options.ExcludeUIDRange) > 0 { excludeUID, err = parseRange(excludeUID, options.ExcludeUIDRange) if err != nil { return nil, E.Cause(err, "parse exclude_uid_range") } } tableIndex := options.IPRoute2TableIndex if tableIndex == 0 { tableIndex = tun.DefaultIPRoute2TableIndex } ruleIndex := options.IPRoute2RuleIndex if ruleIndex == 0 { ruleIndex = tun.DefaultIPRoute2RuleIndex } inputMark := uint32(options.AutoRedirectInputMark) if inputMark == 0 { inputMark = tun.DefaultAutoRedirectInputMark } outputMark := uint32(options.AutoRedirectOutputMark) if outputMark == 0 { outputMark = tun.DefaultAutoRedirectOutputMark } inbound := &Tun{ tag: tag, ctx: ctx, router: router, logger: logger, inboundOptions: options.InboundOptions, tunOptions: tun.Options{ Name: options.InterfaceName, MTU: tunMTU, GSO: options.GSO, Inet4Address: inet4Address, Inet6Address: inet6Address, AutoRoute: options.AutoRoute, IPRoute2TableIndex: tableIndex, IPRoute2RuleIndex: ruleIndex, AutoRedirectInputMark: inputMark, AutoRedirectOutputMark: outputMark, StrictRoute: options.StrictRoute, IncludeInterface: options.IncludeInterface, ExcludeInterface: options.ExcludeInterface, Inet4RouteAddress: inet4RouteAddress, Inet6RouteAddress: inet6RouteAddress, Inet4RouteExcludeAddress: inet4RouteExcludeAddress, Inet6RouteExcludeAddress: inet6RouteExcludeAddress, IncludeUID: includeUID, ExcludeUID: excludeUID, IncludeAndroidUser: options.IncludeAndroidUser, IncludePackage: options.IncludePackage, ExcludePackage: options.ExcludePackage, InterfaceMonitor: router.InterfaceMonitor(), }, endpointIndependentNat: options.EndpointIndependentNat, udpTimeout: int64(udpTimeout.Seconds()), stack: options.Stack, platformInterface: platformInterface, platformOptions: common.PtrValueOrDefault(options.Platform), } if options.AutoRedirect { if !options.AutoRoute { return nil, E.New("`auto_route` is required by `auto_redirect`") } disableNFTables, dErr := strconv.ParseBool(os.Getenv("DISABLE_NFTABLES")) inbound.autoRedirect, err = tun.NewAutoRedirect(tun.AutoRedirectOptions{ TunOptions: &inbound.tunOptions, Context: ctx, Handler: inbound, Logger: logger, NetworkMonitor: router.NetworkMonitor(), InterfaceFinder: router.InterfaceFinder(), TableName: "sing-box", DisableNFTables: dErr == nil && disableNFTables, RouteAddressSet: &inbound.routeAddressSet, RouteExcludeAddressSet: &inbound.routeExcludeAddressSet, }) if err != nil { return nil, E.Cause(err, "initialize auto-redirect") } if runtime.GOOS != "android" { var markMode bool for _, routeAddressSet := range options.RouteAddressSet { ruleSet, loaded := router.RuleSet(routeAddressSet) if !loaded { return nil, E.New("parse route_address_set: rule-set not found: ", routeAddressSet) } ruleSet.IncRef() inbound.routeRuleSet = append(inbound.routeRuleSet, ruleSet) markMode = true } for _, routeExcludeAddressSet := range options.RouteExcludeAddressSet { ruleSet, loaded := router.RuleSet(routeExcludeAddressSet) if !loaded { return nil, E.New("parse route_exclude_address_set: rule-set not found: ", routeExcludeAddressSet) } ruleSet.IncRef() inbound.routeExcludeRuleSet = append(inbound.routeExcludeRuleSet, ruleSet) markMode = true } if markMode { inbound.tunOptions.AutoRedirectMarkMode = true err = router.RegisterAutoRedirectOutputMark(inbound.tunOptions.AutoRedirectOutputMark) if err != nil { return nil, err } } } } return inbound, nil } func uidToRange(uidList option.Listable[uint32]) []ranges.Range[uint32] { return common.Map(uidList, func(uid uint32) ranges.Range[uint32] { return ranges.NewSingle(uid) }) } func parseRange(uidRanges []ranges.Range[uint32], rangeList []string) ([]ranges.Range[uint32], error) { for _, uidRange := range rangeList { if !strings.Contains(uidRange, ":") { return nil, E.New("missing ':' in range: ", uidRange) } subIndex := strings.Index(uidRange, ":") if subIndex == 0 { return nil, E.New("missing range start: ", uidRange) } else if subIndex == len(uidRange)-1 { return nil, E.New("missing range end: ", uidRange) } var start, end uint64 var err error start, err = strconv.ParseUint(uidRange[:subIndex], 0, 32) if err != nil { return nil, E.Cause(err, "parse range start") } end, err = strconv.ParseUint(uidRange[subIndex+1:], 0, 32) if err != nil { return nil, E.Cause(err, "parse range end") } uidRanges = append(uidRanges, ranges.New(uint32(start), uint32(end))) } return uidRanges, nil } func (t *Tun) Type() string { return C.TypeTun } func (t *Tun) Tag() string { return t.tag } func (t *Tun) Start() error { if C.IsAndroid && t.platformInterface == nil { t.tunOptions.BuildAndroidRules(t.router.PackageManager(), t) } if t.tunOptions.Name == "" { t.tunOptions.Name = tun.CalculateInterfaceName("") } var ( tunInterface tun.Tun err error ) monitor := taskmonitor.New(t.logger, C.StartTimeout) monitor.Start("open tun interface") if t.platformInterface != nil { tunInterface, err = t.platformInterface.OpenTun(&t.tunOptions, t.platformOptions) } else { tunInterface, err = tun.New(t.tunOptions) } monitor.Finish() if err != nil { return E.Cause(err, "configure tun interface") } t.logger.Trace("creating stack") t.tunIf = tunInterface var ( forwarderBindInterface bool includeAllNetworks bool ) if t.platformInterface != nil { forwarderBindInterface = true includeAllNetworks = t.platformInterface.IncludeAllNetworks() } tunStack, err := tun.NewStack(t.stack, tun.StackOptions{ Context: t.ctx, Tun: tunInterface, TunOptions: t.tunOptions, EndpointIndependentNat: t.endpointIndependentNat, UDPTimeout: t.udpTimeout, Handler: t, Logger: t.logger, ForwarderBindInterface: forwarderBindInterface, InterfaceFinder: t.router.InterfaceFinder(), IncludeAllNetworks: includeAllNetworks, }) if err != nil { return err } monitor.Start("initiating tun stack") err = tunStack.Start() monitor.Finish() t.tunStack = tunStack if err != nil { return err } t.logger.Info("started at ", t.tunOptions.Name) return nil } func (t *Tun) PostStart() error { monitor := taskmonitor.New(t.logger, C.StartTimeout) if t.autoRedirect != nil { t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet) for _, routeRuleSet := range t.routeRuleSet { ipSets := routeRuleSet.ExtractIPSet() if len(ipSets) == 0 { t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeRuleSet.Name()) } t.routeAddressSet = append(t.routeAddressSet, ipSets...) } t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet) for _, routeExcludeRuleSet := range t.routeExcludeRuleSet { ipSets := routeExcludeRuleSet.ExtractIPSet() if len(ipSets) == 0 { t.logger.Warn("route_address_set: no destination IP CIDR rules found in rule-set: ", routeExcludeRuleSet.Name()) } t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...) } monitor.Start("initialize auto-redirect") err := t.autoRedirect.Start() monitor.Finish() if err != nil { return E.Cause(err, "auto-redirect") } for _, routeRuleSet := range t.routeRuleSet { t.routeRuleSetCallback = append(t.routeRuleSetCallback, routeRuleSet.RegisterCallback(t.updateRouteAddressSet)) routeRuleSet.DecRef() } for _, routeExcludeRuleSet := range t.routeExcludeRuleSet { t.routeExcludeRuleSetCallback = append(t.routeExcludeRuleSetCallback, routeExcludeRuleSet.RegisterCallback(t.updateRouteAddressSet)) routeExcludeRuleSet.DecRef() } t.routeAddressSet = nil t.routeExcludeAddressSet = nil } return nil } func (t *Tun) updateRouteAddressSet(it adapter.RuleSet) { t.routeAddressSet = common.FlatMap(t.routeRuleSet, adapter.RuleSet.ExtractIPSet) t.routeExcludeAddressSet = common.FlatMap(t.routeExcludeRuleSet, adapter.RuleSet.ExtractIPSet) t.autoRedirect.UpdateRouteAddressSet() t.routeAddressSet = nil t.routeExcludeAddressSet = nil } func (t *Tun) Close() error { return common.Close( t.tunStack, t.tunIf, t.autoRedirect, ) } func (t *Tun) NewConnection(ctx context.Context, conn net.Conn, upstreamMetadata M.Metadata) error { ctx = log.ContextWithNewID(ctx) var metadata adapter.InboundContext metadata.Inbound = t.tag metadata.InboundType = C.TypeTun metadata.Source = upstreamMetadata.Source metadata.Destination = upstreamMetadata.Destination metadata.InboundOptions = t.inboundOptions if upstreamMetadata.Protocol != "" { t.logger.InfoContext(ctx, "inbound ", upstreamMetadata.Protocol, " connection from ", metadata.Source) } else { t.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) } t.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) err := t.router.RouteConnection(ctx, conn, metadata) if err != nil { t.NewError(ctx, err) } return nil } func (t *Tun) NewPacketConnection(ctx context.Context, conn N.PacketConn, upstreamMetadata M.Metadata) error { ctx = log.ContextWithNewID(ctx) var metadata adapter.InboundContext metadata.Inbound = t.tag metadata.InboundType = C.TypeTun metadata.Source = upstreamMetadata.Source metadata.Destination = upstreamMetadata.Destination metadata.InboundOptions = t.inboundOptions t.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) t.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) err := t.router.RoutePacketConnection(ctx, conn, metadata) if err != nil { t.NewError(ctx, err) } return nil } func (t *Tun) NewError(ctx context.Context, err error) { NewError(t.logger, ctx, err) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/direct.go
Bcore/windows/resources/sing-box-main/inbound/direct.go
package inbound import ( "context" "net" "net/netip" "time" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/buf" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/udpnat" ) var _ adapter.Inbound = (*Direct)(nil) type Direct struct { myInboundAdapter udpNat *udpnat.Service[netip.AddrPort] overrideOption int overrideDestination M.Socksaddr } func NewDirect(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.DirectInboundOptions) *Direct { options.UDPFragmentDefault = true inbound := &Direct{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeDirect, network: options.Network.Build(), ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, } if options.OverrideAddress != "" && options.OverridePort != 0 { inbound.overrideOption = 1 inbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort) } else if options.OverrideAddress != "" { inbound.overrideOption = 2 inbound.overrideDestination = M.ParseSocksaddrHostPort(options.OverrideAddress, options.OverridePort) } else if options.OverridePort != 0 { inbound.overrideOption = 3 inbound.overrideDestination = M.Socksaddr{Port: options.OverridePort} } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } inbound.udpNat = udpnat.New[netip.AddrPort](int64(udpTimeout.Seconds()), adapter.NewUpstreamContextHandler(inbound.newConnection, inbound.newPacketConnection, inbound)) inbound.connHandler = inbound inbound.packetHandler = inbound inbound.packetUpstream = inbound.udpNat return inbound } func (d *Direct) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { switch d.overrideOption { case 1: metadata.Destination = d.overrideDestination case 2: destination := d.overrideDestination destination.Port = metadata.Destination.Port metadata.Destination = destination case 3: metadata.Destination.Port = d.overrideDestination.Port } d.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) return d.router.RouteConnection(ctx, conn, metadata) } func (d *Direct) NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata adapter.InboundContext) error { switch d.overrideOption { case 1: metadata.Destination = d.overrideDestination case 2: destination := d.overrideDestination destination.Port = metadata.Destination.Port metadata.Destination = destination case 3: metadata.Destination.Port = d.overrideDestination.Port } d.udpNat.NewContextPacket(ctx, metadata.Source.AddrPort(), buffer, adapter.UpstreamMetadata(metadata), func(natConn N.PacketConn) (context.Context, N.PacketWriter) { return adapter.WithContext(log.ContextWithNewID(ctx), &metadata), &udpnat.DirectBackWriter{Source: conn, Nat: natConn} }) return nil } func (d *Direct) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { return d.router.RouteConnection(ctx, conn, metadata) } func (d *Direct) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) d.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) return d.router.RoutePacketConnection(ctx, conn, metadata) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
Begzar/BegzarWindows
https://github.com/Begzar/BegzarWindows/blob/8c374326e7569db68ccfb9e0b5c2daa124d44545/Bcore/windows/resources/sing-box-main/inbound/hysteria2.go
Bcore/windows/resources/sing-box-main/inbound/hysteria2.go
//go:build with_quic package inbound import ( "context" "net" "net/http" "net/http/httputil" "net/url" "time" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/tls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-quic/hysteria" "github.com/sagernet/sing-quic/hysteria2" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/auth" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" ) var _ adapter.Inbound = (*Hysteria2)(nil) type Hysteria2 struct { myInboundAdapter tlsConfig tls.ServerConfig service *hysteria2.Service[int] userNameList []string } func NewHysteria2(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2InboundOptions) (*Hysteria2, error) { options.UDPFragmentDefault = true if options.TLS == nil || !options.TLS.Enabled { return nil, C.ErrTLSRequired } tlsConfig, err := tls.NewServer(ctx, logger, common.PtrValueOrDefault(options.TLS)) if err != nil { return nil, err } var salamanderPassword string if options.Obfs != nil { if options.Obfs.Password == "" { return nil, E.New("missing obfs password") } switch options.Obfs.Type { case hysteria2.ObfsTypeSalamander: salamanderPassword = options.Obfs.Password default: return nil, E.New("unknown obfs type: ", options.Obfs.Type) } } var masqueradeHandler http.Handler if options.Masquerade != "" { masqueradeURL, err := url.Parse(options.Masquerade) if err != nil { return nil, E.Cause(err, "parse masquerade URL") } switch masqueradeURL.Scheme { case "file": masqueradeHandler = http.FileServer(http.Dir(masqueradeURL.Path)) case "http", "https": masqueradeHandler = &httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.SetURL(masqueradeURL) r.Out.Host = r.In.Host }, ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { w.WriteHeader(http.StatusBadGateway) }, } default: return nil, E.New("unknown masquerade URL scheme: ", masqueradeURL.Scheme) } } inbound := &Hysteria2{ myInboundAdapter: myInboundAdapter{ protocol: C.TypeHysteria2, network: []string{N.NetworkUDP}, ctx: ctx, router: router, logger: logger, tag: tag, listenOptions: options.ListenOptions, }, tlsConfig: tlsConfig, } var udpTimeout time.Duration if options.UDPTimeout != 0 { udpTimeout = time.Duration(options.UDPTimeout) } else { udpTimeout = C.UDPTimeout } service, err := hysteria2.NewService[int](hysteria2.ServiceOptions{ Context: ctx, Logger: logger, BrutalDebug: options.BrutalDebug, SendBPS: uint64(options.UpMbps * hysteria.MbpsToBps), ReceiveBPS: uint64(options.DownMbps * hysteria.MbpsToBps), SalamanderPassword: salamanderPassword, TLSConfig: tlsConfig, IgnoreClientBandwidth: options.IgnoreClientBandwidth, UDPTimeout: udpTimeout, Handler: adapter.NewUpstreamHandler(adapter.InboundContext{}, inbound.newConnection, inbound.newPacketConnection, nil), MasqueradeHandler: masqueradeHandler, }) if err != nil { return nil, err } userList := make([]int, 0, len(options.Users)) userNameList := make([]string, 0, len(options.Users)) userPasswordList := make([]string, 0, len(options.Users)) for index, user := range options.Users { userList = append(userList, index) userNameList = append(userNameList, user.Name) userPasswordList = append(userPasswordList, user.Password) } service.UpdateUsers(userList, userPasswordList) inbound.service = service inbound.userNameList = userNameList return inbound, nil } func (h *Hysteria2) newConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) metadata = h.createMetadata(conn, metadata) h.logger.InfoContext(ctx, "inbound connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound connection to ", metadata.Destination) } return h.router.RouteConnection(ctx, conn, metadata) } func (h *Hysteria2) newPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { ctx = log.ContextWithNewID(ctx) metadata = h.createPacketMetadata(conn, metadata) h.logger.InfoContext(ctx, "inbound packet connection from ", metadata.Source) userID, _ := auth.UserFromContext[int](ctx) if userName := h.userNameList[userID]; userName != "" { metadata.User = userName h.logger.InfoContext(ctx, "[", userName, "] inbound packet connection to ", metadata.Destination) } else { h.logger.InfoContext(ctx, "inbound packet connection to ", metadata.Destination) } return h.router.RoutePacketConnection(ctx, conn, metadata) } func (h *Hysteria2) Start() error { if h.tlsConfig != nil { err := h.tlsConfig.Start() if err != nil { return err } } packetConn, err := h.myInboundAdapter.ListenUDP() if err != nil { return err } return h.service.Start(packetConn) } func (h *Hysteria2) Close() error { return common.Close( &h.myInboundAdapter, h.tlsConfig, common.PtrOrNil(h.service), ) }
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/main.go
main.go
package main // This file is just a stub to improve go mod support, allowing less-buggy // commands like `go clean -modcache`. // The actual Temporal CLI is in github.com/RTradeLtd/Temporal/cmd/temporal func main() {}
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/customer/customer.go
customer/customer.go
package customer import ( "encoding/json" "sync" "github.com/RTradeLtd/database/v2/models" "github.com/RTradeLtd/rtfs/v2" ) // Manager is used to handle managing customer objects type Manager struct { um *models.UserManager ipfs rtfs.Manager mutex sync.Mutex } // NewManager is used to instantiate our customer object manager func NewManager(um *models.UserManager, ipfs rtfs.Manager) *Manager { return &Manager{ um: um, ipfs: ipfs, mutex: sync.Mutex{}, } } // GetDeduplicatedStorageSpaceInBytes is used to get the deduplicated storage space used // by this particular hash. It calculates deduplicated storage costs based on previous uploads // the user has made, and does not consider upload from other users. // it is a read-only operation, and returns the storage space that will be used by this upload func (m *Manager) GetDeduplicatedStorageSpaceInBytes(username, hash string) (int, error) { // find the user model user, err := m.um.FindByUserName(username) if err != nil { return 0, err } // construct an empty object var object Object // unmarshal the customer object hash into our typed object if err := m.ipfs.DagGet(user.CustomerObjectHash, &object); err != nil { return 0, err } // if the customer object is empty, then we return full storage space // consumed by the given hash if len(object.UploadedRefs) == 0 && len(object.UploadedRootNodes) == 0 { // get the size of references size, _, err := rtfs.DedupAndCalculatePinSize(hash, m.ipfs) if err != nil { return 0, err } // get datasize of root node stats, err := m.ipfs.Stat(hash) if err != nil { return 0, err } // update size to include data size of root node size = size + int64(stats.DataSize) return int(size), nil } // search through the refs for the given hash refs, err := m.ipfs.Refs(hash, true, true) if err != nil { return 0, err } // refsToCalculate will hold all references that we need // to calculate th estorage size for var ( // will hold all references we need to update+charge for refsToCalculate []string // will hold the total datasize we need to charge size int // will determine if we have updated the root hash rootUpdated bool ) // iterate over all references for the requested hash // and mark whether or not a reference hasn't been seen before for _, ref := range refs { if !object.UploadedRefs[ref] { refsToCalculate = append(refsToCalculate, ref) } } // check if we need to calculate datasize of the roots if !object.UploadedRootNodes[hash] { stats, err := m.ipfs.Stat(hash) if err != nil { return 0, err } // update size size = stats.DataSize // mark as having updated the root rootUpdated = true } // if we have no refs to calculate size for, it means this upload // will consume no additional storage space, thus we can avoid charging them // all but the datasize of the root (if at all) if len(refsToCalculate) == 0 { // if we have updated the used roots of the customer object // this means we need to first update the customer object // stored in database if rootUpdated { // return the new customer object hash and the datasize return size, nil } // since we haven't updated the root, and we have no refs to charge for // we can return a 0 size return 0, nil } // calculate size of all references // also use this to update the refs of customer object for _, ref := range refsToCalculate { // get stats for the reference stats, err := m.ipfs.Stat(ref) if err != nil { return 0, err } // update datasize to include size of reference size = size + stats.DataSize } return size, nil } // Update is used to update a customers deduplicated storage object func (m *Manager) Update(username, hash string) (string, error) { // we use mutex locks so that if a single user account makes two calls to the API in a row // we do not want a confused state of used roots and refs to occur. m.mutex.Lock() defer m.mutex.Unlock() // find the user model user, err := m.um.FindByUserName(username) if err != nil { return "", err } // construct an empty object var object Object // unmarshal the customer object hash into our typed object if err := m.ipfs.DagGet(user.CustomerObjectHash, &object); err != nil { return "", err } // if the customer object is empty, then we need to update it with all references if len(object.UploadedRefs) == 0 && len(object.UploadedRootNodes) == 0 { object = Object{ UploadedRefs: make(map[string]bool), UploadedRootNodes: make(map[string]bool), } // get references for the requested hash refs, err := m.ipfs.Refs(hash, true, true) if err != nil { return "", err } // iterate over all references marking them as being used for _, v := range refs { object.UploadedRefs[v] = true } // mark the root node as being used object.UploadedRootNodes[hash] = true // update the customer object hash stored in our database resp, err := m.put(username, &object) if err != nil { return "", err } return resp, nil } // search through the refs for the given hash refs, err := m.ipfs.Refs(hash, true, true) if err != nil { return "", err } var ( // will determine if we have updated the root hash rootUpdated bool // will determine if we have updated a ref hash refsUpdated bool ) // iterate over all references for the requested hash // and mark whether or not a reference hasn't been seen before for _, ref := range refs { if !object.UploadedRefs[ref] { // if we haven't updated a ref yet, mark as true if !refsUpdated { refsUpdated = true } // mark this particular ref as being seen object.UploadedRefs[ref] = true } } // check if we need to cupdate the roots used if !object.UploadedRootNodes[hash] { // update customer object with root object.UploadedRootNodes[hash] = true // mark as having updated the root rootUpdated = true } // if we have no refs to calculate size for, it means this upload // will consume no additional storage space, thus we can avoid charging them // all but the datasize of the root (if at all) if !refsUpdated { // if we have updated the used roots of the customer object // this means we need to first update the customer object // stored in database if rootUpdated { resp, err := m.put(username, &object) if err != nil { return "", err } // return the new customer object hash and the datasize return resp, nil } // since we haven't updated the root, nor a reference // simply return return "", nil } // store new customer object in ipfs // update database, and return hash of new object resp, err := m.put(username, &object) if err != nil { return "", err } return resp, nil } // put is a wrapper for commonly used functionality. // it is responsible for putting the object to ipfs, and updating // the associated usermodel in database func (m *Manager) put(username string, obj *Object) (string, error) { marshaled, err := json.Marshal(obj) if err != nil { return "", err } resp, err := m.ipfs.DagPut(marshaled, "json", "cbor") if err != nil { return "", err } if err := m.ipfs.Pin(resp); err != nil { return "", err } if err := m.um.UpdateCustomerObjectHash(username, resp); err != nil { return "", err } return resp, nil }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/customer/customer_test.go
customer/customer_test.go
package customer import ( "encoding/json" "testing" "time" "github.com/RTradeLtd/config/v2" "github.com/RTradeLtd/database/v2" "github.com/RTradeLtd/database/v2/models" "github.com/RTradeLtd/rtfs/v2" ) var ( // actual zdpuAnUGSDoNQoHQ2jpjhPePHEvg26mYLsAAGxr4jkzCWUpde emptyObjHash = "bafyreia6oda253w5hnbg4tjgcyid2o2itnghc2mixgcqnukj4ripnm4ise" testHash = "QmS4ustL54uo8FzR9455qaxZwuMiUhyvMcX9Ba8nUH4uVv" testObjHash = "bafyreiesk5qclq2ct4zcycmtfl2fbcosjewek3cm36ppytqqq346w6x5t4" ) func Test_Customer_Empty_Object(t *testing.T) { cfg, err := config.LoadConfig("../testenv/config.json") if err != nil { t.Fatal(err) } db, err := loadDatabase(cfg) if err != nil { t.Fatal(err) } ipfs, err := rtfs.NewManager( cfg.IPFS.APIConnection.Host+":"+cfg.IPFS.APIConnection.Port, "", 5*time.Minute, ) if err != nil { t.Fatal(err) } obj := Object{ UploadedRefs: make(map[string]bool), UploadedRootNodes: make(map[string]bool), } marshaled, err := json.Marshal(&obj) if err != nil { t.Fatal(err) } resp, err := ipfs.DagPut(marshaled, "json", "cbor") if err != nil { t.Fatal(err) } if resp != emptyObjHash { t.Fatal("failed to get correct empty object hash") } manager := NewManager(models.NewUserManager(db.DB), ipfs) // defer updating the customer object hash // to the default for easy future testing defer func() { if err := manager.um.UpdateCustomerObjectHash("testuser", emptyObjHash); err != nil { t.Fatal(err) } }() size, err := manager.GetDeduplicatedStorageSpaceInBytes("testuser", testHash) if err != nil { t.Fatal(err) } if size != 6171 { t.Fatal("failed to get size for empty customer object check") } hash, err := manager.Update("testuser", testHash) if err != nil { t.Fatal(err) } if hash != testObjHash { t.Fatal("failed to get correct object hash") } user, err := manager.um.FindByUserName("testuser") if err != nil { t.Fatal(err) } if user.CustomerObjectHash != testObjHash { t.Fatal("failed to set correct customer object hash") } // now test size calculation for the same test hash // this should result in a size of 0 being returned size, err = manager.GetDeduplicatedStorageSpaceInBytes("testuser", testHash) if err != nil { t.Fatal(err) } if size != 0 { t.Fatal("failed to get size for empty customer object check") } hash, err = manager.Update("testuser", testHash) if err != nil { t.Fatal(err) } if hash != "" { t.Fatal("hash should be empty") } // create a duplicated linked hash unixFSObject, err := ipfs.NewObject("") if err != nil { t.Fatal(err) } newHash, err := ipfs.PatchLink(testHash, "hello", unixFSObject, true) if err != nil { t.Fatal(err) } if newHash != "QmRYBsa1UiDXfdozyDhbzXhj7PivyjCsBJybYNQ5bBbTBg" { t.Fatal("failed to create new hash") } size, err = manager.GetDeduplicatedStorageSpaceInBytes("testuser", newHash) if err != nil { t.Fatal(err) } if size != 2 { t.Fatal("failed to calculate correct size") } newObjHash, err := manager.Update("testuser", newHash) if err != nil { t.Fatal(err) } if newObjHash != "bafyreibcksmdzfandtmo6xhresbkcmhqsswubxmokqgc3t6jbrpx7q7nce" { t.Fatal("failed to properly construct new object hash") } // now repeat the same test ensuring we get a 0 for size used // since we have already stored this hash size, err = manager.GetDeduplicatedStorageSpaceInBytes("testuser", newHash) if err != nil { t.Fatal(err) } if size != 0 { t.Fatal("failed to calculate correct size") } newObjHash, err = manager.Update("testuser", newHash) if err != nil { t.Fatal(err) } if newObjHash != "" { t.Fatal("failed to properly construct new object hash") } } func loadDatabase(cfg *config.TemporalConfig) (*database.Manager, error) { return database.New(cfg, database.Options{SSLModeDisable: true}) }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/customer/types.go
customer/types.go
package customer // Object represents a single customer type Object struct { // UploadedRefs is a map used to check whether or not a particular link ref has been uploaded // the only time this value is populated is when an ipld objecct (say a folder) is uploaded, all // the links of the folder will fill this map UploadedRefs map[string]bool `json:"uploaded_nodes"` // UploadedRootNodes is a map used to check whether or not a particular entire root node has been uploaded. // each upload will always count as an uploaded root node however only ipld objects that contain links will also go to uploaded refs UploadedRootNodes map[string]bool `json:"uploaded_root_nodes"` }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/customer/doc.go
customer/doc.go
// Package customer is responsible for constructing customer upload objects to handle deduplicated storage billing package customer
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/rtfscluster/doc.go
rtfscluster/doc.go
// Package rtfscluster provides utility functions for interacting with IPFS // cluster APIs package rtfscluster
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/rtfscluster/rtfs_cluster_test.go
rtfscluster/rtfs_cluster_test.go
package rtfscluster_test import ( "context" "testing" "github.com/RTradeLtd/Temporal/rtfscluster" gocid "github.com/ipfs/go-cid" ) const ( testPIN = "QmS4ustL54uo8FzR9455qaxZwuMiUhyvMcX9Ba8nUH4uVv" // ip address of our first ipfs and ipfs cluster node as per our makefile nodeOneAPIAddr = "127.0.0.1" // this is the port of the IPFS Cluster API nodePort = "9094" ) func TestInitialize(t *testing.T) { cm, err := rtfscluster.Initialize(context.Background(), nodeOneAPIAddr, nodePort) if err != nil { t.Fatal(err) } id, err := cm.Client.ID(context.Background()) if err != nil { t.Fatal(err) } if id.Version == "" { t.Fatal("version is empty string when it shouldn't be") } } func TestInitialize_Failure(t *testing.T) { if _, err := rtfscluster.Initialize(context.Background(), "10.255.255.255", "9094"); err == nil { t.Fatal("expected error") } } func TestDecodeHashString(t *testing.T) { cm, err := rtfscluster.Initialize(context.Background(), nodeOneAPIAddr, nodePort) if err != nil { t.Fatal(err) } type args struct { hash string } tests := []struct { name string args args wantErr bool }{ {"Success", args{testPIN}, false}, {"Failure", args{"notahash"}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if _, err := cm.DecodeHashString(tt.args.hash); (err != nil) != tt.wantErr { t.Fatalf("DecodeHashString() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestClusterPin(t *testing.T) { cm, err := rtfscluster.Initialize(context.Background(), nodeOneAPIAddr, nodePort) if err != nil { t.Fatal(err) } decoded, err := cm.DecodeHashString(testPIN) if err != nil { t.Fatal(err) } type args struct { cid gocid.Cid } tests := []struct { name string args args wantErr bool }{ {"Success", args{decoded}, false}, {"Failure", args{gocid.Cid{}}, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := cm.Pin(context.Background(), tt.args.cid); (err != nil) != tt.wantErr { t.Fatalf("Pin() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestListPeers(t *testing.T) { cm, err := rtfscluster.Initialize(context.Background(), nodeOneAPIAddr, nodePort) if err != nil { t.Fatal(err) } peers, err := cm.ListPeers(context.Background()) if err != nil { t.Fatal(err) } if len(peers) == 0 { t.Fatal("no pers found") } }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/rtfscluster/rtfs_cluster.go
rtfscluster/rtfs_cluster.go
package rtfscluster import ( "context" "fmt" gocid "github.com/ipfs/go-cid" "github.com/ipfs/ipfs-cluster/api" "github.com/ipfs/ipfs-cluster/api/rest/client" ) // ClusterManager is a helper interface to interact with the cluster apis type ClusterManager struct { Config *client.Config Client client.Client } // Initialize is used to init, and return a cluster manager object func Initialize(ctx context.Context, hostAddress, hostPort string) (*ClusterManager, error) { cm := ClusterManager{} cm.GenRestAPIConfig() if hostAddress != "" && hostPort != "" { cm.Config.Host = hostAddress cm.Config.Port = hostPort } // modify default config with infrastructure specific settings if err := cm.GenClient(); err != nil { return nil, err } if _, err := cm.ListPeers(ctx); err != nil { return nil, err } return &cm, nil } // GenRestAPIConfig is used to generate the api cfg // needed to interact with the cluster func (cm *ClusterManager) GenRestAPIConfig() { cm.Config = &client.Config{} } // GenClient is used to generate a client to interact with the cluster func (cm *ClusterManager) GenClient() error { cl, err := client.NewDefaultClient(cm.Config) if err != nil { return err } cm.Client = cl return nil } // ListPeers is used to list the known cluster peers func (cm *ClusterManager) ListPeers(ctx context.Context) ([]*api.ID, error) { peers, err := cm.Client.Peers(ctx) if err != nil { return nil, err } return peers, nil } // DecodeHashString is used to take a hash string, and turn it into a CID func (cm *ClusterManager) DecodeHashString(cidString string) (gocid.Cid, error) { cid, err := gocid.Decode(cidString) if err != nil { return gocid.Cid{}, err } return cid, nil } // Pin is used to add a pin to the cluster func (cm *ClusterManager) Pin(ctx context.Context, cid gocid.Cid) error { _, err := cm.Client.Pin(ctx, cid, api.PinOptions{ReplicationFactorMax: -1, ReplicationFactorMin: -1}) if err != nil { return err } status, err := cm.Client.Status(ctx, cid, true) if err != nil { fmt.Println("error pinning hash to cluster") return err } fmt.Println("status") fmt.Println(status) return nil }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/cmd/temporal/main_test.go
cmd/temporal/main_test.go
package main import ( "context" "testing" "time" "github.com/RTradeLtd/config/v2" ) func init() { var t = true dbNoSSL = &t dbMigrate = &t devMode = &t debug = &t var blank string configPath = &blank } func TestAPI(t *testing.T) { cfg, err := config.LoadConfig("../../testenv/config.json") if err != nil { t.Fatal(err) } type args struct { port string listenAddress string certFilePath string keyFilePath string logDir string } tests := []struct { name string args args }{ {"NoTLS-NoPort-NoLogDir", args{"", "127.0.0.1", "", "", ""}}, {"NoTLS-WithPort-WithLogDir", args{"6768", "127.0.0.1", "", "", "./tmp/"}}, {"TLS-WithPort-WithLogDir", args{"6769", "127.0.0.1", "../../testenv/certs/api.cert", "../../testenv/certs/api.key", "./tmp/"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // set up call args apiPort = &tt.args.port flags := map[string]string{ "listenAddress": tt.args.listenAddress, "certFilePath": tt.args.certFilePath, "keyFilePath": tt.args.keyFilePath, } cfg.LogDir = tt.args.logDir // setup global context ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) commands["api"].Action(*cfg, flags) cancel() }) } } // TestQueueIPFS is used to test IPFS queues func TestQueuesIPFS(t *testing.T) { cfg, err := config.LoadConfig("../../testenv/config.json") if err != nil { t.Fatal(err) } type args struct { parentCmd string childCmd string logDir string } tests := []struct { name string args args }{ {"IPNSEntry-NoLogDir", args{"ipfs", "ipns-entry", ""}}, {"IPNSEntry-LogDir", args{"ipfs", "ipns-entry", "./tmp/"}}, {"IPFSPin-NoLogDir", args{"ipfs", "pin", ""}}, {"IPFSPin-LogDir", args{"ipfs", "pin", "./tmp/"}}, {"IPFSKey-NoLogDir", args{"ipfs", "key-creation", ""}}, {"IPFSKey-LogDir", args{"ipfs", "key-creation", "./tmp/"}}, {"IPFSCluster-NoLogDir", args{"ipfs", "cluster", ""}}, {"IPFSCluster-LogDir", args{"ipfs", "cluster", "./tmp/"}}, } queueCmds := commands["queue"] for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cfg.LogDir = tt.args.logDir ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) defer cancel() queueCmds.Children[tt.args.parentCmd].Children[tt.args.childCmd].Action(*cfg, nil) }) } } func TestQueuesEmailSend(t *testing.T) { cfg, err := config.LoadConfig("../../testenv/config.json") if err != nil { t.Fatal(err) } type args struct { logDir string } tests := []struct { name string args args }{ {"NoLogDir", args{""}}, {"LogDir", args{"./tmp"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cfg.LogDir = tt.args.logDir ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) defer cancel() commands["queue"].Children["email-send"].Action(*cfg, nil) }) } } func TestMigrations(t *testing.T) { cfg, err := config.LoadConfig("../../testenv/config.json") if err != nil { t.Fatal(err) } // this wont work with our test environment as the psql server doesn't have ssl //commands["migrate"].Action(*cfg, nil) commands["migrate"].Action(*cfg, nil) } func TestInit(t *testing.T) { *configPath = "tmp/new_config.json" commands["init"].Action(config.TemporalConfig{}, nil) } func TestAdmin(t *testing.T) { cfg, err := config.LoadConfig("../../testenv/config.json") if err != nil { t.Fatal(err) } flags := map[string]string{ "dbAdmin": "testuser", } commands["admin"].Action(*cfg, flags) } func TestUser(t *testing.T) { cfg, err := config.LoadConfig("../../testenv/config.json") if err != nil { t.Fatal(err) } flags := map[string]string{ "user": "myuser", "pass": "mypass", "email": "myuser+test@example.org", } commands["user"].Action(*cfg, flags) }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/cmd/temporal/doc.go
cmd/temporal/doc.go
/* Temporal is the command-line interface for Temporal. Documentation is available via `temporal help`. */ package main
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/cmd/temporal/main.go
cmd/temporal/main.go
package main import ( "context" "flag" "fmt" "log" "os" "os/signal" "path/filepath" "sync" "syscall" "go.bobheadxi.dev/zapx/zapx" "go.uber.org/zap" v2 "github.com/RTradeLtd/Temporal/api/v2" clients "github.com/RTradeLtd/Temporal/grpc-clients" "github.com/RTradeLtd/Temporal/queue" "github.com/RTradeLtd/cmd/v2" "github.com/RTradeLtd/config/v2" "github.com/RTradeLtd/database/v2" "github.com/RTradeLtd/database/v2/models" pbLens "github.com/RTradeLtd/grpc/lensv2" pbOrch "github.com/RTradeLtd/grpc/nexus" pbSigner "github.com/RTradeLtd/grpc/pay" "github.com/RTradeLtd/kaas/v2" pbBchWallet "github.com/gcash/bchwallet/rpc/walletrpc" "github.com/jinzhu/gorm" ) // Version denotes the tag of this build var Version string const ( closeMessage = "press CTRL+C to stop processing and close queue resources" defaultLogPath = "/var/log/temporal/" ) // globals var ( ctx context.Context cancel context.CancelFunc orch pbOrch.ServiceClient lens pbLens.LensV2Client signer pbSigner.SignerClient bchWallet pbBchWallet.WalletServiceClient ) // command-line flags var ( devMode *bool debug *bool configPath *string dbNoSSL *bool dbMigrate *bool apiPort *string ) func baseFlagSet() *flag.FlagSet { var f = flag.NewFlagSet("", flag.ExitOnError) // basic flags devMode = f.Bool("dev", false, "toggle dev mode") debug = f.Bool("debug", false, "toggle debug mode") configPath = f.String("config", os.Getenv("CONFIG_DAG"), "path to Temporal configuration") // db configuration dbNoSSL = f.Bool("db.no_ssl", false, "toggle SSL connection with database") dbMigrate = f.Bool("db.migrate", false, "toggle whether a database migration should occur") // api configuration apiPort = f.String("api.port", "6767", "set port to expose API on") return f } func logPath(base, file string) (logPath string) { if base == "" { logPath = filepath.Join(base, file) } else { logPath = filepath.Join(base, file) } return } func newDB(cfg config.TemporalConfig) (*gorm.DB, error) { var ( dbm *database.Manager err error ) //dbm, err = database.New(&cfg, database.Options{SSLModeDisable: noSSL}) dbm, err = database.New(&cfg, database.Options{}) if err != nil { log.Println( "WARNING: secure db connection failed, attempting fallback to insecure connection", ) dbm, err = database.New(&cfg, database.Options{SSLModeDisable: true}) if err != nil { log.Println( "ERROR: insecure db connection failed, exiting", ) return nil, err } } return dbm.DB, nil } func initClients(l *zap.SugaredLogger, cfg *config.TemporalConfig) (closers []func()) { closers = make([]func(), 0) if lens == nil { client, err := clients.NewLensClient(cfg.Services) if err != nil { l.Fatal(err) } closers = append(closers, client.Close) lens = client } if orch == nil { client, err := clients.NewOcrhestratorClient(cfg.Nexus) if err != nil { l.Fatal(err) } closers = append(closers, client.Close) orch = client } if signer == nil { client, err := clients.NewSignerClient(cfg) if err != nil { l.Fatal(err) } closers = append(closers, client.Close) signer = client } if bchWallet == nil { client, err := clients.NewBchWalletClient(cfg.Services) if err != nil { l.Fatal(err) } closers = append(closers, client.Close) bchWallet = client } return } var commands = map[string]cmd.Cmd{ "api": { Blurb: "start Temporal api server", Description: "Start the API service used to interact with Temporal. Run with DEBUG=true to enable debug messages.", Action: func(cfg config.TemporalConfig, args map[string]string) { logger, err := zapx.New(logPath(cfg.LogDir, "api_service.log"), *devMode) if err != nil { fmt.Println("failed to start logger ", err) os.Exit(1) } l := logger.Sugar().With("version", args["version"]) // init clients and clean up if necessary var closers = initClients(l, &cfg) if closers != nil { defer func() { for _, c := range closers { c() } }() } clients := v2.Clients{ Lens: lens, Orch: orch, Signer: signer, BchWallet: bchWallet, } // init api service service, err := v2.Initialize( ctx, &cfg, args["version"], v2.Options{DebugLogging: *debug, DevMode: *devMode}, clients, l, ) if err != nil { l.Fatal(err) } // set up clean interrupt quitChannel := make(chan os.Signal) signal.Notify(quitChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) go func() { fmt.Println(closeMessage) <-quitChannel cancel() service.Close() }() // go! var addr = fmt.Sprintf("%s:%s", args["listenAddress"], *apiPort) var ( cert string key string ) if args["certFilePath"] == "" || args["keyFilePath"] == "" { fmt.Println("TLS config incomplete - starting API service without TLS...") err = service.ListenAndServe(ctx, addr, nil) } else { if cert, err = filepath.Abs(args["certFilePath"]); err != nil { fmt.Println("certFilePath:", err) os.Exit(1) } if key, err = filepath.Abs(args["keyFilePath"]); err != nil { fmt.Println("keyFilePath:", err) os.Exit(1) } fmt.Println("Starting API service with TLS...") err = service.ListenAndServe(ctx, addr, &v2.TLSConfig{ CertFile: cert, KeyFile: key, }) } if err != nil { fmt.Printf("API service execution failed: %s\n", err.Error()) fmt.Println("Refer to the logs for more details") os.Exit(1) } }, }, "queue": { Blurb: "execute commands for various queues", Description: "Interact with Temporal's various queue APIs", ChildRequired: true, Children: map[string]cmd.Cmd{ "ipfs": { Blurb: "IPFS queue sub commands", Description: "Used to launch the various queues that interact with IPFS", ChildRequired: true, Children: map[string]cmd.Cmd{ "ipns-entry": { Blurb: "IPNS entry creation queue", Description: "Listens to requests to create IPNS records", Action: func(cfg config.TemporalConfig, args map[string]string) { logger, err := zapx.New(logPath(cfg.LogDir, "ipns_consumer.log"), *devMode) if err != nil { fmt.Println("failed to start logger ", err) os.Exit(1) } l := logger.Named("ipns_consumer").Sugar() db, err := newDB(cfg) if err != nil { fmt.Println("failed to start db", err) os.Exit(1) } quitChannel := make(chan os.Signal) signal.Notify(quitChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) waitGroup := &sync.WaitGroup{} go func() { fmt.Println(closeMessage) <-quitChannel cancel() }() for { qm, err := queue.New(queue.IpnsEntryQueue, cfg.RabbitMQ.URL, false, *devMode, &cfg, l) if err != nil { fmt.Println("failed to start queue", err) os.Exit(1) } waitGroup.Add(1) err = qm.ConsumeMessages(ctx, waitGroup, db, &cfg) if err != nil && err.Error() != queue.ErrReconnect { fmt.Println("failed to consume messages", err) os.Exit(1) } else if err != nil && err.Error() == queue.ErrReconnect { continue } // this will only be true if we had a graceful exit to the queue process, aka CTRL+C if err == nil { break } } waitGroup.Wait() }, }, "pin": { Blurb: "Pin addition queue", Description: "Listens to pin requests", Action: func(cfg config.TemporalConfig, args map[string]string) { logger, err := zapx.New(logPath(cfg.LogDir, "pin_consumer.log"), *devMode) if err != nil { fmt.Println("failed to start logger ", err) os.Exit(1) } l := logger.Named("pin_consumer").Sugar() db, err := newDB(cfg) if err != nil { fmt.Println("failed to start db", err) os.Exit(1) } quitChannel := make(chan os.Signal) signal.Notify(quitChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) waitGroup := &sync.WaitGroup{} go func() { fmt.Println(closeMessage) <-quitChannel cancel() }() for { qm, err := queue.New(queue.IpfsPinQueue, cfg.RabbitMQ.URL, false, *devMode, &cfg, l) if err != nil { fmt.Println("failed to start queue", err) os.Exit(1) } waitGroup.Add(1) err = qm.ConsumeMessages(ctx, waitGroup, db, &cfg) if err != nil && err.Error() != queue.ErrReconnect { fmt.Println("failed to consume messages", err) os.Exit(1) } else if err != nil && err.Error() == queue.ErrReconnect { continue } // this will only be true if we had a graceful exit to the queue process, aka CTRL+C if err == nil { break } } waitGroup.Wait() }, }, "key-creation": { Blurb: "Key creation queue", Description: fmt.Sprintf("Listen to key creation requests.\nMessages to this queue are broadcasted to all nodes"), Action: func(cfg config.TemporalConfig, args map[string]string) { logger, err := zapx.New(logPath(cfg.LogDir, "key_consumer.log"), *devMode) if err != nil { fmt.Println("failed to start logger ", err) os.Exit(1) } l := logger.Named("key_consumer").Sugar() db, err := newDB(cfg) if err != nil { fmt.Println("failed to start db", err) os.Exit(1) } quitChannel := make(chan os.Signal) signal.Notify(quitChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) waitGroup := &sync.WaitGroup{} go func() { fmt.Println(closeMessage) <-quitChannel cancel() }() for { qm, err := queue.New(queue.IpfsKeyCreationQueue, cfg.RabbitMQ.URL, false, *devMode, &cfg, l) if err != nil { fmt.Println("failed to start queue", err) os.Exit(1) } waitGroup.Add(1) err = qm.ConsumeMessages(ctx, waitGroup, db, &cfg) if err != nil && err.Error() != queue.ErrReconnect { fmt.Println("failed to consume messages", err) os.Exit(1) } else if err != nil && err.Error() == queue.ErrReconnect { continue } // this will only be true if we had a graceful exit to the queue process, aka CTRL+C if err == nil { break } } waitGroup.Wait() }, }, "cluster": { Blurb: "Cluster pin queue", Description: "Listens to requests to pin content to the cluster", Action: func(cfg config.TemporalConfig, args map[string]string) { logger, err := zapx.New(logPath(cfg.LogDir, "cluster_pin_consumer.log"), *devMode) if err != nil { fmt.Println("failed to start logger ", err) os.Exit(1) } l := logger.Named("cluster_pin_consumer").Sugar() db, err := newDB(cfg) if err != nil { fmt.Println("failed to start db", err) os.Exit(1) } quitChannel := make(chan os.Signal) signal.Notify(quitChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) waitGroup := &sync.WaitGroup{} go func() { fmt.Println(closeMessage) <-quitChannel cancel() }() for { qm, err := queue.New(queue.IpfsClusterPinQueue, cfg.RabbitMQ.URL, false, *devMode, &cfg, l) if err != nil { fmt.Println("failed to start queue", err) os.Exit(1) } waitGroup.Add(1) err = qm.ConsumeMessages(ctx, waitGroup, db, &cfg) if err != nil && err.Error() != queue.ErrReconnect { fmt.Println("failed to consume messages", err) os.Exit(1) } else if err != nil && err.Error() == queue.ErrReconnect { continue } // this will only be true if we had a graceful exit to the queue process, aka CTRL+C if err == nil { break } } waitGroup.Wait() }, }, }, }, "email-send": { Blurb: "Email send queue", Description: "Listens to requests to send emails", Action: func(cfg config.TemporalConfig, args map[string]string) { logger, err := zapx.New(logPath(cfg.LogDir, "email_consumer.log"), *devMode) if err != nil { fmt.Println("failed to start logger ", err) os.Exit(1) } l := logger.Named("email_consumer").Sugar() db, err := newDB(cfg) if err != nil { fmt.Println("failed to start db", err) os.Exit(1) } quitChannel := make(chan os.Signal) signal.Notify(quitChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) waitGroup := &sync.WaitGroup{} go func() { fmt.Println(closeMessage) <-quitChannel cancel() }() for { qm, err := queue.New(queue.EmailSendQueue, cfg.RabbitMQ.URL, false, *devMode, &cfg, l) if err != nil { fmt.Println("failed to start queue", err) os.Exit(1) } waitGroup.Add(1) err = qm.ConsumeMessages(ctx, waitGroup, db, &cfg) if err != nil && err.Error() != queue.ErrReconnect { fmt.Println("failed to consume messages", err) os.Exit(1) } else if err != nil && err.Error() == queue.ErrReconnect { continue } // this will only be true if we had a graceful exit to the queue process, aka CTRL+C if err == nil { break } } waitGroup.Wait() }, }, }, }, "krab": { Blurb: "runs the krab service", Description: "Runs the krab grpc server, allowing for secure private key management", Action: func(cfg config.TemporalConfig, args map[string]string) { if err := kaas.NewServer(cfg.Services.Krab.URL, "tcp", &cfg); err != nil { fmt.Println("failed to start krab server", err) os.Exit(1) } }, }, "init": { PreRun: true, Blurb: "initialize blank Temporal configuration", Description: "Initializes a blank Temporal configuration template at path provided by the '-config' flag", Action: func(cfg config.TemporalConfig, args map[string]string) { println("generating config at", *configPath) if err := config.GenerateConfig(*configPath); err != nil { fmt.Println("failed to generate default config template", err) os.Exit(1) } }, }, "user": { Hidden: true, Blurb: "create a user", Description: "Create a Temporal user. Provide args as username, password, email. Do not use in production.", Args: []string{"user", "pass", "email"}, Action: func(cfg config.TemporalConfig, args map[string]string) { fmt.Printf("creating user '%s' (%s)...\n", args["user"], args["email"]) d, err := database.New(&cfg, database.Options{ SSLModeDisable: *dbNoSSL, RunMigrations: *dbMigrate, }) if err != nil { fmt.Println("failed to initialize database connection", err) os.Exit(1) } // create user account if _, err := models.NewUserManager(d.DB).NewUserAccount( args["user"], args["pass"], args["email"], ); err != nil { fmt.Println("failed to create user account", err) os.Exit(1) } // update tier if err := models.NewUsageManager(d.DB).UpdateTier(args["user"], models.Free); err != nil { fmt.Println("failed to update user account tier", err) os.Exit(1) } // add credits if _, err := models.NewUserManager(d.DB).AddCredits(args["user"], 99999999); err != nil { fmt.Println("failed to grant credits to user account", err) os.Exit(1) } // generate email activation token userModel, err := models.NewUserManager(d.DB).GenerateEmailVerificationToken(args["user"]) if err != nil { fmt.Println("failed to generate email verification token", err) os.Exit(1) } // activate email if _, err := models.NewUserManager(d.DB).ValidateEmailVerificationToken(args["user"], userModel.EmailVerificationToken); err != nil { fmt.Println("failed to activate email", err) os.Exit(1) } }, }, "admin": { Hidden: true, Blurb: "assign user as an admin", Description: "Assign an existing Temporal user as an administrator.", Args: []string{"dbAdmin"}, Action: func(cfg config.TemporalConfig, args map[string]string) { if args["dbAdmin"] == "" { fmt.Println("dbAdmin flag not provided") os.Exit(1) } d, err := database.New(&cfg, database.Options{ SSLModeDisable: *dbNoSSL, RunMigrations: *dbMigrate, }) if err != nil { fmt.Println("failed to initialize database", err) os.Exit(1) } found, err := models.NewUserManager(d.DB).ToggleAdmin(args["dbAdmin"]) if err != nil { fmt.Println("failed to tag user as admin", err) os.Exit(1) } if !found { fmt.Println("failed to find user", err) os.Exit(1) } }, }, "migrate": { Blurb: "run database migrations", Description: "Runs our initial database migrations, creating missing tables, etc. Not affected by --db.migrate", Action: func(cfg config.TemporalConfig, args map[string]string) { if _, err := database.New(&cfg, database.Options{ SSLModeDisable: *dbNoSSL, RunMigrations: true, }); err != nil { fmt.Println("failed to perform secure migration", err) os.Exit(1) } }, }, } func main() { if Version == "" { Version = "latest" } // initialize global context ctx, cancel = context.WithCancel(context.Background()) // create app temporal := cmd.New(commands, cmd.Config{ Name: "Temporal", ExecName: "temporal", Version: Version, Desc: "Temporal is an easy-to-use interface into distributed and decentralized storage technologies for personal and enterprise use cases.", Options: baseFlagSet(), }) // run no-config commands, exit if command was run if exit := temporal.PreRun(nil, os.Args[1:]); exit == cmd.CodeOK { os.Exit(0) } // load config tCfg, err := config.LoadConfig(*configPath) if err != nil { println("failed to load config at", *configPath) os.Exit(1) } // load arguments flags := map[string]string{ "certFilePath": tCfg.API.Connection.Certificates.CertPath, "keyFilePath": tCfg.API.Connection.Certificates.KeyPath, "listenAddress": tCfg.API.Connection.ListenAddress, "dbPass": tCfg.Database.Password, "dbURL": tCfg.Database.URL, "dbUser": tCfg.Database.Username, "version": Version, } // execute os.Exit(temporal.Run(*tCfg, flags, os.Args[1:])) }
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/mocks/lens.mock.go
mocks/lens.mock.go
// Code generated by counterfeiter. DO NOT EDIT. package mocks import ( "context" "sync" "github.com/RTradeLtd/grpc/lensv2" "google.golang.org/grpc" ) type FakeLensV2Client struct { IndexStub func(context.Context, *lensv2.IndexReq, ...grpc.CallOption) (*lensv2.IndexResp, error) indexMutex sync.RWMutex indexArgsForCall []struct { arg1 context.Context arg2 *lensv2.IndexReq arg3 []grpc.CallOption } indexReturns struct { result1 *lensv2.IndexResp result2 error } indexReturnsOnCall map[int]struct { result1 *lensv2.IndexResp result2 error } RemoveStub func(context.Context, *lensv2.RemoveReq, ...grpc.CallOption) (*lensv2.RemoveResp, error) removeMutex sync.RWMutex removeArgsForCall []struct { arg1 context.Context arg2 *lensv2.RemoveReq arg3 []grpc.CallOption } removeReturns struct { result1 *lensv2.RemoveResp result2 error } removeReturnsOnCall map[int]struct { result1 *lensv2.RemoveResp result2 error } SearchStub func(context.Context, *lensv2.SearchReq, ...grpc.CallOption) (*lensv2.SearchResp, error) searchMutex sync.RWMutex searchArgsForCall []struct { arg1 context.Context arg2 *lensv2.SearchReq arg3 []grpc.CallOption } searchReturns struct { result1 *lensv2.SearchResp result2 error } searchReturnsOnCall map[int]struct { result1 *lensv2.SearchResp result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeLensV2Client) Index(arg1 context.Context, arg2 *lensv2.IndexReq, arg3 ...grpc.CallOption) (*lensv2.IndexResp, error) { fake.indexMutex.Lock() ret, specificReturn := fake.indexReturnsOnCall[len(fake.indexArgsForCall)] fake.indexArgsForCall = append(fake.indexArgsForCall, struct { arg1 context.Context arg2 *lensv2.IndexReq arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("Index", []interface{}{arg1, arg2, arg3}) fake.indexMutex.Unlock() if fake.IndexStub != nil { return fake.IndexStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.indexReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeLensV2Client) IndexCallCount() int { fake.indexMutex.RLock() defer fake.indexMutex.RUnlock() return len(fake.indexArgsForCall) } func (fake *FakeLensV2Client) IndexCalls(stub func(context.Context, *lensv2.IndexReq, ...grpc.CallOption) (*lensv2.IndexResp, error)) { fake.indexMutex.Lock() defer fake.indexMutex.Unlock() fake.IndexStub = stub } func (fake *FakeLensV2Client) IndexArgsForCall(i int) (context.Context, *lensv2.IndexReq, []grpc.CallOption) { fake.indexMutex.RLock() defer fake.indexMutex.RUnlock() argsForCall := fake.indexArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeLensV2Client) IndexReturns(result1 *lensv2.IndexResp, result2 error) { fake.indexMutex.Lock() defer fake.indexMutex.Unlock() fake.IndexStub = nil fake.indexReturns = struct { result1 *lensv2.IndexResp result2 error }{result1, result2} } func (fake *FakeLensV2Client) IndexReturnsOnCall(i int, result1 *lensv2.IndexResp, result2 error) { fake.indexMutex.Lock() defer fake.indexMutex.Unlock() fake.IndexStub = nil if fake.indexReturnsOnCall == nil { fake.indexReturnsOnCall = make(map[int]struct { result1 *lensv2.IndexResp result2 error }) } fake.indexReturnsOnCall[i] = struct { result1 *lensv2.IndexResp result2 error }{result1, result2} } func (fake *FakeLensV2Client) Remove(arg1 context.Context, arg2 *lensv2.RemoveReq, arg3 ...grpc.CallOption) (*lensv2.RemoveResp, error) { fake.removeMutex.Lock() ret, specificReturn := fake.removeReturnsOnCall[len(fake.removeArgsForCall)] fake.removeArgsForCall = append(fake.removeArgsForCall, struct { arg1 context.Context arg2 *lensv2.RemoveReq arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("Remove", []interface{}{arg1, arg2, arg3}) fake.removeMutex.Unlock() if fake.RemoveStub != nil { return fake.RemoveStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.removeReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeLensV2Client) RemoveCallCount() int { fake.removeMutex.RLock() defer fake.removeMutex.RUnlock() return len(fake.removeArgsForCall) } func (fake *FakeLensV2Client) RemoveCalls(stub func(context.Context, *lensv2.RemoveReq, ...grpc.CallOption) (*lensv2.RemoveResp, error)) { fake.removeMutex.Lock() defer fake.removeMutex.Unlock() fake.RemoveStub = stub } func (fake *FakeLensV2Client) RemoveArgsForCall(i int) (context.Context, *lensv2.RemoveReq, []grpc.CallOption) { fake.removeMutex.RLock() defer fake.removeMutex.RUnlock() argsForCall := fake.removeArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeLensV2Client) RemoveReturns(result1 *lensv2.RemoveResp, result2 error) { fake.removeMutex.Lock() defer fake.removeMutex.Unlock() fake.RemoveStub = nil fake.removeReturns = struct { result1 *lensv2.RemoveResp result2 error }{result1, result2} } func (fake *FakeLensV2Client) RemoveReturnsOnCall(i int, result1 *lensv2.RemoveResp, result2 error) { fake.removeMutex.Lock() defer fake.removeMutex.Unlock() fake.RemoveStub = nil if fake.removeReturnsOnCall == nil { fake.removeReturnsOnCall = make(map[int]struct { result1 *lensv2.RemoveResp result2 error }) } fake.removeReturnsOnCall[i] = struct { result1 *lensv2.RemoveResp result2 error }{result1, result2} } func (fake *FakeLensV2Client) Search(arg1 context.Context, arg2 *lensv2.SearchReq, arg3 ...grpc.CallOption) (*lensv2.SearchResp, error) { fake.searchMutex.Lock() ret, specificReturn := fake.searchReturnsOnCall[len(fake.searchArgsForCall)] fake.searchArgsForCall = append(fake.searchArgsForCall, struct { arg1 context.Context arg2 *lensv2.SearchReq arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("Search", []interface{}{arg1, arg2, arg3}) fake.searchMutex.Unlock() if fake.SearchStub != nil { return fake.SearchStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.searchReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeLensV2Client) SearchCallCount() int { fake.searchMutex.RLock() defer fake.searchMutex.RUnlock() return len(fake.searchArgsForCall) } func (fake *FakeLensV2Client) SearchCalls(stub func(context.Context, *lensv2.SearchReq, ...grpc.CallOption) (*lensv2.SearchResp, error)) { fake.searchMutex.Lock() defer fake.searchMutex.Unlock() fake.SearchStub = stub } func (fake *FakeLensV2Client) SearchArgsForCall(i int) (context.Context, *lensv2.SearchReq, []grpc.CallOption) { fake.searchMutex.RLock() defer fake.searchMutex.RUnlock() argsForCall := fake.searchArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeLensV2Client) SearchReturns(result1 *lensv2.SearchResp, result2 error) { fake.searchMutex.Lock() defer fake.searchMutex.Unlock() fake.SearchStub = nil fake.searchReturns = struct { result1 *lensv2.SearchResp result2 error }{result1, result2} } func (fake *FakeLensV2Client) SearchReturnsOnCall(i int, result1 *lensv2.SearchResp, result2 error) { fake.searchMutex.Lock() defer fake.searchMutex.Unlock() fake.SearchStub = nil if fake.searchReturnsOnCall == nil { fake.searchReturnsOnCall = make(map[int]struct { result1 *lensv2.SearchResp result2 error }) } fake.searchReturnsOnCall[i] = struct { result1 *lensv2.SearchResp result2 error }{result1, result2} } func (fake *FakeLensV2Client) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.indexMutex.RLock() defer fake.indexMutex.RUnlock() fake.removeMutex.RLock() defer fake.removeMutex.RUnlock() fake.searchMutex.RLock() defer fake.searchMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *FakeLensV2Client) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ lensv2.LensV2Client = new(FakeLensV2Client)
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/mocks/rtfs.mock.go
mocks/rtfs.mock.go
// Code generated by counterfeiter. DO NOT EDIT. package mocks import ( "context" "io" "sync" "time" shell "github.com/RTradeLtd/go-ipfs-api" rtfs "github.com/RTradeLtd/rtfs/v2" ) type FakeManager struct { AddStub func(io.Reader, ...func(*shell.RequestBuilder) error) (string, error) addMutex sync.RWMutex addArgsForCall []struct { arg1 io.Reader arg2 []func(*shell.RequestBuilder) error } addReturns struct { result1 string result2 error } addReturnsOnCall map[int]struct { result1 string result2 error } AddDirStub func(string) (string, error) addDirMutex sync.RWMutex addDirArgsForCall []struct { arg1 string } addDirReturns struct { result1 string result2 error } addDirReturnsOnCall map[int]struct { result1 string result2 error } AppendDataStub func(string, interface{}) (string, error) appendDataMutex sync.RWMutex appendDataArgsForCall []struct { arg1 string arg2 interface{} } appendDataReturns struct { result1 string result2 error } appendDataReturnsOnCall map[int]struct { result1 string result2 error } CatStub func(string) ([]byte, error) catMutex sync.RWMutex catArgsForCall []struct { arg1 string } catReturns struct { result1 []byte result2 error } catReturnsOnCall map[int]struct { result1 []byte result2 error } CheckPinStub func(string) (bool, error) checkPinMutex sync.RWMutex checkPinArgsForCall []struct { arg1 string } checkPinReturns struct { result1 bool result2 error } checkPinReturnsOnCall map[int]struct { result1 bool result2 error } CustomRequestStub func(context.Context, string, string, map[string]string, ...string) (*shell.Response, error) customRequestMutex sync.RWMutex customRequestArgsForCall []struct { arg1 context.Context arg2 string arg3 string arg4 map[string]string arg5 []string } customRequestReturns struct { result1 *shell.Response result2 error } customRequestReturnsOnCall map[int]struct { result1 *shell.Response result2 error } DagGetStub func(string, interface{}) error dagGetMutex sync.RWMutex dagGetArgsForCall []struct { arg1 string arg2 interface{} } dagGetReturns struct { result1 error } dagGetReturnsOnCall map[int]struct { result1 error } DagPutStub func(interface{}, string, string) (string, error) dagPutMutex sync.RWMutex dagPutArgsForCall []struct { arg1 interface{} arg2 string arg3 string } dagPutReturns struct { result1 string result2 error } dagPutReturnsOnCall map[int]struct { result1 string result2 error } GetLogsStub func(context.Context) (shell.Logger, error) getLogsMutex sync.RWMutex getLogsArgsForCall []struct { arg1 context.Context } getLogsReturns struct { result1 shell.Logger result2 error } getLogsReturnsOnCall map[int]struct { result1 shell.Logger result2 error } NewObjectStub func(string) (string, error) newObjectMutex sync.RWMutex newObjectArgsForCall []struct { arg1 string } newObjectReturns struct { result1 string result2 error } newObjectReturnsOnCall map[int]struct { result1 string result2 error } NodeAddressStub func() string nodeAddressMutex sync.RWMutex nodeAddressArgsForCall []struct { } nodeAddressReturns struct { result1 string } nodeAddressReturnsOnCall map[int]struct { result1 string } PatchLinkStub func(string, string, string, bool) (string, error) patchLinkMutex sync.RWMutex patchLinkArgsForCall []struct { arg1 string arg2 string arg3 string arg4 bool } patchLinkReturns struct { result1 string result2 error } patchLinkReturnsOnCall map[int]struct { result1 string result2 error } PinStub func(string) error pinMutex sync.RWMutex pinArgsForCall []struct { arg1 string } pinReturns struct { result1 error } pinReturnsOnCall map[int]struct { result1 error } PinUpdateStub func(string, string) (string, error) pinUpdateMutex sync.RWMutex pinUpdateArgsForCall []struct { arg1 string arg2 string } pinUpdateReturns struct { result1 string result2 error } pinUpdateReturnsOnCall map[int]struct { result1 string result2 error } PubSubPublishStub func(string, string) error pubSubPublishMutex sync.RWMutex pubSubPublishArgsForCall []struct { arg1 string arg2 string } pubSubPublishReturns struct { result1 error } pubSubPublishReturnsOnCall map[int]struct { result1 error } PublishStub func(string, string, time.Duration, time.Duration, bool) (*shell.PublishResponse, error) publishMutex sync.RWMutex publishArgsForCall []struct { arg1 string arg2 string arg3 time.Duration arg4 time.Duration arg5 bool } publishReturns struct { result1 *shell.PublishResponse result2 error } publishReturnsOnCall map[int]struct { result1 *shell.PublishResponse result2 error } RefsStub func(string, bool, bool) ([]string, error) refsMutex sync.RWMutex refsArgsForCall []struct { arg1 string arg2 bool arg3 bool } refsReturns struct { result1 []string result2 error } refsReturnsOnCall map[int]struct { result1 []string result2 error } ResolveStub func(string) (string, error) resolveMutex sync.RWMutex resolveArgsForCall []struct { arg1 string } resolveReturns struct { result1 string result2 error } resolveReturnsOnCall map[int]struct { result1 string result2 error } SetDataStub func(string, interface{}) (string, error) setDataMutex sync.RWMutex setDataArgsForCall []struct { arg1 string arg2 interface{} } setDataReturns struct { result1 string result2 error } setDataReturnsOnCall map[int]struct { result1 string result2 error } StatStub func(string) (*shell.ObjectStats, error) statMutex sync.RWMutex statArgsForCall []struct { arg1 string } statReturns struct { result1 *shell.ObjectStats result2 error } statReturnsOnCall map[int]struct { result1 *shell.ObjectStats result2 error } SwarmConnectStub func(context.Context, ...string) error swarmConnectMutex sync.RWMutex swarmConnectArgsForCall []struct { arg1 context.Context arg2 []string } swarmConnectReturns struct { result1 error } swarmConnectReturnsOnCall map[int]struct { result1 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeManager) Add(arg1 io.Reader, arg2 ...func(*shell.RequestBuilder) error) (string, error) { fake.addMutex.Lock() ret, specificReturn := fake.addReturnsOnCall[len(fake.addArgsForCall)] fake.addArgsForCall = append(fake.addArgsForCall, struct { arg1 io.Reader arg2 []func(*shell.RequestBuilder) error }{arg1, arg2}) fake.recordInvocation("Add", []interface{}{arg1, arg2}) fake.addMutex.Unlock() if fake.AddStub != nil { return fake.AddStub(arg1, arg2...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.addReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) AddCallCount() int { fake.addMutex.RLock() defer fake.addMutex.RUnlock() return len(fake.addArgsForCall) } func (fake *FakeManager) AddCalls(stub func(io.Reader, ...func(*shell.RequestBuilder) error) (string, error)) { fake.addMutex.Lock() defer fake.addMutex.Unlock() fake.AddStub = stub } func (fake *FakeManager) AddArgsForCall(i int) (io.Reader, []func(*shell.RequestBuilder) error) { fake.addMutex.RLock() defer fake.addMutex.RUnlock() argsForCall := fake.addArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeManager) AddReturns(result1 string, result2 error) { fake.addMutex.Lock() defer fake.addMutex.Unlock() fake.AddStub = nil fake.addReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) AddReturnsOnCall(i int, result1 string, result2 error) { fake.addMutex.Lock() defer fake.addMutex.Unlock() fake.AddStub = nil if fake.addReturnsOnCall == nil { fake.addReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.addReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) AddDir(arg1 string) (string, error) { fake.addDirMutex.Lock() ret, specificReturn := fake.addDirReturnsOnCall[len(fake.addDirArgsForCall)] fake.addDirArgsForCall = append(fake.addDirArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("AddDir", []interface{}{arg1}) fake.addDirMutex.Unlock() if fake.AddDirStub != nil { return fake.AddDirStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.addDirReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) AddDirCallCount() int { fake.addDirMutex.RLock() defer fake.addDirMutex.RUnlock() return len(fake.addDirArgsForCall) } func (fake *FakeManager) AddDirCalls(stub func(string) (string, error)) { fake.addDirMutex.Lock() defer fake.addDirMutex.Unlock() fake.AddDirStub = stub } func (fake *FakeManager) AddDirArgsForCall(i int) string { fake.addDirMutex.RLock() defer fake.addDirMutex.RUnlock() argsForCall := fake.addDirArgsForCall[i] return argsForCall.arg1 } func (fake *FakeManager) AddDirReturns(result1 string, result2 error) { fake.addDirMutex.Lock() defer fake.addDirMutex.Unlock() fake.AddDirStub = nil fake.addDirReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) AddDirReturnsOnCall(i int, result1 string, result2 error) { fake.addDirMutex.Lock() defer fake.addDirMutex.Unlock() fake.AddDirStub = nil if fake.addDirReturnsOnCall == nil { fake.addDirReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.addDirReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) AppendData(arg1 string, arg2 interface{}) (string, error) { fake.appendDataMutex.Lock() ret, specificReturn := fake.appendDataReturnsOnCall[len(fake.appendDataArgsForCall)] fake.appendDataArgsForCall = append(fake.appendDataArgsForCall, struct { arg1 string arg2 interface{} }{arg1, arg2}) fake.recordInvocation("AppendData", []interface{}{arg1, arg2}) fake.appendDataMutex.Unlock() if fake.AppendDataStub != nil { return fake.AppendDataStub(arg1, arg2) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.appendDataReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) AppendDataCallCount() int { fake.appendDataMutex.RLock() defer fake.appendDataMutex.RUnlock() return len(fake.appendDataArgsForCall) } func (fake *FakeManager) AppendDataCalls(stub func(string, interface{}) (string, error)) { fake.appendDataMutex.Lock() defer fake.appendDataMutex.Unlock() fake.AppendDataStub = stub } func (fake *FakeManager) AppendDataArgsForCall(i int) (string, interface{}) { fake.appendDataMutex.RLock() defer fake.appendDataMutex.RUnlock() argsForCall := fake.appendDataArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeManager) AppendDataReturns(result1 string, result2 error) { fake.appendDataMutex.Lock() defer fake.appendDataMutex.Unlock() fake.AppendDataStub = nil fake.appendDataReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) AppendDataReturnsOnCall(i int, result1 string, result2 error) { fake.appendDataMutex.Lock() defer fake.appendDataMutex.Unlock() fake.AppendDataStub = nil if fake.appendDataReturnsOnCall == nil { fake.appendDataReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.appendDataReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) Cat(arg1 string) ([]byte, error) { fake.catMutex.Lock() ret, specificReturn := fake.catReturnsOnCall[len(fake.catArgsForCall)] fake.catArgsForCall = append(fake.catArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("Cat", []interface{}{arg1}) fake.catMutex.Unlock() if fake.CatStub != nil { return fake.CatStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.catReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) CatCallCount() int { fake.catMutex.RLock() defer fake.catMutex.RUnlock() return len(fake.catArgsForCall) } func (fake *FakeManager) CatCalls(stub func(string) ([]byte, error)) { fake.catMutex.Lock() defer fake.catMutex.Unlock() fake.CatStub = stub } func (fake *FakeManager) CatArgsForCall(i int) string { fake.catMutex.RLock() defer fake.catMutex.RUnlock() argsForCall := fake.catArgsForCall[i] return argsForCall.arg1 } func (fake *FakeManager) CatReturns(result1 []byte, result2 error) { fake.catMutex.Lock() defer fake.catMutex.Unlock() fake.CatStub = nil fake.catReturns = struct { result1 []byte result2 error }{result1, result2} } func (fake *FakeManager) CatReturnsOnCall(i int, result1 []byte, result2 error) { fake.catMutex.Lock() defer fake.catMutex.Unlock() fake.CatStub = nil if fake.catReturnsOnCall == nil { fake.catReturnsOnCall = make(map[int]struct { result1 []byte result2 error }) } fake.catReturnsOnCall[i] = struct { result1 []byte result2 error }{result1, result2} } func (fake *FakeManager) CheckPin(arg1 string) (bool, error) { fake.checkPinMutex.Lock() ret, specificReturn := fake.checkPinReturnsOnCall[len(fake.checkPinArgsForCall)] fake.checkPinArgsForCall = append(fake.checkPinArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("CheckPin", []interface{}{arg1}) fake.checkPinMutex.Unlock() if fake.CheckPinStub != nil { return fake.CheckPinStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.checkPinReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) CheckPinCallCount() int { fake.checkPinMutex.RLock() defer fake.checkPinMutex.RUnlock() return len(fake.checkPinArgsForCall) } func (fake *FakeManager) CheckPinCalls(stub func(string) (bool, error)) { fake.checkPinMutex.Lock() defer fake.checkPinMutex.Unlock() fake.CheckPinStub = stub } func (fake *FakeManager) CheckPinArgsForCall(i int) string { fake.checkPinMutex.RLock() defer fake.checkPinMutex.RUnlock() argsForCall := fake.checkPinArgsForCall[i] return argsForCall.arg1 } func (fake *FakeManager) CheckPinReturns(result1 bool, result2 error) { fake.checkPinMutex.Lock() defer fake.checkPinMutex.Unlock() fake.CheckPinStub = nil fake.checkPinReturns = struct { result1 bool result2 error }{result1, result2} } func (fake *FakeManager) CheckPinReturnsOnCall(i int, result1 bool, result2 error) { fake.checkPinMutex.Lock() defer fake.checkPinMutex.Unlock() fake.CheckPinStub = nil if fake.checkPinReturnsOnCall == nil { fake.checkPinReturnsOnCall = make(map[int]struct { result1 bool result2 error }) } fake.checkPinReturnsOnCall[i] = struct { result1 bool result2 error }{result1, result2} } func (fake *FakeManager) CustomRequest(arg1 context.Context, arg2 string, arg3 string, arg4 map[string]string, arg5 ...string) (*shell.Response, error) { fake.customRequestMutex.Lock() ret, specificReturn := fake.customRequestReturnsOnCall[len(fake.customRequestArgsForCall)] fake.customRequestArgsForCall = append(fake.customRequestArgsForCall, struct { arg1 context.Context arg2 string arg3 string arg4 map[string]string arg5 []string }{arg1, arg2, arg3, arg4, arg5}) fake.recordInvocation("CustomRequest", []interface{}{arg1, arg2, arg3, arg4, arg5}) fake.customRequestMutex.Unlock() if fake.CustomRequestStub != nil { return fake.CustomRequestStub(arg1, arg2, arg3, arg4, arg5...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.customRequestReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) CustomRequestCallCount() int { fake.customRequestMutex.RLock() defer fake.customRequestMutex.RUnlock() return len(fake.customRequestArgsForCall) } func (fake *FakeManager) CustomRequestCalls(stub func(context.Context, string, string, map[string]string, ...string) (*shell.Response, error)) { fake.customRequestMutex.Lock() defer fake.customRequestMutex.Unlock() fake.CustomRequestStub = stub } func (fake *FakeManager) CustomRequestArgsForCall(i int) (context.Context, string, string, map[string]string, []string) { fake.customRequestMutex.RLock() defer fake.customRequestMutex.RUnlock() argsForCall := fake.customRequestArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4, argsForCall.arg5 } func (fake *FakeManager) CustomRequestReturns(result1 *shell.Response, result2 error) { fake.customRequestMutex.Lock() defer fake.customRequestMutex.Unlock() fake.CustomRequestStub = nil fake.customRequestReturns = struct { result1 *shell.Response result2 error }{result1, result2} } func (fake *FakeManager) CustomRequestReturnsOnCall(i int, result1 *shell.Response, result2 error) { fake.customRequestMutex.Lock() defer fake.customRequestMutex.Unlock() fake.CustomRequestStub = nil if fake.customRequestReturnsOnCall == nil { fake.customRequestReturnsOnCall = make(map[int]struct { result1 *shell.Response result2 error }) } fake.customRequestReturnsOnCall[i] = struct { result1 *shell.Response result2 error }{result1, result2} } func (fake *FakeManager) DagGet(arg1 string, arg2 interface{}) error { fake.dagGetMutex.Lock() ret, specificReturn := fake.dagGetReturnsOnCall[len(fake.dagGetArgsForCall)] fake.dagGetArgsForCall = append(fake.dagGetArgsForCall, struct { arg1 string arg2 interface{} }{arg1, arg2}) fake.recordInvocation("DagGet", []interface{}{arg1, arg2}) fake.dagGetMutex.Unlock() if fake.DagGetStub != nil { return fake.DagGetStub(arg1, arg2) } if specificReturn { return ret.result1 } fakeReturns := fake.dagGetReturns return fakeReturns.result1 } func (fake *FakeManager) DagGetCallCount() int { fake.dagGetMutex.RLock() defer fake.dagGetMutex.RUnlock() return len(fake.dagGetArgsForCall) } func (fake *FakeManager) DagGetCalls(stub func(string, interface{}) error) { fake.dagGetMutex.Lock() defer fake.dagGetMutex.Unlock() fake.DagGetStub = stub } func (fake *FakeManager) DagGetArgsForCall(i int) (string, interface{}) { fake.dagGetMutex.RLock() defer fake.dagGetMutex.RUnlock() argsForCall := fake.dagGetArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeManager) DagGetReturns(result1 error) { fake.dagGetMutex.Lock() defer fake.dagGetMutex.Unlock() fake.DagGetStub = nil fake.dagGetReturns = struct { result1 error }{result1} } func (fake *FakeManager) DagGetReturnsOnCall(i int, result1 error) { fake.dagGetMutex.Lock() defer fake.dagGetMutex.Unlock() fake.DagGetStub = nil if fake.dagGetReturnsOnCall == nil { fake.dagGetReturnsOnCall = make(map[int]struct { result1 error }) } fake.dagGetReturnsOnCall[i] = struct { result1 error }{result1} } func (fake *FakeManager) DagPut(arg1 interface{}, arg2 string, arg3 string) (string, error) { fake.dagPutMutex.Lock() ret, specificReturn := fake.dagPutReturnsOnCall[len(fake.dagPutArgsForCall)] fake.dagPutArgsForCall = append(fake.dagPutArgsForCall, struct { arg1 interface{} arg2 string arg3 string }{arg1, arg2, arg3}) fake.recordInvocation("DagPut", []interface{}{arg1, arg2, arg3}) fake.dagPutMutex.Unlock() if fake.DagPutStub != nil { return fake.DagPutStub(arg1, arg2, arg3) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.dagPutReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) DagPutCallCount() int { fake.dagPutMutex.RLock() defer fake.dagPutMutex.RUnlock() return len(fake.dagPutArgsForCall) } func (fake *FakeManager) DagPutCalls(stub func(interface{}, string, string) (string, error)) { fake.dagPutMutex.Lock() defer fake.dagPutMutex.Unlock() fake.DagPutStub = stub } func (fake *FakeManager) DagPutArgsForCall(i int) (interface{}, string, string) { fake.dagPutMutex.RLock() defer fake.dagPutMutex.RUnlock() argsForCall := fake.dagPutArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeManager) DagPutReturns(result1 string, result2 error) { fake.dagPutMutex.Lock() defer fake.dagPutMutex.Unlock() fake.DagPutStub = nil fake.dagPutReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) DagPutReturnsOnCall(i int, result1 string, result2 error) { fake.dagPutMutex.Lock() defer fake.dagPutMutex.Unlock() fake.DagPutStub = nil if fake.dagPutReturnsOnCall == nil { fake.dagPutReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.dagPutReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) GetLogs(arg1 context.Context) (shell.Logger, error) { fake.getLogsMutex.Lock() ret, specificReturn := fake.getLogsReturnsOnCall[len(fake.getLogsArgsForCall)] fake.getLogsArgsForCall = append(fake.getLogsArgsForCall, struct { arg1 context.Context }{arg1}) fake.recordInvocation("GetLogs", []interface{}{arg1}) fake.getLogsMutex.Unlock() if fake.GetLogsStub != nil { return fake.GetLogsStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.getLogsReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) GetLogsCallCount() int { fake.getLogsMutex.RLock() defer fake.getLogsMutex.RUnlock() return len(fake.getLogsArgsForCall) } func (fake *FakeManager) GetLogsCalls(stub func(context.Context) (shell.Logger, error)) { fake.getLogsMutex.Lock() defer fake.getLogsMutex.Unlock() fake.GetLogsStub = stub } func (fake *FakeManager) GetLogsArgsForCall(i int) context.Context { fake.getLogsMutex.RLock() defer fake.getLogsMutex.RUnlock() argsForCall := fake.getLogsArgsForCall[i] return argsForCall.arg1 } func (fake *FakeManager) GetLogsReturns(result1 shell.Logger, result2 error) { fake.getLogsMutex.Lock() defer fake.getLogsMutex.Unlock() fake.GetLogsStub = nil fake.getLogsReturns = struct { result1 shell.Logger result2 error }{result1, result2} } func (fake *FakeManager) GetLogsReturnsOnCall(i int, result1 shell.Logger, result2 error) { fake.getLogsMutex.Lock() defer fake.getLogsMutex.Unlock() fake.GetLogsStub = nil if fake.getLogsReturnsOnCall == nil { fake.getLogsReturnsOnCall = make(map[int]struct { result1 shell.Logger result2 error }) } fake.getLogsReturnsOnCall[i] = struct { result1 shell.Logger result2 error }{result1, result2} } func (fake *FakeManager) NewObject(arg1 string) (string, error) { fake.newObjectMutex.Lock() ret, specificReturn := fake.newObjectReturnsOnCall[len(fake.newObjectArgsForCall)] fake.newObjectArgsForCall = append(fake.newObjectArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("NewObject", []interface{}{arg1}) fake.newObjectMutex.Unlock() if fake.NewObjectStub != nil { return fake.NewObjectStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.newObjectReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) NewObjectCallCount() int { fake.newObjectMutex.RLock() defer fake.newObjectMutex.RUnlock() return len(fake.newObjectArgsForCall) } func (fake *FakeManager) NewObjectCalls(stub func(string) (string, error)) { fake.newObjectMutex.Lock() defer fake.newObjectMutex.Unlock() fake.NewObjectStub = stub } func (fake *FakeManager) NewObjectArgsForCall(i int) string { fake.newObjectMutex.RLock() defer fake.newObjectMutex.RUnlock() argsForCall := fake.newObjectArgsForCall[i] return argsForCall.arg1 } func (fake *FakeManager) NewObjectReturns(result1 string, result2 error) { fake.newObjectMutex.Lock() defer fake.newObjectMutex.Unlock() fake.NewObjectStub = nil fake.newObjectReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) NewObjectReturnsOnCall(i int, result1 string, result2 error) { fake.newObjectMutex.Lock() defer fake.newObjectMutex.Unlock() fake.NewObjectStub = nil if fake.newObjectReturnsOnCall == nil { fake.newObjectReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.newObjectReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) NodeAddress() string { fake.nodeAddressMutex.Lock() ret, specificReturn := fake.nodeAddressReturnsOnCall[len(fake.nodeAddressArgsForCall)] fake.nodeAddressArgsForCall = append(fake.nodeAddressArgsForCall, struct { }{}) fake.recordInvocation("NodeAddress", []interface{}{}) fake.nodeAddressMutex.Unlock() if fake.NodeAddressStub != nil { return fake.NodeAddressStub() } if specificReturn { return ret.result1 } fakeReturns := fake.nodeAddressReturns return fakeReturns.result1 } func (fake *FakeManager) NodeAddressCallCount() int { fake.nodeAddressMutex.RLock() defer fake.nodeAddressMutex.RUnlock() return len(fake.nodeAddressArgsForCall) } func (fake *FakeManager) NodeAddressCalls(stub func() string) { fake.nodeAddressMutex.Lock() defer fake.nodeAddressMutex.Unlock() fake.NodeAddressStub = stub } func (fake *FakeManager) NodeAddressReturns(result1 string) { fake.nodeAddressMutex.Lock() defer fake.nodeAddressMutex.Unlock() fake.NodeAddressStub = nil fake.nodeAddressReturns = struct { result1 string }{result1} } func (fake *FakeManager) NodeAddressReturnsOnCall(i int, result1 string) { fake.nodeAddressMutex.Lock() defer fake.nodeAddressMutex.Unlock() fake.NodeAddressStub = nil if fake.nodeAddressReturnsOnCall == nil { fake.nodeAddressReturnsOnCall = make(map[int]struct { result1 string }) } fake.nodeAddressReturnsOnCall[i] = struct { result1 string }{result1} } func (fake *FakeManager) PatchLink(arg1 string, arg2 string, arg3 string, arg4 bool) (string, error) { fake.patchLinkMutex.Lock() ret, specificReturn := fake.patchLinkReturnsOnCall[len(fake.patchLinkArgsForCall)] fake.patchLinkArgsForCall = append(fake.patchLinkArgsForCall, struct { arg1 string arg2 string arg3 string arg4 bool }{arg1, arg2, arg3, arg4}) fake.recordInvocation("PatchLink", []interface{}{arg1, arg2, arg3, arg4}) fake.patchLinkMutex.Unlock() if fake.PatchLinkStub != nil { return fake.PatchLinkStub(arg1, arg2, arg3, arg4) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.patchLinkReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) PatchLinkCallCount() int { fake.patchLinkMutex.RLock() defer fake.patchLinkMutex.RUnlock() return len(fake.patchLinkArgsForCall) } func (fake *FakeManager) PatchLinkCalls(stub func(string, string, string, bool) (string, error)) { fake.patchLinkMutex.Lock() defer fake.patchLinkMutex.Unlock() fake.PatchLinkStub = stub } func (fake *FakeManager) PatchLinkArgsForCall(i int) (string, string, string, bool) { fake.patchLinkMutex.RLock() defer fake.patchLinkMutex.RUnlock() argsForCall := fake.patchLinkArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 } func (fake *FakeManager) PatchLinkReturns(result1 string, result2 error) { fake.patchLinkMutex.Lock() defer fake.patchLinkMutex.Unlock() fake.PatchLinkStub = nil fake.patchLinkReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) PatchLinkReturnsOnCall(i int, result1 string, result2 error) { fake.patchLinkMutex.Lock() defer fake.patchLinkMutex.Unlock() fake.PatchLinkStub = nil if fake.patchLinkReturnsOnCall == nil { fake.patchLinkReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.patchLinkReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) Pin(arg1 string) error { fake.pinMutex.Lock() ret, specificReturn := fake.pinReturnsOnCall[len(fake.pinArgsForCall)] fake.pinArgsForCall = append(fake.pinArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("Pin", []interface{}{arg1}) fake.pinMutex.Unlock() if fake.PinStub != nil { return fake.PinStub(arg1) } if specificReturn { return ret.result1 } fakeReturns := fake.pinReturns return fakeReturns.result1 } func (fake *FakeManager) PinCallCount() int { fake.pinMutex.RLock() defer fake.pinMutex.RUnlock() return len(fake.pinArgsForCall) } func (fake *FakeManager) PinCalls(stub func(string) error) { fake.pinMutex.Lock() defer fake.pinMutex.Unlock() fake.PinStub = stub } func (fake *FakeManager) PinArgsForCall(i int) string { fake.pinMutex.RLock() defer fake.pinMutex.RUnlock() argsForCall := fake.pinArgsForCall[i] return argsForCall.arg1 } func (fake *FakeManager) PinReturns(result1 error) { fake.pinMutex.Lock() defer fake.pinMutex.Unlock() fake.PinStub = nil fake.pinReturns = struct { result1 error }{result1} } func (fake *FakeManager) PinReturnsOnCall(i int, result1 error) { fake.pinMutex.Lock() defer fake.pinMutex.Unlock() fake.PinStub = nil if fake.pinReturnsOnCall == nil { fake.pinReturnsOnCall = make(map[int]struct { result1 error }) } fake.pinReturnsOnCall[i] = struct { result1 error }{result1} } func (fake *FakeManager) PinUpdate(arg1 string, arg2 string) (string, error) { fake.pinUpdateMutex.Lock() ret, specificReturn := fake.pinUpdateReturnsOnCall[len(fake.pinUpdateArgsForCall)] fake.pinUpdateArgsForCall = append(fake.pinUpdateArgsForCall, struct { arg1 string arg2 string }{arg1, arg2}) fake.recordInvocation("PinUpdate", []interface{}{arg1, arg2}) fake.pinUpdateMutex.Unlock() if fake.PinUpdateStub != nil { return fake.PinUpdateStub(arg1, arg2) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.pinUpdateReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeManager) PinUpdateCallCount() int { fake.pinUpdateMutex.RLock() defer fake.pinUpdateMutex.RUnlock() return len(fake.pinUpdateArgsForCall) } func (fake *FakeManager) PinUpdateCalls(stub func(string, string) (string, error)) { fake.pinUpdateMutex.Lock() defer fake.pinUpdateMutex.Unlock() fake.PinUpdateStub = stub } func (fake *FakeManager) PinUpdateArgsForCall(i int) (string, string) { fake.pinUpdateMutex.RLock() defer fake.pinUpdateMutex.RUnlock() argsForCall := fake.pinUpdateArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeManager) PinUpdateReturns(result1 string, result2 error) { fake.pinUpdateMutex.Lock() defer fake.pinUpdateMutex.Unlock() fake.PinUpdateStub = nil fake.pinUpdateReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) PinUpdateReturnsOnCall(i int, result1 string, result2 error) { fake.pinUpdateMutex.Lock() defer fake.pinUpdateMutex.Unlock() fake.PinUpdateStub = nil if fake.pinUpdateReturnsOnCall == nil { fake.pinUpdateReturnsOnCall = make(map[int]struct { result1 string result2 error }) } fake.pinUpdateReturnsOnCall[i] = struct { result1 string result2 error }{result1, result2} } func (fake *FakeManager) PubSubPublish(arg1 string, arg2 string) error { fake.pubSubPublishMutex.Lock() ret, specificReturn := fake.pubSubPublishReturnsOnCall[len(fake.pubSubPublishArgsForCall)] fake.pubSubPublishArgsForCall = append(fake.pubSubPublishArgsForCall, struct { arg1 string arg2 string }{arg1, arg2}) fake.recordInvocation("PubSubPublish", []interface{}{arg1, arg2}) fake.pubSubPublishMutex.Unlock() if fake.PubSubPublishStub != nil { return fake.PubSubPublishStub(arg1, arg2) } if specificReturn { return ret.result1 } fakeReturns := fake.pubSubPublishReturns return fakeReturns.result1 } func (fake *FakeManager) PubSubPublishCallCount() int { fake.pubSubPublishMutex.RLock() defer fake.pubSubPublishMutex.RUnlock() return len(fake.pubSubPublishArgsForCall) } func (fake *FakeManager) PubSubPublishCalls(stub func(string, string) error) { fake.pubSubPublishMutex.Lock() defer fake.pubSubPublishMutex.Unlock() fake.PubSubPublishStub = stub } func (fake *FakeManager) PubSubPublishArgsForCall(i int) (string, string) { fake.pubSubPublishMutex.RLock() defer fake.pubSubPublishMutex.RUnlock() argsForCall := fake.pubSubPublishArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeManager) PubSubPublishReturns(result1 error) { fake.pubSubPublishMutex.Lock() defer fake.pubSubPublishMutex.Unlock()
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
true
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/mocks/bch.mock.go
mocks/bch.mock.go
// Code generated by counterfeiter. DO NOT EDIT. package mocks import ( "context" "sync" "github.com/gcash/bchwallet/rpc/walletrpc" "google.golang.org/grpc" ) type FakeWalletServiceClient struct { AccountNotificationsStub func(context.Context, *walletrpc.AccountNotificationsRequest, ...grpc.CallOption) (walletrpc.WalletService_AccountNotificationsClient, error) accountNotificationsMutex sync.RWMutex accountNotificationsArgsForCall []struct { arg1 context.Context arg2 *walletrpc.AccountNotificationsRequest arg3 []grpc.CallOption } accountNotificationsReturns struct { result1 walletrpc.WalletService_AccountNotificationsClient result2 error } accountNotificationsReturnsOnCall map[int]struct { result1 walletrpc.WalletService_AccountNotificationsClient result2 error } AccountNumberStub func(context.Context, *walletrpc.AccountNumberRequest, ...grpc.CallOption) (*walletrpc.AccountNumberResponse, error) accountNumberMutex sync.RWMutex accountNumberArgsForCall []struct { arg1 context.Context arg2 *walletrpc.AccountNumberRequest arg3 []grpc.CallOption } accountNumberReturns struct { result1 *walletrpc.AccountNumberResponse result2 error } accountNumberReturnsOnCall map[int]struct { result1 *walletrpc.AccountNumberResponse result2 error } AccountsStub func(context.Context, *walletrpc.AccountsRequest, ...grpc.CallOption) (*walletrpc.AccountsResponse, error) accountsMutex sync.RWMutex accountsArgsForCall []struct { arg1 context.Context arg2 *walletrpc.AccountsRequest arg3 []grpc.CallOption } accountsReturns struct { result1 *walletrpc.AccountsResponse result2 error } accountsReturnsOnCall map[int]struct { result1 *walletrpc.AccountsResponse result2 error } BalanceStub func(context.Context, *walletrpc.BalanceRequest, ...grpc.CallOption) (*walletrpc.BalanceResponse, error) balanceMutex sync.RWMutex balanceArgsForCall []struct { arg1 context.Context arg2 *walletrpc.BalanceRequest arg3 []grpc.CallOption } balanceReturns struct { result1 *walletrpc.BalanceResponse result2 error } balanceReturnsOnCall map[int]struct { result1 *walletrpc.BalanceResponse result2 error } ChangePassphraseStub func(context.Context, *walletrpc.ChangePassphraseRequest, ...grpc.CallOption) (*walletrpc.ChangePassphraseResponse, error) changePassphraseMutex sync.RWMutex changePassphraseArgsForCall []struct { arg1 context.Context arg2 *walletrpc.ChangePassphraseRequest arg3 []grpc.CallOption } changePassphraseReturns struct { result1 *walletrpc.ChangePassphraseResponse result2 error } changePassphraseReturnsOnCall map[int]struct { result1 *walletrpc.ChangePassphraseResponse result2 error } CreateTransactionStub func(context.Context, *walletrpc.CreateTransactionRequest, ...grpc.CallOption) (*walletrpc.CreateTransactionResponse, error) createTransactionMutex sync.RWMutex createTransactionArgsForCall []struct { arg1 context.Context arg2 *walletrpc.CreateTransactionRequest arg3 []grpc.CallOption } createTransactionReturns struct { result1 *walletrpc.CreateTransactionResponse result2 error } createTransactionReturnsOnCall map[int]struct { result1 *walletrpc.CreateTransactionResponse result2 error } CurrentAddressStub func(context.Context, *walletrpc.CurrentAddressRequest, ...grpc.CallOption) (*walletrpc.CurrentAddressResponse, error) currentAddressMutex sync.RWMutex currentAddressArgsForCall []struct { arg1 context.Context arg2 *walletrpc.CurrentAddressRequest arg3 []grpc.CallOption } currentAddressReturns struct { result1 *walletrpc.CurrentAddressResponse result2 error } currentAddressReturnsOnCall map[int]struct { result1 *walletrpc.CurrentAddressResponse result2 error } DownloadPaymentRequestStub func(context.Context, *walletrpc.DownloadPaymentRequestRequest, ...grpc.CallOption) (*walletrpc.DownloadPaymentRequestResponse, error) downloadPaymentRequestMutex sync.RWMutex downloadPaymentRequestArgsForCall []struct { arg1 context.Context arg2 *walletrpc.DownloadPaymentRequestRequest arg3 []grpc.CallOption } downloadPaymentRequestReturns struct { result1 *walletrpc.DownloadPaymentRequestResponse result2 error } downloadPaymentRequestReturnsOnCall map[int]struct { result1 *walletrpc.DownloadPaymentRequestResponse result2 error } FundTransactionStub func(context.Context, *walletrpc.FundTransactionRequest, ...grpc.CallOption) (*walletrpc.FundTransactionResponse, error) fundTransactionMutex sync.RWMutex fundTransactionArgsForCall []struct { arg1 context.Context arg2 *walletrpc.FundTransactionRequest arg3 []grpc.CallOption } fundTransactionReturns struct { result1 *walletrpc.FundTransactionResponse result2 error } fundTransactionReturnsOnCall map[int]struct { result1 *walletrpc.FundTransactionResponse result2 error } GetTransactionsStub func(context.Context, *walletrpc.GetTransactionsRequest, ...grpc.CallOption) (*walletrpc.GetTransactionsResponse, error) getTransactionsMutex sync.RWMutex getTransactionsArgsForCall []struct { arg1 context.Context arg2 *walletrpc.GetTransactionsRequest arg3 []grpc.CallOption } getTransactionsReturns struct { result1 *walletrpc.GetTransactionsResponse result2 error } getTransactionsReturnsOnCall map[int]struct { result1 *walletrpc.GetTransactionsResponse result2 error } ImportPrivateKeyStub func(context.Context, *walletrpc.ImportPrivateKeyRequest, ...grpc.CallOption) (*walletrpc.ImportPrivateKeyResponse, error) importPrivateKeyMutex sync.RWMutex importPrivateKeyArgsForCall []struct { arg1 context.Context arg2 *walletrpc.ImportPrivateKeyRequest arg3 []grpc.CallOption } importPrivateKeyReturns struct { result1 *walletrpc.ImportPrivateKeyResponse result2 error } importPrivateKeyReturnsOnCall map[int]struct { result1 *walletrpc.ImportPrivateKeyResponse result2 error } NetworkStub func(context.Context, *walletrpc.NetworkRequest, ...grpc.CallOption) (*walletrpc.NetworkResponse, error) networkMutex sync.RWMutex networkArgsForCall []struct { arg1 context.Context arg2 *walletrpc.NetworkRequest arg3 []grpc.CallOption } networkReturns struct { result1 *walletrpc.NetworkResponse result2 error } networkReturnsOnCall map[int]struct { result1 *walletrpc.NetworkResponse result2 error } NextAccountStub func(context.Context, *walletrpc.NextAccountRequest, ...grpc.CallOption) (*walletrpc.NextAccountResponse, error) nextAccountMutex sync.RWMutex nextAccountArgsForCall []struct { arg1 context.Context arg2 *walletrpc.NextAccountRequest arg3 []grpc.CallOption } nextAccountReturns struct { result1 *walletrpc.NextAccountResponse result2 error } nextAccountReturnsOnCall map[int]struct { result1 *walletrpc.NextAccountResponse result2 error } NextAddressStub func(context.Context, *walletrpc.NextAddressRequest, ...grpc.CallOption) (*walletrpc.NextAddressResponse, error) nextAddressMutex sync.RWMutex nextAddressArgsForCall []struct { arg1 context.Context arg2 *walletrpc.NextAddressRequest arg3 []grpc.CallOption } nextAddressReturns struct { result1 *walletrpc.NextAddressResponse result2 error } nextAddressReturnsOnCall map[int]struct { result1 *walletrpc.NextAddressResponse result2 error } PingStub func(context.Context, *walletrpc.PingRequest, ...grpc.CallOption) (*walletrpc.PingResponse, error) pingMutex sync.RWMutex pingArgsForCall []struct { arg1 context.Context arg2 *walletrpc.PingRequest arg3 []grpc.CallOption } pingReturns struct { result1 *walletrpc.PingResponse result2 error } pingReturnsOnCall map[int]struct { result1 *walletrpc.PingResponse result2 error } PostPaymentStub func(context.Context, *walletrpc.PostPaymentRequest, ...grpc.CallOption) (*walletrpc.PostPaymentResponse, error) postPaymentMutex sync.RWMutex postPaymentArgsForCall []struct { arg1 context.Context arg2 *walletrpc.PostPaymentRequest arg3 []grpc.CallOption } postPaymentReturns struct { result1 *walletrpc.PostPaymentResponse result2 error } postPaymentReturnsOnCall map[int]struct { result1 *walletrpc.PostPaymentResponse result2 error } PublishTransactionStub func(context.Context, *walletrpc.PublishTransactionRequest, ...grpc.CallOption) (*walletrpc.PublishTransactionResponse, error) publishTransactionMutex sync.RWMutex publishTransactionArgsForCall []struct { arg1 context.Context arg2 *walletrpc.PublishTransactionRequest arg3 []grpc.CallOption } publishTransactionReturns struct { result1 *walletrpc.PublishTransactionResponse result2 error } publishTransactionReturnsOnCall map[int]struct { result1 *walletrpc.PublishTransactionResponse result2 error } RenameAccountStub func(context.Context, *walletrpc.RenameAccountRequest, ...grpc.CallOption) (*walletrpc.RenameAccountResponse, error) renameAccountMutex sync.RWMutex renameAccountArgsForCall []struct { arg1 context.Context arg2 *walletrpc.RenameAccountRequest arg3 []grpc.CallOption } renameAccountReturns struct { result1 *walletrpc.RenameAccountResponse result2 error } renameAccountReturnsOnCall map[int]struct { result1 *walletrpc.RenameAccountResponse result2 error } RescanStub func(context.Context, *walletrpc.RescanRequest, ...grpc.CallOption) (*walletrpc.RescanResponse, error) rescanMutex sync.RWMutex rescanArgsForCall []struct { arg1 context.Context arg2 *walletrpc.RescanRequest arg3 []grpc.CallOption } rescanReturns struct { result1 *walletrpc.RescanResponse result2 error } rescanReturnsOnCall map[int]struct { result1 *walletrpc.RescanResponse result2 error } RescanNotificationsStub func(context.Context, *walletrpc.RescanNotificationsRequest, ...grpc.CallOption) (walletrpc.WalletService_RescanNotificationsClient, error) rescanNotificationsMutex sync.RWMutex rescanNotificationsArgsForCall []struct { arg1 context.Context arg2 *walletrpc.RescanNotificationsRequest arg3 []grpc.CallOption } rescanNotificationsReturns struct { result1 walletrpc.WalletService_RescanNotificationsClient result2 error } rescanNotificationsReturnsOnCall map[int]struct { result1 walletrpc.WalletService_RescanNotificationsClient result2 error } SignTransactionStub func(context.Context, *walletrpc.SignTransactionRequest, ...grpc.CallOption) (*walletrpc.SignTransactionResponse, error) signTransactionMutex sync.RWMutex signTransactionArgsForCall []struct { arg1 context.Context arg2 *walletrpc.SignTransactionRequest arg3 []grpc.CallOption } signTransactionReturns struct { result1 *walletrpc.SignTransactionResponse result2 error } signTransactionReturnsOnCall map[int]struct { result1 *walletrpc.SignTransactionResponse result2 error } SpentnessNotificationsStub func(context.Context, *walletrpc.SpentnessNotificationsRequest, ...grpc.CallOption) (walletrpc.WalletService_SpentnessNotificationsClient, error) spentnessNotificationsMutex sync.RWMutex spentnessNotificationsArgsForCall []struct { arg1 context.Context arg2 *walletrpc.SpentnessNotificationsRequest arg3 []grpc.CallOption } spentnessNotificationsReturns struct { result1 walletrpc.WalletService_SpentnessNotificationsClient result2 error } spentnessNotificationsReturnsOnCall map[int]struct { result1 walletrpc.WalletService_SpentnessNotificationsClient result2 error } SweepAccountStub func(context.Context, *walletrpc.SweepAccountRequest, ...grpc.CallOption) (*walletrpc.SweepAccountResponse, error) sweepAccountMutex sync.RWMutex sweepAccountArgsForCall []struct { arg1 context.Context arg2 *walletrpc.SweepAccountRequest arg3 []grpc.CallOption } sweepAccountReturns struct { result1 *walletrpc.SweepAccountResponse result2 error } sweepAccountReturnsOnCall map[int]struct { result1 *walletrpc.SweepAccountResponse result2 error } TransactionNotificationsStub func(context.Context, *walletrpc.TransactionNotificationsRequest, ...grpc.CallOption) (walletrpc.WalletService_TransactionNotificationsClient, error) transactionNotificationsMutex sync.RWMutex transactionNotificationsArgsForCall []struct { arg1 context.Context arg2 *walletrpc.TransactionNotificationsRequest arg3 []grpc.CallOption } transactionNotificationsReturns struct { result1 walletrpc.WalletService_TransactionNotificationsClient result2 error } transactionNotificationsReturnsOnCall map[int]struct { result1 walletrpc.WalletService_TransactionNotificationsClient result2 error } ValidateAddressStub func(context.Context, *walletrpc.ValidateAddressRequest, ...grpc.CallOption) (*walletrpc.ValidateAddressResponse, error) validateAddressMutex sync.RWMutex validateAddressArgsForCall []struct { arg1 context.Context arg2 *walletrpc.ValidateAddressRequest arg3 []grpc.CallOption } validateAddressReturns struct { result1 *walletrpc.ValidateAddressResponse result2 error } validateAddressReturnsOnCall map[int]struct { result1 *walletrpc.ValidateAddressResponse result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeWalletServiceClient) AccountNotifications(arg1 context.Context, arg2 *walletrpc.AccountNotificationsRequest, arg3 ...grpc.CallOption) (walletrpc.WalletService_AccountNotificationsClient, error) { fake.accountNotificationsMutex.Lock() ret, specificReturn := fake.accountNotificationsReturnsOnCall[len(fake.accountNotificationsArgsForCall)] fake.accountNotificationsArgsForCall = append(fake.accountNotificationsArgsForCall, struct { arg1 context.Context arg2 *walletrpc.AccountNotificationsRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("AccountNotifications", []interface{}{arg1, arg2, arg3}) fake.accountNotificationsMutex.Unlock() if fake.AccountNotificationsStub != nil { return fake.AccountNotificationsStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.accountNotificationsReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) AccountNotificationsCallCount() int { fake.accountNotificationsMutex.RLock() defer fake.accountNotificationsMutex.RUnlock() return len(fake.accountNotificationsArgsForCall) } func (fake *FakeWalletServiceClient) AccountNotificationsCalls(stub func(context.Context, *walletrpc.AccountNotificationsRequest, ...grpc.CallOption) (walletrpc.WalletService_AccountNotificationsClient, error)) { fake.accountNotificationsMutex.Lock() defer fake.accountNotificationsMutex.Unlock() fake.AccountNotificationsStub = stub } func (fake *FakeWalletServiceClient) AccountNotificationsArgsForCall(i int) (context.Context, *walletrpc.AccountNotificationsRequest, []grpc.CallOption) { fake.accountNotificationsMutex.RLock() defer fake.accountNotificationsMutex.RUnlock() argsForCall := fake.accountNotificationsArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) AccountNotificationsReturns(result1 walletrpc.WalletService_AccountNotificationsClient, result2 error) { fake.accountNotificationsMutex.Lock() defer fake.accountNotificationsMutex.Unlock() fake.AccountNotificationsStub = nil fake.accountNotificationsReturns = struct { result1 walletrpc.WalletService_AccountNotificationsClient result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) AccountNotificationsReturnsOnCall(i int, result1 walletrpc.WalletService_AccountNotificationsClient, result2 error) { fake.accountNotificationsMutex.Lock() defer fake.accountNotificationsMutex.Unlock() fake.AccountNotificationsStub = nil if fake.accountNotificationsReturnsOnCall == nil { fake.accountNotificationsReturnsOnCall = make(map[int]struct { result1 walletrpc.WalletService_AccountNotificationsClient result2 error }) } fake.accountNotificationsReturnsOnCall[i] = struct { result1 walletrpc.WalletService_AccountNotificationsClient result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) AccountNumber(arg1 context.Context, arg2 *walletrpc.AccountNumberRequest, arg3 ...grpc.CallOption) (*walletrpc.AccountNumberResponse, error) { fake.accountNumberMutex.Lock() ret, specificReturn := fake.accountNumberReturnsOnCall[len(fake.accountNumberArgsForCall)] fake.accountNumberArgsForCall = append(fake.accountNumberArgsForCall, struct { arg1 context.Context arg2 *walletrpc.AccountNumberRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("AccountNumber", []interface{}{arg1, arg2, arg3}) fake.accountNumberMutex.Unlock() if fake.AccountNumberStub != nil { return fake.AccountNumberStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.accountNumberReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) AccountNumberCallCount() int { fake.accountNumberMutex.RLock() defer fake.accountNumberMutex.RUnlock() return len(fake.accountNumberArgsForCall) } func (fake *FakeWalletServiceClient) AccountNumberCalls(stub func(context.Context, *walletrpc.AccountNumberRequest, ...grpc.CallOption) (*walletrpc.AccountNumberResponse, error)) { fake.accountNumberMutex.Lock() defer fake.accountNumberMutex.Unlock() fake.AccountNumberStub = stub } func (fake *FakeWalletServiceClient) AccountNumberArgsForCall(i int) (context.Context, *walletrpc.AccountNumberRequest, []grpc.CallOption) { fake.accountNumberMutex.RLock() defer fake.accountNumberMutex.RUnlock() argsForCall := fake.accountNumberArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) AccountNumberReturns(result1 *walletrpc.AccountNumberResponse, result2 error) { fake.accountNumberMutex.Lock() defer fake.accountNumberMutex.Unlock() fake.AccountNumberStub = nil fake.accountNumberReturns = struct { result1 *walletrpc.AccountNumberResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) AccountNumberReturnsOnCall(i int, result1 *walletrpc.AccountNumberResponse, result2 error) { fake.accountNumberMutex.Lock() defer fake.accountNumberMutex.Unlock() fake.AccountNumberStub = nil if fake.accountNumberReturnsOnCall == nil { fake.accountNumberReturnsOnCall = make(map[int]struct { result1 *walletrpc.AccountNumberResponse result2 error }) } fake.accountNumberReturnsOnCall[i] = struct { result1 *walletrpc.AccountNumberResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) Accounts(arg1 context.Context, arg2 *walletrpc.AccountsRequest, arg3 ...grpc.CallOption) (*walletrpc.AccountsResponse, error) { fake.accountsMutex.Lock() ret, specificReturn := fake.accountsReturnsOnCall[len(fake.accountsArgsForCall)] fake.accountsArgsForCall = append(fake.accountsArgsForCall, struct { arg1 context.Context arg2 *walletrpc.AccountsRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("Accounts", []interface{}{arg1, arg2, arg3}) fake.accountsMutex.Unlock() if fake.AccountsStub != nil { return fake.AccountsStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.accountsReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) AccountsCallCount() int { fake.accountsMutex.RLock() defer fake.accountsMutex.RUnlock() return len(fake.accountsArgsForCall) } func (fake *FakeWalletServiceClient) AccountsCalls(stub func(context.Context, *walletrpc.AccountsRequest, ...grpc.CallOption) (*walletrpc.AccountsResponse, error)) { fake.accountsMutex.Lock() defer fake.accountsMutex.Unlock() fake.AccountsStub = stub } func (fake *FakeWalletServiceClient) AccountsArgsForCall(i int) (context.Context, *walletrpc.AccountsRequest, []grpc.CallOption) { fake.accountsMutex.RLock() defer fake.accountsMutex.RUnlock() argsForCall := fake.accountsArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) AccountsReturns(result1 *walletrpc.AccountsResponse, result2 error) { fake.accountsMutex.Lock() defer fake.accountsMutex.Unlock() fake.AccountsStub = nil fake.accountsReturns = struct { result1 *walletrpc.AccountsResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) AccountsReturnsOnCall(i int, result1 *walletrpc.AccountsResponse, result2 error) { fake.accountsMutex.Lock() defer fake.accountsMutex.Unlock() fake.AccountsStub = nil if fake.accountsReturnsOnCall == nil { fake.accountsReturnsOnCall = make(map[int]struct { result1 *walletrpc.AccountsResponse result2 error }) } fake.accountsReturnsOnCall[i] = struct { result1 *walletrpc.AccountsResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) Balance(arg1 context.Context, arg2 *walletrpc.BalanceRequest, arg3 ...grpc.CallOption) (*walletrpc.BalanceResponse, error) { fake.balanceMutex.Lock() ret, specificReturn := fake.balanceReturnsOnCall[len(fake.balanceArgsForCall)] fake.balanceArgsForCall = append(fake.balanceArgsForCall, struct { arg1 context.Context arg2 *walletrpc.BalanceRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("Balance", []interface{}{arg1, arg2, arg3}) fake.balanceMutex.Unlock() if fake.BalanceStub != nil { return fake.BalanceStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.balanceReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) BalanceCallCount() int { fake.balanceMutex.RLock() defer fake.balanceMutex.RUnlock() return len(fake.balanceArgsForCall) } func (fake *FakeWalletServiceClient) BalanceCalls(stub func(context.Context, *walletrpc.BalanceRequest, ...grpc.CallOption) (*walletrpc.BalanceResponse, error)) { fake.balanceMutex.Lock() defer fake.balanceMutex.Unlock() fake.BalanceStub = stub } func (fake *FakeWalletServiceClient) BalanceArgsForCall(i int) (context.Context, *walletrpc.BalanceRequest, []grpc.CallOption) { fake.balanceMutex.RLock() defer fake.balanceMutex.RUnlock() argsForCall := fake.balanceArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) BalanceReturns(result1 *walletrpc.BalanceResponse, result2 error) { fake.balanceMutex.Lock() defer fake.balanceMutex.Unlock() fake.BalanceStub = nil fake.balanceReturns = struct { result1 *walletrpc.BalanceResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) BalanceReturnsOnCall(i int, result1 *walletrpc.BalanceResponse, result2 error) { fake.balanceMutex.Lock() defer fake.balanceMutex.Unlock() fake.BalanceStub = nil if fake.balanceReturnsOnCall == nil { fake.balanceReturnsOnCall = make(map[int]struct { result1 *walletrpc.BalanceResponse result2 error }) } fake.balanceReturnsOnCall[i] = struct { result1 *walletrpc.BalanceResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) ChangePassphrase(arg1 context.Context, arg2 *walletrpc.ChangePassphraseRequest, arg3 ...grpc.CallOption) (*walletrpc.ChangePassphraseResponse, error) { fake.changePassphraseMutex.Lock() ret, specificReturn := fake.changePassphraseReturnsOnCall[len(fake.changePassphraseArgsForCall)] fake.changePassphraseArgsForCall = append(fake.changePassphraseArgsForCall, struct { arg1 context.Context arg2 *walletrpc.ChangePassphraseRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("ChangePassphrase", []interface{}{arg1, arg2, arg3}) fake.changePassphraseMutex.Unlock() if fake.ChangePassphraseStub != nil { return fake.ChangePassphraseStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.changePassphraseReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) ChangePassphraseCallCount() int { fake.changePassphraseMutex.RLock() defer fake.changePassphraseMutex.RUnlock() return len(fake.changePassphraseArgsForCall) } func (fake *FakeWalletServiceClient) ChangePassphraseCalls(stub func(context.Context, *walletrpc.ChangePassphraseRequest, ...grpc.CallOption) (*walletrpc.ChangePassphraseResponse, error)) { fake.changePassphraseMutex.Lock() defer fake.changePassphraseMutex.Unlock() fake.ChangePassphraseStub = stub } func (fake *FakeWalletServiceClient) ChangePassphraseArgsForCall(i int) (context.Context, *walletrpc.ChangePassphraseRequest, []grpc.CallOption) { fake.changePassphraseMutex.RLock() defer fake.changePassphraseMutex.RUnlock() argsForCall := fake.changePassphraseArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) ChangePassphraseReturns(result1 *walletrpc.ChangePassphraseResponse, result2 error) { fake.changePassphraseMutex.Lock() defer fake.changePassphraseMutex.Unlock() fake.ChangePassphraseStub = nil fake.changePassphraseReturns = struct { result1 *walletrpc.ChangePassphraseResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) ChangePassphraseReturnsOnCall(i int, result1 *walletrpc.ChangePassphraseResponse, result2 error) { fake.changePassphraseMutex.Lock() defer fake.changePassphraseMutex.Unlock() fake.ChangePassphraseStub = nil if fake.changePassphraseReturnsOnCall == nil { fake.changePassphraseReturnsOnCall = make(map[int]struct { result1 *walletrpc.ChangePassphraseResponse result2 error }) } fake.changePassphraseReturnsOnCall[i] = struct { result1 *walletrpc.ChangePassphraseResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) CreateTransaction(arg1 context.Context, arg2 *walletrpc.CreateTransactionRequest, arg3 ...grpc.CallOption) (*walletrpc.CreateTransactionResponse, error) { fake.createTransactionMutex.Lock() ret, specificReturn := fake.createTransactionReturnsOnCall[len(fake.createTransactionArgsForCall)] fake.createTransactionArgsForCall = append(fake.createTransactionArgsForCall, struct { arg1 context.Context arg2 *walletrpc.CreateTransactionRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("CreateTransaction", []interface{}{arg1, arg2, arg3}) fake.createTransactionMutex.Unlock() if fake.CreateTransactionStub != nil { return fake.CreateTransactionStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.createTransactionReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) CreateTransactionCallCount() int { fake.createTransactionMutex.RLock() defer fake.createTransactionMutex.RUnlock() return len(fake.createTransactionArgsForCall) } func (fake *FakeWalletServiceClient) CreateTransactionCalls(stub func(context.Context, *walletrpc.CreateTransactionRequest, ...grpc.CallOption) (*walletrpc.CreateTransactionResponse, error)) { fake.createTransactionMutex.Lock() defer fake.createTransactionMutex.Unlock() fake.CreateTransactionStub = stub } func (fake *FakeWalletServiceClient) CreateTransactionArgsForCall(i int) (context.Context, *walletrpc.CreateTransactionRequest, []grpc.CallOption) { fake.createTransactionMutex.RLock() defer fake.createTransactionMutex.RUnlock() argsForCall := fake.createTransactionArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) CreateTransactionReturns(result1 *walletrpc.CreateTransactionResponse, result2 error) { fake.createTransactionMutex.Lock() defer fake.createTransactionMutex.Unlock() fake.CreateTransactionStub = nil fake.createTransactionReturns = struct { result1 *walletrpc.CreateTransactionResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) CreateTransactionReturnsOnCall(i int, result1 *walletrpc.CreateTransactionResponse, result2 error) { fake.createTransactionMutex.Lock() defer fake.createTransactionMutex.Unlock() fake.CreateTransactionStub = nil if fake.createTransactionReturnsOnCall == nil { fake.createTransactionReturnsOnCall = make(map[int]struct { result1 *walletrpc.CreateTransactionResponse result2 error }) } fake.createTransactionReturnsOnCall[i] = struct { result1 *walletrpc.CreateTransactionResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) CurrentAddress(arg1 context.Context, arg2 *walletrpc.CurrentAddressRequest, arg3 ...grpc.CallOption) (*walletrpc.CurrentAddressResponse, error) { fake.currentAddressMutex.Lock() ret, specificReturn := fake.currentAddressReturnsOnCall[len(fake.currentAddressArgsForCall)] fake.currentAddressArgsForCall = append(fake.currentAddressArgsForCall, struct { arg1 context.Context arg2 *walletrpc.CurrentAddressRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("CurrentAddress", []interface{}{arg1, arg2, arg3}) fake.currentAddressMutex.Unlock() if fake.CurrentAddressStub != nil { return fake.CurrentAddressStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.currentAddressReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) CurrentAddressCallCount() int { fake.currentAddressMutex.RLock() defer fake.currentAddressMutex.RUnlock() return len(fake.currentAddressArgsForCall) } func (fake *FakeWalletServiceClient) CurrentAddressCalls(stub func(context.Context, *walletrpc.CurrentAddressRequest, ...grpc.CallOption) (*walletrpc.CurrentAddressResponse, error)) { fake.currentAddressMutex.Lock() defer fake.currentAddressMutex.Unlock() fake.CurrentAddressStub = stub } func (fake *FakeWalletServiceClient) CurrentAddressArgsForCall(i int) (context.Context, *walletrpc.CurrentAddressRequest, []grpc.CallOption) { fake.currentAddressMutex.RLock() defer fake.currentAddressMutex.RUnlock() argsForCall := fake.currentAddressArgsForCall[i] return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3 } func (fake *FakeWalletServiceClient) CurrentAddressReturns(result1 *walletrpc.CurrentAddressResponse, result2 error) { fake.currentAddressMutex.Lock() defer fake.currentAddressMutex.Unlock() fake.CurrentAddressStub = nil fake.currentAddressReturns = struct { result1 *walletrpc.CurrentAddressResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) CurrentAddressReturnsOnCall(i int, result1 *walletrpc.CurrentAddressResponse, result2 error) { fake.currentAddressMutex.Lock() defer fake.currentAddressMutex.Unlock() fake.CurrentAddressStub = nil if fake.currentAddressReturnsOnCall == nil { fake.currentAddressReturnsOnCall = make(map[int]struct { result1 *walletrpc.CurrentAddressResponse result2 error }) } fake.currentAddressReturnsOnCall[i] = struct { result1 *walletrpc.CurrentAddressResponse result2 error }{result1, result2} } func (fake *FakeWalletServiceClient) DownloadPaymentRequest(arg1 context.Context, arg2 *walletrpc.DownloadPaymentRequestRequest, arg3 ...grpc.CallOption) (*walletrpc.DownloadPaymentRequestResponse, error) { fake.downloadPaymentRequestMutex.Lock() ret, specificReturn := fake.downloadPaymentRequestReturnsOnCall[len(fake.downloadPaymentRequestArgsForCall)] fake.downloadPaymentRequestArgsForCall = append(fake.downloadPaymentRequestArgsForCall, struct { arg1 context.Context arg2 *walletrpc.DownloadPaymentRequestRequest arg3 []grpc.CallOption }{arg1, arg2, arg3}) fake.recordInvocation("DownloadPaymentRequest", []interface{}{arg1, arg2, arg3}) fake.downloadPaymentRequestMutex.Unlock() if fake.DownloadPaymentRequestStub != nil { return fake.DownloadPaymentRequestStub(arg1, arg2, arg3...) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.downloadPaymentRequestReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeWalletServiceClient) DownloadPaymentRequestCallCount() int { fake.downloadPaymentRequestMutex.RLock() defer fake.downloadPaymentRequestMutex.RUnlock() return len(fake.downloadPaymentRequestArgsForCall) } func (fake *FakeWalletServiceClient) DownloadPaymentRequestCalls(stub func(context.Context, *walletrpc.DownloadPaymentRequestRequest, ...grpc.CallOption) (*walletrpc.DownloadPaymentRequestResponse, error)) { fake.downloadPaymentRequestMutex.Lock()
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
true
RTradeLtd/Temporal
https://github.com/RTradeLtd/Temporal/blob/4547df5e64d9823c6f670da4261de9e6d7353fb8/mocks/doc.go
mocks/doc.go
// Package mocks provided generated mock implementations of various interfaces // that Temporal depends on for testing purposes. package mocks
go
MIT
4547df5e64d9823c6f670da4261de9e6d7353fb8
2026-01-07T09:35:24.447786Z
false