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/option/simple.go
Bcore/windows/resources/sing-box-main/option/simple.go
package option import "github.com/sagernet/sing/common/auth" type SocksInboundOptions struct { ListenOptions Users []auth.User `json:"users,omitempty"` } type HTTPMixedInboundOptions struct { ListenOptions Users []auth.User `json:"users,omitempty"` SetSystemProxy bool `json:"set_system_proxy,omitempty"` InboundTLSOptionsContainer } type SocksOutboundOptions struct { DialerOptions ServerOptions Version string `json:"version,omitempty"` Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` Network NetworkList `json:"network,omitempty"` UDPOverTCP *UDPOverTCPOptions `json:"udp_over_tcp,omitempty"` } type HTTPOutboundOptions struct { DialerOptions ServerOptions Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` OutboundTLSOptionsContainer Path string `json:"path,omitempty"` Headers HTTPHeader `json:"headers,omitempty"` }
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/option/debug.go
Bcore/windows/resources/sing-box-main/option/debug.go
package option import ( "github.com/sagernet/sing-box/common/humanize" "github.com/sagernet/sing/common/json" ) type DebugOptions struct { Listen string `json:"listen,omitempty"` GCPercent *int `json:"gc_percent,omitempty"` MaxStack *int `json:"max_stack,omitempty"` MaxThreads *int `json:"max_threads,omitempty"` PanicOnFault *bool `json:"panic_on_fault,omitempty"` TraceBack string `json:"trace_back,omitempty"` MemoryLimit MemoryBytes `json:"memory_limit,omitempty"` OOMKiller *bool `json:"oom_killer,omitempty"` } type MemoryBytes uint64 func (l MemoryBytes) MarshalJSON() ([]byte, error) { return json.Marshal(humanize.MemoryBytes(uint64(l))) } func (l *MemoryBytes) UnmarshalJSON(bytes []byte) error { var valueInteger int64 err := json.Unmarshal(bytes, &valueInteger) if err == nil { *l = MemoryBytes(valueInteger) return nil } var valueString string err = json.Unmarshal(bytes, &valueString) if err != nil { return err } parsedValue, err := humanize.ParseMemoryBytes(valueString) if err != nil { return err } *l = MemoryBytes(parsedValue) 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/option/outbound.go
Bcore/windows/resources/sing-box-main/option/outbound.go
package option import ( C "github.com/sagernet/sing-box/constant" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" M "github.com/sagernet/sing/common/metadata" ) type _Outbound struct { Type string `json:"type"` Tag string `json:"tag,omitempty"` DirectOptions DirectOutboundOptions `json:"-"` SocksOptions SocksOutboundOptions `json:"-"` HTTPOptions HTTPOutboundOptions `json:"-"` ShadowsocksOptions ShadowsocksOutboundOptions `json:"-"` VMessOptions VMessOutboundOptions `json:"-"` TrojanOptions TrojanOutboundOptions `json:"-"` WireGuardOptions WireGuardOutboundOptions `json:"-"` HysteriaOptions HysteriaOutboundOptions `json:"-"` TorOptions TorOutboundOptions `json:"-"` SSHOptions SSHOutboundOptions `json:"-"` ShadowTLSOptions ShadowTLSOutboundOptions `json:"-"` ShadowsocksROptions ShadowsocksROutboundOptions `json:"-"` VLESSOptions VLESSOutboundOptions `json:"-"` TUICOptions TUICOutboundOptions `json:"-"` Hysteria2Options Hysteria2OutboundOptions `json:"-"` SelectorOptions SelectorOutboundOptions `json:"-"` URLTestOptions URLTestOutboundOptions `json:"-"` } type Outbound _Outbound func (h *Outbound) RawOptions() (any, error) { var rawOptionsPtr any switch h.Type { case C.TypeDirect: rawOptionsPtr = &h.DirectOptions case C.TypeBlock, C.TypeDNS: rawOptionsPtr = nil case C.TypeSOCKS: rawOptionsPtr = &h.SocksOptions case C.TypeHTTP: rawOptionsPtr = &h.HTTPOptions case C.TypeShadowsocks: rawOptionsPtr = &h.ShadowsocksOptions case C.TypeVMess: rawOptionsPtr = &h.VMessOptions case C.TypeTrojan: rawOptionsPtr = &h.TrojanOptions case C.TypeWireGuard: rawOptionsPtr = &h.WireGuardOptions case C.TypeHysteria: rawOptionsPtr = &h.HysteriaOptions case C.TypeTor: rawOptionsPtr = &h.TorOptions case C.TypeSSH: rawOptionsPtr = &h.SSHOptions case C.TypeShadowTLS: rawOptionsPtr = &h.ShadowTLSOptions case C.TypeShadowsocksR: rawOptionsPtr = &h.ShadowsocksROptions case C.TypeVLESS: rawOptionsPtr = &h.VLESSOptions case C.TypeTUIC: rawOptionsPtr = &h.TUICOptions case C.TypeHysteria2: rawOptionsPtr = &h.Hysteria2Options case C.TypeSelector: rawOptionsPtr = &h.SelectorOptions case C.TypeURLTest: rawOptionsPtr = &h.URLTestOptions case "": return nil, E.New("missing outbound type") default: return nil, E.New("unknown outbound type: ", h.Type) } return rawOptionsPtr, nil } func (h *Outbound) MarshalJSON() ([]byte, error) { rawOptions, err := h.RawOptions() if err != nil { return nil, err } return MarshallObjects((*_Outbound)(h), rawOptions) } func (h *Outbound) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_Outbound)(h)) if err != nil { return err } rawOptions, err := h.RawOptions() if err != nil { return err } err = UnmarshallExcluded(bytes, (*_Outbound)(h), rawOptions) if err != nil { return err } return nil } type DialerOptionsWrapper interface { TakeDialerOptions() DialerOptions ReplaceDialerOptions(options DialerOptions) } type DialerOptions struct { Detour string `json:"detour,omitempty"` BindInterface string `json:"bind_interface,omitempty"` Inet4BindAddress *ListenAddress `json:"inet4_bind_address,omitempty"` Inet6BindAddress *ListenAddress `json:"inet6_bind_address,omitempty"` ProtectPath string `json:"protect_path,omitempty"` RoutingMark uint32 `json:"routing_mark,omitempty"` ReuseAddr bool `json:"reuse_addr,omitempty"` ConnectTimeout Duration `json:"connect_timeout,omitempty"` TCPFastOpen bool `json:"tcp_fast_open,omitempty"` TCPMultiPath bool `json:"tcp_multi_path,omitempty"` UDPFragment *bool `json:"udp_fragment,omitempty"` UDPFragmentDefault bool `json:"-"` DomainStrategy DomainStrategy `json:"domain_strategy,omitempty"` FallbackDelay Duration `json:"fallback_delay,omitempty"` IsWireGuardListener bool `json:"-"` } func (o *DialerOptions) TakeDialerOptions() DialerOptions { return *o } func (o *DialerOptions) ReplaceDialerOptions(options DialerOptions) { *o = options } type ServerOptionsWrapper interface { TakeServerOptions() ServerOptions ReplaceServerOptions(options ServerOptions) } type ServerOptions struct { Server string `json:"server"` ServerPort uint16 `json:"server_port"` } func (o ServerOptions) Build() M.Socksaddr { return M.ParseSocksaddrHostPort(o.Server, o.ServerPort) } func (o *ServerOptions) TakeServerOptions() ServerOptions { return *o } func (o *ServerOptions) ReplaceServerOptions(options ServerOptions) { *o = options }
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/option/redir.go
Bcore/windows/resources/sing-box-main/option/redir.go
package option type RedirectInboundOptions struct { ListenOptions } type TProxyInboundOptions struct { ListenOptions Network NetworkList `json:"network,omitempty"` }
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/option/platform.go
Bcore/windows/resources/sing-box-main/option/platform.go
package option import ( E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" ) type OnDemandOptions struct { Enabled bool `json:"enabled,omitempty"` Rules []OnDemandRule `json:"rules,omitempty"` } type OnDemandRule struct { Action *OnDemandRuleAction `json:"action,omitempty"` DNSSearchDomainMatch Listable[string] `json:"dns_search_domain_match,omitempty"` DNSServerAddressMatch Listable[string] `json:"dns_server_address_match,omitempty"` InterfaceTypeMatch *OnDemandRuleInterfaceType `json:"interface_type_match,omitempty"` SSIDMatch Listable[string] `json:"ssid_match,omitempty"` ProbeURL string `json:"probe_url,omitempty"` } type OnDemandRuleAction int func (r *OnDemandRuleAction) MarshalJSON() ([]byte, error) { if r == nil { return nil, nil } value := *r var actionName string switch value { case 1: actionName = "connect" case 2: actionName = "disconnect" case 3: actionName = "evaluate_connection" default: return nil, E.New("unknown action: ", value) } return json.Marshal(actionName) } func (r *OnDemandRuleAction) UnmarshalJSON(bytes []byte) error { var actionName string if err := json.Unmarshal(bytes, &actionName); err != nil { return err } var actionValue int switch actionName { case "connect": actionValue = 1 case "disconnect": actionValue = 2 case "evaluate_connection": actionValue = 3 case "ignore": actionValue = 4 default: return E.New("unknown action name: ", actionName) } *r = OnDemandRuleAction(actionValue) return nil } type OnDemandRuleInterfaceType int func (r *OnDemandRuleInterfaceType) MarshalJSON() ([]byte, error) { if r == nil { return nil, nil } value := *r var interfaceTypeName string switch value { case 1: interfaceTypeName = "any" case 2: interfaceTypeName = "wifi" case 3: interfaceTypeName = "cellular" default: return nil, E.New("unknown interface type: ", value) } return json.Marshal(interfaceTypeName) } func (r *OnDemandRuleInterfaceType) UnmarshalJSON(bytes []byte) error { var interfaceTypeName string if err := json.Unmarshal(bytes, &interfaceTypeName); err != nil { return err } var interfaceTypeValue int switch interfaceTypeName { case "any": interfaceTypeValue = 1 case "wifi": interfaceTypeValue = 2 case "cellular": interfaceTypeValue = 3 default: return E.New("unknown interface type name: ", interfaceTypeName) } *r = OnDemandRuleInterfaceType(interfaceTypeValue) 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/option/shadowsocksr.go
Bcore/windows/resources/sing-box-main/option/shadowsocksr.go
package option type ShadowsocksROutboundOptions struct { DialerOptions ServerOptions Method string `json:"method"` Password string `json:"password"` Obfs string `json:"obfs,omitempty"` ObfsParam string `json:"obfs_param,omitempty"` Protocol string `json:"protocol,omitempty"` ProtocolParam string `json:"protocol_param,omitempty"` Network NetworkList `json:"network,omitempty"` }
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/option/shadowtls.go
Bcore/windows/resources/sing-box-main/option/shadowtls.go
package option type ShadowTLSInboundOptions struct { ListenOptions Version int `json:"version,omitempty"` Password string `json:"password,omitempty"` Users []ShadowTLSUser `json:"users,omitempty"` Handshake ShadowTLSHandshakeOptions `json:"handshake,omitempty"` HandshakeForServerName map[string]ShadowTLSHandshakeOptions `json:"handshake_for_server_name,omitempty"` StrictMode bool `json:"strict_mode,omitempty"` } type ShadowTLSUser struct { Name string `json:"name,omitempty"` Password string `json:"password,omitempty"` } type ShadowTLSHandshakeOptions struct { ServerOptions DialerOptions } type ShadowTLSOutboundOptions struct { DialerOptions ServerOptions Version int `json:"version,omitempty"` Password string `json:"password,omitempty"` OutboundTLSOptionsContainer }
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/option/wireguard.go
Bcore/windows/resources/sing-box-main/option/wireguard.go
package option import "net/netip" type WireGuardOutboundOptions struct { DialerOptions SystemInterface bool `json:"system_interface,omitempty"` GSO bool `json:"gso,omitempty"` InterfaceName string `json:"interface_name,omitempty"` LocalAddress Listable[netip.Prefix] `json:"local_address"` PrivateKey string `json:"private_key"` Peers []WireGuardPeer `json:"peers,omitempty"` ServerOptions PeerPublicKey string `json:"peer_public_key"` PreSharedKey string `json:"pre_shared_key,omitempty"` Reserved []uint8 `json:"reserved,omitempty"` Workers int `json:"workers,omitempty"` MTU uint32 `json:"mtu,omitempty"` Network NetworkList `json:"network,omitempty"` } type WireGuardPeer struct { ServerOptions PublicKey string `json:"public_key,omitempty"` PreSharedKey string `json:"pre_shared_key,omitempty"` AllowedIPs Listable[string] `json:"allowed_ips,omitempty"` Reserved []uint8 `json:"reserved,omitempty"` }
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/option/trojan.go
Bcore/windows/resources/sing-box-main/option/trojan.go
package option type TrojanInboundOptions struct { ListenOptions Users []TrojanUser `json:"users,omitempty"` InboundTLSOptionsContainer Fallback *ServerOptions `json:"fallback,omitempty"` FallbackForALPN map[string]*ServerOptions `json:"fallback_for_alpn,omitempty"` Multiplex *InboundMultiplexOptions `json:"multiplex,omitempty"` Transport *V2RayTransportOptions `json:"transport,omitempty"` } type TrojanUser struct { Name string `json:"name"` Password string `json:"password"` } type TrojanOutboundOptions struct { DialerOptions ServerOptions Password string `json:"password"` Network NetworkList `json:"network,omitempty"` OutboundTLSOptionsContainer Multiplex *OutboundMultiplexOptions `json:"multiplex,omitempty"` Transport *V2RayTransportOptions `json:"transport,omitempty"` }
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/option/tuic.go
Bcore/windows/resources/sing-box-main/option/tuic.go
package option type TUICInboundOptions struct { ListenOptions Users []TUICUser `json:"users,omitempty"` CongestionControl string `json:"congestion_control,omitempty"` AuthTimeout Duration `json:"auth_timeout,omitempty"` ZeroRTTHandshake bool `json:"zero_rtt_handshake,omitempty"` Heartbeat Duration `json:"heartbeat,omitempty"` InboundTLSOptionsContainer } type TUICUser struct { Name string `json:"name,omitempty"` UUID string `json:"uuid,omitempty"` Password string `json:"password,omitempty"` } type TUICOutboundOptions struct { DialerOptions ServerOptions UUID string `json:"uuid,omitempty"` Password string `json:"password,omitempty"` CongestionControl string `json:"congestion_control,omitempty"` UDPRelayMode string `json:"udp_relay_mode,omitempty"` UDPOverStream bool `json:"udp_over_stream,omitempty"` ZeroRTTHandshake bool `json:"zero_rtt_handshake,omitempty"` Heartbeat Duration `json:"heartbeat,omitempty"` Network NetworkList `json:"network,omitempty"` OutboundTLSOptionsContainer }
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/option/tor.go
Bcore/windows/resources/sing-box-main/option/tor.go
package option type TorOutboundOptions struct { DialerOptions ExecutablePath string `json:"executable_path,omitempty"` ExtraArgs []string `json:"extra_args,omitempty"` DataDirectory string `json:"data_directory,omitempty"` Options map[string]string `json:"torrc,omitempty"` }
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/option/rule.go
Bcore/windows/resources/sing-box-main/option/rule.go
package option import ( "reflect" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" ) type _Rule struct { Type string `json:"type,omitempty"` DefaultOptions DefaultRule `json:"-"` LogicalOptions LogicalRule `json:"-"` } type Rule _Rule func (r Rule) MarshalJSON() ([]byte, error) { var v any switch r.Type { case C.RuleTypeDefault: r.Type = "" v = r.DefaultOptions case C.RuleTypeLogical: v = r.LogicalOptions default: return nil, E.New("unknown rule type: " + r.Type) } return MarshallObjects((_Rule)(r), v) } func (r *Rule) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_Rule)(r)) if err != nil { return err } var v any switch r.Type { case "", C.RuleTypeDefault: r.Type = C.RuleTypeDefault v = &r.DefaultOptions case C.RuleTypeLogical: v = &r.LogicalOptions default: return E.New("unknown rule type: " + r.Type) } err = UnmarshallExcluded(bytes, (*_Rule)(r), v) if err != nil { return err } return nil } func (r Rule) IsValid() bool { switch r.Type { case C.RuleTypeDefault: return r.DefaultOptions.IsValid() case C.RuleTypeLogical: return r.LogicalOptions.IsValid() default: panic("unknown rule type: " + r.Type) } } type _DefaultRule struct { Inbound Listable[string] `json:"inbound,omitempty"` IPVersion int `json:"ip_version,omitempty"` Network Listable[string] `json:"network,omitempty"` AuthUser Listable[string] `json:"auth_user,omitempty"` Protocol Listable[string] `json:"protocol,omitempty"` Client Listable[string] `json:"client,omitempty"` Domain Listable[string] `json:"domain,omitempty"` DomainSuffix Listable[string] `json:"domain_suffix,omitempty"` DomainKeyword Listable[string] `json:"domain_keyword,omitempty"` DomainRegex Listable[string] `json:"domain_regex,omitempty"` Geosite Listable[string] `json:"geosite,omitempty"` SourceGeoIP Listable[string] `json:"source_geoip,omitempty"` GeoIP Listable[string] `json:"geoip,omitempty"` SourceIPCIDR Listable[string] `json:"source_ip_cidr,omitempty"` SourceIPIsPrivate bool `json:"source_ip_is_private,omitempty"` IPCIDR Listable[string] `json:"ip_cidr,omitempty"` IPIsPrivate bool `json:"ip_is_private,omitempty"` SourcePort Listable[uint16] `json:"source_port,omitempty"` SourcePortRange Listable[string] `json:"source_port_range,omitempty"` Port Listable[uint16] `json:"port,omitempty"` PortRange Listable[string] `json:"port_range,omitempty"` ProcessName Listable[string] `json:"process_name,omitempty"` ProcessPath Listable[string] `json:"process_path,omitempty"` ProcessPathRegex Listable[string] `json:"process_path_regex,omitempty"` PackageName Listable[string] `json:"package_name,omitempty"` User Listable[string] `json:"user,omitempty"` UserID Listable[int32] `json:"user_id,omitempty"` ClashMode string `json:"clash_mode,omitempty"` WIFISSID Listable[string] `json:"wifi_ssid,omitempty"` WIFIBSSID Listable[string] `json:"wifi_bssid,omitempty"` RuleSet Listable[string] `json:"rule_set,omitempty"` RuleSetIPCIDRMatchSource bool `json:"rule_set_ip_cidr_match_source,omitempty"` Invert bool `json:"invert,omitempty"` Outbound string `json:"outbound,omitempty"` // Deprecated: renamed to rule_set_ip_cidr_match_source Deprecated_RulesetIPCIDRMatchSource bool `json:"rule_set_ipcidr_match_source,omitempty"` } type DefaultRule _DefaultRule func (r *DefaultRule) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_DefaultRule)(r)) if err != nil { return err } //nolint:staticcheck //goland:noinspection GoDeprecation if r.Deprecated_RulesetIPCIDRMatchSource { r.Deprecated_RulesetIPCIDRMatchSource = false r.RuleSetIPCIDRMatchSource = true } return nil } func (r *DefaultRule) IsValid() bool { var defaultValue DefaultRule defaultValue.Invert = r.Invert defaultValue.Outbound = r.Outbound return !reflect.DeepEqual(r, defaultValue) } type LogicalRule struct { Mode string `json:"mode"` Rules []Rule `json:"rules,omitempty"` Invert bool `json:"invert,omitempty"` Outbound string `json:"outbound,omitempty"` } func (r LogicalRule) IsValid() bool { return len(r.Rules) > 0 && common.All(r.Rules, Rule.IsValid) }
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/option/tun.go
Bcore/windows/resources/sing-box-main/option/tun.go
package option import ( "net/netip" "strconv" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" "github.com/sagernet/sing/common/json" ) type TunInboundOptions struct { InterfaceName string `json:"interface_name,omitempty"` MTU uint32 `json:"mtu,omitempty"` GSO bool `json:"gso,omitempty"` Address Listable[netip.Prefix] `json:"address,omitempty"` AutoRoute bool `json:"auto_route,omitempty"` IPRoute2TableIndex int `json:"iproute2_table_index,omitempty"` IPRoute2RuleIndex int `json:"iproute2_rule_index,omitempty"` AutoRedirect bool `json:"auto_redirect,omitempty"` AutoRedirectInputMark FwMark `json:"auto_redirect_input_mark,omitempty"` AutoRedirectOutputMark FwMark `json:"auto_redirect_output_mark,omitempty"` StrictRoute bool `json:"strict_route,omitempty"` RouteAddress Listable[netip.Prefix] `json:"route_address,omitempty"` RouteAddressSet Listable[string] `json:"route_address_set,omitempty"` RouteExcludeAddress Listable[netip.Prefix] `json:"route_exclude_address,omitempty"` RouteExcludeAddressSet Listable[string] `json:"route_exclude_address_set,omitempty"` IncludeInterface Listable[string] `json:"include_interface,omitempty"` ExcludeInterface Listable[string] `json:"exclude_interface,omitempty"` IncludeUID Listable[uint32] `json:"include_uid,omitempty"` IncludeUIDRange Listable[string] `json:"include_uid_range,omitempty"` ExcludeUID Listable[uint32] `json:"exclude_uid,omitempty"` ExcludeUIDRange Listable[string] `json:"exclude_uid_range,omitempty"` IncludeAndroidUser Listable[int] `json:"include_android_user,omitempty"` IncludePackage Listable[string] `json:"include_package,omitempty"` ExcludePackage Listable[string] `json:"exclude_package,omitempty"` EndpointIndependentNat bool `json:"endpoint_independent_nat,omitempty"` UDPTimeout UDPTimeoutCompat `json:"udp_timeout,omitempty"` Stack string `json:"stack,omitempty"` Platform *TunPlatformOptions `json:"platform,omitempty"` InboundOptions // Deprecated: merged to Address Inet4Address Listable[netip.Prefix] `json:"inet4_address,omitempty"` // Deprecated: merged to Address Inet6Address Listable[netip.Prefix] `json:"inet6_address,omitempty"` // Deprecated: merged to RouteAddress Inet4RouteAddress Listable[netip.Prefix] `json:"inet4_route_address,omitempty"` // Deprecated: merged to RouteAddress Inet6RouteAddress Listable[netip.Prefix] `json:"inet6_route_address,omitempty"` // Deprecated: merged to RouteExcludeAddress Inet4RouteExcludeAddress Listable[netip.Prefix] `json:"inet4_route_exclude_address,omitempty"` // Deprecated: merged to RouteExcludeAddress Inet6RouteExcludeAddress Listable[netip.Prefix] `json:"inet6_route_exclude_address,omitempty"` } type FwMark uint32 func (f FwMark) MarshalJSON() ([]byte, error) { return json.Marshal(F.ToString("0x", strconv.FormatUint(uint64(f), 16))) } func (f *FwMark) UnmarshalJSON(bytes []byte) error { var stringValue string err := json.Unmarshal(bytes, &stringValue) if err != nil { if rawErr := json.Unmarshal(bytes, (*uint32)(f)); rawErr == nil { return nil } return E.Cause(err, "invalid number or string mark") } intValue, err := strconv.ParseUint(stringValue, 0, 32) if err != nil { return err } *f = FwMark(intValue) 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/option/rule_dns.go
Bcore/windows/resources/sing-box-main/option/rule_dns.go
package option import ( "reflect" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/json" ) type _DNSRule struct { Type string `json:"type,omitempty"` DefaultOptions DefaultDNSRule `json:"-"` LogicalOptions LogicalDNSRule `json:"-"` } type DNSRule _DNSRule func (r DNSRule) MarshalJSON() ([]byte, error) { var v any switch r.Type { case C.RuleTypeDefault: r.Type = "" v = r.DefaultOptions case C.RuleTypeLogical: v = r.LogicalOptions default: return nil, E.New("unknown rule type: " + r.Type) } return MarshallObjects((_DNSRule)(r), v) } func (r *DNSRule) UnmarshalJSON(bytes []byte) error { err := json.Unmarshal(bytes, (*_DNSRule)(r)) if err != nil { return err } var v any switch r.Type { case "", C.RuleTypeDefault: r.Type = C.RuleTypeDefault v = &r.DefaultOptions case C.RuleTypeLogical: v = &r.LogicalOptions default: return E.New("unknown rule type: " + r.Type) } err = UnmarshallExcluded(bytes, (*_DNSRule)(r), v) if err != nil { return err } return nil } func (r DNSRule) IsValid() bool { switch r.Type { case C.RuleTypeDefault: return r.DefaultOptions.IsValid() case C.RuleTypeLogical: return r.LogicalOptions.IsValid() default: panic("unknown DNS rule type: " + r.Type) } } type _DefaultDNSRule struct { Inbound Listable[string] `json:"inbound,omitempty"` IPVersion int `json:"ip_version,omitempty"` QueryType Listable[DNSQueryType] `json:"query_type,omitempty"` Network Listable[string] `json:"network,omitempty"` AuthUser Listable[string] `json:"auth_user,omitempty"` Protocol Listable[string] `json:"protocol,omitempty"` Domain Listable[string] `json:"domain,omitempty"` DomainSuffix Listable[string] `json:"domain_suffix,omitempty"` DomainKeyword Listable[string] `json:"domain_keyword,omitempty"` DomainRegex Listable[string] `json:"domain_regex,omitempty"` Geosite Listable[string] `json:"geosite,omitempty"` SourceGeoIP Listable[string] `json:"source_geoip,omitempty"` GeoIP Listable[string] `json:"geoip,omitempty"` IPCIDR Listable[string] `json:"ip_cidr,omitempty"` IPIsPrivate bool `json:"ip_is_private,omitempty"` SourceIPCIDR Listable[string] `json:"source_ip_cidr,omitempty"` SourceIPIsPrivate bool `json:"source_ip_is_private,omitempty"` SourcePort Listable[uint16] `json:"source_port,omitempty"` SourcePortRange Listable[string] `json:"source_port_range,omitempty"` Port Listable[uint16] `json:"port,omitempty"` PortRange Listable[string] `json:"port_range,omitempty"` ProcessName Listable[string] `json:"process_name,omitempty"` ProcessPath Listable[string] `json:"process_path,omitempty"` ProcessPathRegex Listable[string] `json:"process_path_regex,omitempty"` PackageName Listable[string] `json:"package_name,omitempty"` User Listable[string] `json:"user,omitempty"` UserID Listable[int32] `json:"user_id,omitempty"` Outbound Listable[string] `json:"outbound,omitempty"` ClashMode string `json:"clash_mode,omitempty"` WIFISSID Listable[string] `json:"wifi_ssid,omitempty"` WIFIBSSID Listable[string] `json:"wifi_bssid,omitempty"` RuleSet Listable[string] `json:"rule_set,omitempty"` RuleSetIPCIDRMatchSource bool `json:"rule_set_ip_cidr_match_source,omitempty"` RuleSetIPCIDRAcceptEmpty bool `json:"rule_set_ip_cidr_accept_empty,omitempty"` Invert bool `json:"invert,omitempty"` Server string `json:"server,omitempty"` DisableCache bool `json:"disable_cache,omitempty"` RewriteTTL *uint32 `json:"rewrite_ttl,omitempty"` ClientSubnet *AddrPrefix `json:"client_subnet,omitempty"` // Deprecated: renamed to rule_set_ip_cidr_match_source Deprecated_RulesetIPCIDRMatchSource bool `json:"rule_set_ipcidr_match_source,omitempty"` } type DefaultDNSRule _DefaultDNSRule func (r *DefaultDNSRule) UnmarshalJSON(bytes []byte) error { err := json.UnmarshalDisallowUnknownFields(bytes, (*_DefaultDNSRule)(r)) if err != nil { return err } //nolint:staticcheck //goland:noinspection GoDeprecation if r.Deprecated_RulesetIPCIDRMatchSource { r.Deprecated_RulesetIPCIDRMatchSource = false r.RuleSetIPCIDRMatchSource = true } return nil } func (r *DefaultDNSRule) IsValid() bool { var defaultValue DefaultDNSRule defaultValue.Invert = r.Invert defaultValue.Server = r.Server defaultValue.DisableCache = r.DisableCache defaultValue.RewriteTTL = r.RewriteTTL defaultValue.ClientSubnet = r.ClientSubnet return !reflect.DeepEqual(r, defaultValue) } type LogicalDNSRule struct { Mode string `json:"mode"` Rules []DNSRule `json:"rules,omitempty"` Invert bool `json:"invert,omitempty"` Server string `json:"server,omitempty"` DisableCache bool `json:"disable_cache,omitempty"` RewriteTTL *uint32 `json:"rewrite_ttl,omitempty"` ClientSubnet *AddrPrefix `json:"client_subnet,omitempty"` } func (r LogicalDNSRule) IsValid() bool { return len(r.Rules) > 0 && common.All(r.Rules, DNSRule.IsValid) }
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/option/direct.go
Bcore/windows/resources/sing-box-main/option/direct.go
package option type DirectInboundOptions struct { ListenOptions Network NetworkList `json:"network,omitempty"` OverrideAddress string `json:"override_address,omitempty"` OverridePort uint16 `json:"override_port,omitempty"` } type DirectOutboundOptions struct { DialerOptions OverrideAddress string `json:"override_address,omitempty"` OverridePort uint16 `json:"override_port,omitempty"` ProxyProtocol uint8 `json:"proxy_protocol,omitempty"` }
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/option/route.go
Bcore/windows/resources/sing-box-main/option/route.go
package option type RouteOptions struct { GeoIP *GeoIPOptions `json:"geoip,omitempty"` Geosite *GeositeOptions `json:"geosite,omitempty"` Rules []Rule `json:"rules,omitempty"` RuleSet []RuleSet `json:"rule_set,omitempty"` Final string `json:"final,omitempty"` FindProcess bool `json:"find_process,omitempty"` AutoDetectInterface bool `json:"auto_detect_interface,omitempty"` OverrideAndroidVPN bool `json:"override_android_vpn,omitempty"` DefaultInterface string `json:"default_interface,omitempty"` DefaultMark uint32 `json:"default_mark,omitempty"` } type GeoIPOptions struct { Path string `json:"path,omitempty"` DownloadURL string `json:"download_url,omitempty"` DownloadDetour string `json:"download_detour,omitempty"` } type GeositeOptions struct { Path string `json:"path,omitempty"` DownloadURL string `json:"download_url,omitempty"` DownloadDetour string `json:"download_detour,omitempty"` }
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/option/tls.go
Bcore/windows/resources/sing-box-main/option/tls.go
package option type InboundTLSOptions struct { Enabled bool `json:"enabled,omitempty"` ServerName string `json:"server_name,omitempty"` Insecure bool `json:"insecure,omitempty"` ALPN Listable[string] `json:"alpn,omitempty"` MinVersion string `json:"min_version,omitempty"` MaxVersion string `json:"max_version,omitempty"` CipherSuites Listable[string] `json:"cipher_suites,omitempty"` Certificate Listable[string] `json:"certificate,omitempty"` CertificatePath string `json:"certificate_path,omitempty"` Key Listable[string] `json:"key,omitempty"` KeyPath string `json:"key_path,omitempty"` ACME *InboundACMEOptions `json:"acme,omitempty"` ECH *InboundECHOptions `json:"ech,omitempty"` Reality *InboundRealityOptions `json:"reality,omitempty"` } type InboundTLSOptionsContainer struct { TLS *InboundTLSOptions `json:"tls,omitempty"` } type InboundTLSOptionsWrapper interface { TakeInboundTLSOptions() *InboundTLSOptions ReplaceInboundTLSOptions(options *InboundTLSOptions) } func (o *InboundTLSOptionsContainer) TakeInboundTLSOptions() *InboundTLSOptions { return o.TLS } func (o *InboundTLSOptionsContainer) ReplaceInboundTLSOptions(options *InboundTLSOptions) { o.TLS = options } type OutboundTLSOptions struct { Enabled bool `json:"enabled,omitempty"` DisableSNI bool `json:"disable_sni,omitempty"` ServerName string `json:"server_name,omitempty"` Insecure bool `json:"insecure,omitempty"` ALPN Listable[string] `json:"alpn,omitempty"` MinVersion string `json:"min_version,omitempty"` MaxVersion string `json:"max_version,omitempty"` CipherSuites Listable[string] `json:"cipher_suites,omitempty"` Certificate Listable[string] `json:"certificate,omitempty"` CertificatePath string `json:"certificate_path,omitempty"` ECH *OutboundECHOptions `json:"ech,omitempty"` UTLS *OutboundUTLSOptions `json:"utls,omitempty"` Reality *OutboundRealityOptions `json:"reality,omitempty"` } type OutboundTLSOptionsContainer struct { TLS *OutboundTLSOptions `json:"tls,omitempty"` } type OutboundTLSOptionsWrapper interface { TakeOutboundTLSOptions() *OutboundTLSOptions ReplaceOutboundTLSOptions(options *OutboundTLSOptions) } func (o *OutboundTLSOptionsContainer) TakeOutboundTLSOptions() *OutboundTLSOptions { return o.TLS } func (o *OutboundTLSOptionsContainer) ReplaceOutboundTLSOptions(options *OutboundTLSOptions) { o.TLS = options } type InboundRealityOptions struct { Enabled bool `json:"enabled,omitempty"` Handshake InboundRealityHandshakeOptions `json:"handshake,omitempty"` PrivateKey string `json:"private_key,omitempty"` ShortID Listable[string] `json:"short_id,omitempty"` MaxTimeDifference Duration `json:"max_time_difference,omitempty"` } type InboundRealityHandshakeOptions struct { ServerOptions DialerOptions } type InboundECHOptions struct { Enabled bool `json:"enabled,omitempty"` PQSignatureSchemesEnabled bool `json:"pq_signature_schemes_enabled,omitempty"` DynamicRecordSizingDisabled bool `json:"dynamic_record_sizing_disabled,omitempty"` Key Listable[string] `json:"key,omitempty"` KeyPath string `json:"key_path,omitempty"` } type OutboundECHOptions struct { Enabled bool `json:"enabled,omitempty"` PQSignatureSchemesEnabled bool `json:"pq_signature_schemes_enabled,omitempty"` DynamicRecordSizingDisabled bool `json:"dynamic_record_sizing_disabled,omitempty"` Config Listable[string] `json:"config,omitempty"` ConfigPath string `json:"config_path,omitempty"` } type OutboundUTLSOptions struct { Enabled bool `json:"enabled,omitempty"` Fingerprint string `json:"fingerprint,omitempty"` } type OutboundRealityOptions struct { Enabled bool `json:"enabled,omitempty"` PublicKey string `json:"public_key,omitempty"` ShortID string `json:"short_id,omitempty"` }
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/option/hysteria2.go
Bcore/windows/resources/sing-box-main/option/hysteria2.go
package option type Hysteria2InboundOptions struct { ListenOptions UpMbps int `json:"up_mbps,omitempty"` DownMbps int `json:"down_mbps,omitempty"` Obfs *Hysteria2Obfs `json:"obfs,omitempty"` Users []Hysteria2User `json:"users,omitempty"` IgnoreClientBandwidth bool `json:"ignore_client_bandwidth,omitempty"` InboundTLSOptionsContainer Masquerade string `json:"masquerade,omitempty"` BrutalDebug bool `json:"brutal_debug,omitempty"` } type Hysteria2Obfs struct { Type string `json:"type,omitempty"` Password string `json:"password,omitempty"` } type Hysteria2User struct { Name string `json:"name,omitempty"` Password string `json:"password,omitempty"` } type Hysteria2OutboundOptions struct { DialerOptions ServerOptions UpMbps int `json:"up_mbps,omitempty"` DownMbps int `json:"down_mbps,omitempty"` Obfs *Hysteria2Obfs `json:"obfs,omitempty"` Password string `json:"password,omitempty"` Network NetworkList `json:"network,omitempty"` OutboundTLSOptionsContainer BrutalDebug bool `json:"brutal_debug,omitempty"` }
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/include/tz_ios.go
Bcore/windows/resources/sing-box-main/include/tz_ios.go
package include /* #cgo CFLAGS: -x objective-c #cgo LDFLAGS: -framework Foundation #import <Foundation/Foundation.h> const char* getSystemTimeZone() { NSTimeZone *timeZone = [NSTimeZone systemTimeZone]; NSString *timeZoneName = [timeZone description]; return [timeZoneName UTF8String]; } */ import "C" import ( "strings" "time" ) func init() { tzDescription := C.GoString(C.getSystemTimeZone()) if len(tzDescription) == 0 { return } location, err := time.LoadLocation(strings.Split(tzDescription, " ")[0]) if err != nil { return } time.Local = location }
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/include/tz_android.go
Bcore/windows/resources/sing-box-main/include/tz_android.go
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // kanged from https://github.com/golang/mobile/blob/c713f31d574bb632a93f169b2cc99c9e753fef0e/app/android.go#L89 package include // #include <time.h> import "C" import "time" func init() { var currentT C.time_t var currentTM C.struct_tm C.time(&currentT) C.localtime_r(&currentT, &currentTM) tzOffset := int(currentTM.tm_gmtoff) tz := C.GoString(currentTM.tm_zone) time.Local = time.FixedZone(tz, tzOffset) }
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/include/dhcp_stub.go
Bcore/windows/resources/sing-box-main/include/dhcp_stub.go
//go:build !with_dhcp package include import ( "github.com/sagernet/sing-dns" E "github.com/sagernet/sing/common/exceptions" ) func init() { dns.RegisterTransport([]string{"dhcp"}, func(options dns.TransportOptions) (dns.Transport, error) { return nil, E.New(`DHCP is not included in this build, rebuild with -tags with_dhcp`) }) }
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/include/v2rayapi_stub.go
Bcore/windows/resources/sing-box-main/include/v2rayapi_stub.go
//go:build !with_v2ray_api package include import ( "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/experimental" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) func init() { experimental.RegisterV2RayServerConstructor(func(logger log.Logger, options option.V2RayAPIOptions) (adapter.V2RayServer, error) { return nil, E.New(`v2ray api is not included in this build, rebuild with -tags with_v2ray_api`) }) }
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/include/clashapi_stub.go
Bcore/windows/resources/sing-box-main/include/clashapi_stub.go
//go:build !with_clash_api package include import ( "context" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/experimental" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) func init() { experimental.RegisterClashServerConstructor(func(ctx context.Context, router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) { return nil, E.New(`clash api is not included in this build, rebuild with -tags with_clash_api`) }) }
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/include/quic.go
Bcore/windows/resources/sing-box-main/include/quic.go
//go:build with_quic package include import ( _ "github.com/sagernet/sing-box/transport/v2rayquic" _ "github.com/sagernet/sing-dns/quic" )
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/include/clashapi.go
Bcore/windows/resources/sing-box-main/include/clashapi.go
//go:build with_clash_api package include import _ "github.com/sagernet/sing-box/experimental/clashapi"
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/include/dhcp.go
Bcore/windows/resources/sing-box-main/include/dhcp.go
//go:build with_dhcp package include import _ "github.com/sagernet/sing-box/transport/dhcp"
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/include/v2rayapi.go
Bcore/windows/resources/sing-box-main/include/v2rayapi.go
//go:build with_v2ray_api package include import _ "github.com/sagernet/sing-box/experimental/v2rayapi"
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/include/quic_stub.go
Bcore/windows/resources/sing-box-main/include/quic_stub.go
//go:build !with_quic package include import ( "context" "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-box/transport/v2ray" "github.com/sagernet/sing-dns" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) func init() { dns.RegisterTransport([]string{"quic", "h3"}, func(options dns.TransportOptions) (dns.Transport, error) { return nil, C.ErrQUICNotIncluded }) v2ray.RegisterQUICConstructor( func(ctx context.Context, options option.V2RayQUICOptions, tlsConfig tls.ServerConfig, handler adapter.V2RayServerTransportHandler) (adapter.V2RayServerTransport, error) { return nil, C.ErrQUICNotIncluded }, func(ctx context.Context, dialer N.Dialer, serverAddr M.Socksaddr, options option.V2RayQUICOptions, tlsConfig tls.Config) (adapter.V2RayClientTransport, 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/common/process/searcher_stub.go
Bcore/windows/resources/sing-box-main/common/process/searcher_stub.go
//go:build !linux && !windows && !darwin package process import ( "os" ) func NewSearcher(_ Config) (Searcher, 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/common/process/searcher.go
Bcore/windows/resources/sing-box-main/common/process/searcher.go
package process import ( "context" "net/netip" "os/user" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-tun" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" ) type Searcher interface { FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) } var ErrNotFound = E.New("process not found") type Config struct { Logger log.ContextLogger PackageManager tun.PackageManager } type Info struct { ProcessPath string PackageName string User string UserId int32 } func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { info, err := searcher.FindProcessInfo(ctx, network, source, destination) if err != nil { return nil, err } if info.UserId != -1 { osUser, _ := user.LookupId(F.ToString(info.UserId)) if osUser != nil { info.User = osUser.Username } } return info, 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/common/process/searcher_windows.go
Bcore/windows/resources/sing-box-main/common/process/searcher_windows.go
package process import ( "context" "fmt" "net/netip" "os" "syscall" "unsafe" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" "golang.org/x/sys/windows" ) var _ Searcher = (*windowsSearcher)(nil) type windowsSearcher struct{} func NewSearcher(_ Config) (Searcher, error) { err := initWin32API() if err != nil { return nil, E.Cause(err, "init win32 api") } return &windowsSearcher{}, nil } var ( modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll") procGetExtendedTcpTable = modiphlpapi.NewProc("GetExtendedTcpTable") procGetExtendedUdpTable = modiphlpapi.NewProc("GetExtendedUdpTable") modkernel32 = windows.NewLazySystemDLL("kernel32.dll") procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW") ) func initWin32API() error { err := modiphlpapi.Load() if err != nil { return E.Cause(err, "load iphlpapi.dll") } err = procGetExtendedTcpTable.Find() if err != nil { return E.Cause(err, "load iphlpapi::GetExtendedTcpTable") } err = procGetExtendedUdpTable.Find() if err != nil { return E.Cause(err, "load iphlpapi::GetExtendedUdpTable") } err = modkernel32.Load() if err != nil { return E.Cause(err, "load kernel32.dll") } err = procQueryFullProcessImageNameW.Find() if err != nil { return E.Cause(err, "load kernel32::QueryFullProcessImageNameW") } return nil } func (s *windowsSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { processName, err := findProcessName(network, source.Addr(), int(source.Port())) if err != nil { return nil, err } return &Info{ProcessPath: processName, UserId: -1}, nil } func findProcessName(network string, ip netip.Addr, srcPort int) (string, error) { family := windows.AF_INET if ip.Is6() { family = windows.AF_INET6 } const ( tcpTablePidConn = 4 udpTablePid = 1 ) var class int var fn uintptr switch network { case N.NetworkTCP: fn = procGetExtendedTcpTable.Addr() class = tcpTablePidConn case N.NetworkUDP: fn = procGetExtendedUdpTable.Addr() class = udpTablePid default: return "", os.ErrInvalid } buf, err := getTransportTable(fn, family, class) if err != nil { return "", err } s := newSearcher(family == windows.AF_INET, network == N.NetworkTCP) pid, err := s.Search(buf, ip, uint16(srcPort)) if err != nil { return "", err } return getExecPathFromPID(pid) } type searcher struct { itemSize int port int ip int ipSize int pid int tcpState int } func (s *searcher) Search(b []byte, ip netip.Addr, port uint16) (uint32, error) { n := int(readNativeUint32(b[:4])) itemSize := s.itemSize for i := 0; i < n; i++ { row := b[4+itemSize*i : 4+itemSize*(i+1)] if s.tcpState >= 0 { tcpState := readNativeUint32(row[s.tcpState : s.tcpState+4]) // MIB_TCP_STATE_ESTAB, only check established connections for TCP if tcpState != 5 { continue } } // according to MSDN, only the lower 16 bits of dwLocalPort are used and the port number is in network endian. // this field can be illustrated as follows depends on different machine endianess: // little endian: [ MSB LSB 0 0 ] interpret as native uint32 is ((LSB<<8)|MSB) // big endian: [ 0 0 MSB LSB ] interpret as native uint32 is ((MSB<<8)|LSB) // so we need an syscall.Ntohs on the lower 16 bits after read the port as native uint32 srcPort := syscall.Ntohs(uint16(readNativeUint32(row[s.port : s.port+4]))) if srcPort != port { continue } srcIP, _ := netip.AddrFromSlice(row[s.ip : s.ip+s.ipSize]) // windows binds an unbound udp socket to 0.0.0.0/[::] while first sendto if ip != srcIP && (!srcIP.IsUnspecified() || s.tcpState != -1) { continue } pid := readNativeUint32(row[s.pid : s.pid+4]) return pid, nil } return 0, ErrNotFound } func newSearcher(isV4, isTCP bool) *searcher { var itemSize, port, ip, ipSize, pid int tcpState := -1 switch { case isV4 && isTCP: // struct MIB_TCPROW_OWNER_PID itemSize, port, ip, ipSize, pid, tcpState = 24, 8, 4, 4, 20, 0 case isV4 && !isTCP: // struct MIB_UDPROW_OWNER_PID itemSize, port, ip, ipSize, pid = 12, 4, 0, 4, 8 case !isV4 && isTCP: // struct MIB_TCP6ROW_OWNER_PID itemSize, port, ip, ipSize, pid, tcpState = 56, 20, 0, 16, 52, 48 case !isV4 && !isTCP: // struct MIB_UDP6ROW_OWNER_PID itemSize, port, ip, ipSize, pid = 28, 20, 0, 16, 24 } return &searcher{ itemSize: itemSize, port: port, ip: ip, ipSize: ipSize, pid: pid, tcpState: tcpState, } } func getTransportTable(fn uintptr, family int, class int) ([]byte, error) { for size, buf := uint32(8), make([]byte, 8); ; { ptr := unsafe.Pointer(&buf[0]) err, _, _ := syscall.SyscallN(fn, uintptr(ptr), uintptr(unsafe.Pointer(&size)), 0, uintptr(family), uintptr(class), 0) switch err { case 0: return buf, nil case uintptr(syscall.ERROR_INSUFFICIENT_BUFFER): buf = make([]byte, size) default: return nil, fmt.Errorf("syscall error: %d", err) } } } func readNativeUint32(b []byte) uint32 { return *(*uint32)(unsafe.Pointer(&b[0])) } func getExecPathFromPID(pid uint32) (string, error) { // kernel process starts with a colon in order to distinguish with normal processes switch pid { case 0: // reserved pid for system idle process return ":System Idle Process", nil case 4: // reserved pid for windows kernel image return ":System", nil } h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid) if err != nil { return "", err } defer windows.CloseHandle(h) buf := make([]uint16, syscall.MAX_LONG_PATH) size := uint32(len(buf)) r1, _, err := syscall.SyscallN( procQueryFullProcessImageNameW.Addr(), uintptr(h), uintptr(0), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size)), ) if r1 == 0 { return "", err } return syscall.UTF16ToString(buf[:size]), 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/common/process/searcher_android.go
Bcore/windows/resources/sing-box-main/common/process/searcher_android.go
package process import ( "context" "net/netip" "github.com/sagernet/sing-tun" ) var _ Searcher = (*androidSearcher)(nil) type androidSearcher struct { packageManager tun.PackageManager } func NewSearcher(config Config) (Searcher, error) { return &androidSearcher{config.PackageManager}, nil } func (s *androidSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { _, uid, err := resolveSocketByNetlink(network, source, destination) if err != nil { return nil, err } if sharedPackage, loaded := s.packageManager.SharedPackageByID(uid % 100000); loaded { return &Info{ UserId: int32(uid), PackageName: sharedPackage, }, nil } if packageName, loaded := s.packageManager.PackageByID(uid % 100000); loaded { return &Info{ UserId: int32(uid), PackageName: packageName, }, nil } return &Info{UserId: int32(uid)}, 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/common/process/searcher_darwin.go
Bcore/windows/resources/sing-box-main/common/process/searcher_darwin.go
package process import ( "context" "encoding/binary" "net/netip" "os" "strconv" "strings" "syscall" "unsafe" N "github.com/sagernet/sing/common/network" "golang.org/x/sys/unix" ) var _ Searcher = (*darwinSearcher)(nil) type darwinSearcher struct{} func NewSearcher(_ Config) (Searcher, error) { return &darwinSearcher{}, nil } func (d *darwinSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { processName, err := findProcessName(network, source.Addr(), int(source.Port())) if err != nil { return nil, err } return &Info{ProcessPath: processName, UserId: -1}, nil } var structSize = func() int { value, _ := syscall.Sysctl("kern.osrelease") major, _, _ := strings.Cut(value, ".") n, _ := strconv.ParseInt(major, 10, 64) switch true { case n >= 22: return 408 default: // from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n // size/offset are round up (aligned) to 8 bytes in darwin // rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) + // 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n)) return 384 } }() func findProcessName(network string, ip netip.Addr, port int) (string, error) { var spath string switch network { case N.NetworkTCP: spath = "net.inet.tcp.pcblist_n" case N.NetworkUDP: spath = "net.inet.udp.pcblist_n" default: return "", os.ErrInvalid } isIPv4 := ip.Is4() value, err := unix.SysctlRaw(spath) if err != nil { return "", err } buf := value // from darwin-xnu/bsd/netinet/in_pcblist.c:get_pcblist_n // size/offset are round up (aligned) to 8 bytes in darwin // rup8(sizeof(xinpcb_n)) + rup8(sizeof(xsocket_n)) + // 2 * rup8(sizeof(xsockbuf_n)) + rup8(sizeof(xsockstat_n)) itemSize := structSize if network == N.NetworkTCP { // rup8(sizeof(xtcpcb_n)) itemSize += 208 } // skip the first xinpgen(24 bytes) block for i := 24; i+itemSize <= len(buf); i += itemSize { // offset of xinpcb_n and xsocket_n inp, so := i, i+104 srcPort := binary.BigEndian.Uint16(buf[inp+18 : inp+20]) if uint16(port) != srcPort { continue } // xinpcb_n.inp_vflag flag := buf[inp+44] var srcIP netip.Addr switch { case flag&0x1 > 0 && isIPv4: // ipv4 srcIP = netip.AddrFrom4(*(*[4]byte)(buf[inp+76 : inp+80])) case flag&0x2 > 0 && !isIPv4: // ipv6 srcIP = netip.AddrFrom16(*(*[16]byte)(buf[inp+64 : inp+80])) default: continue } if ip != srcIP { continue } // xsocket_n.so_last_pid pid := readNativeUint32(buf[so+68 : so+72]) return getExecPathFromPID(pid) } return "", ErrNotFound } func getExecPathFromPID(pid uint32) (string, error) { const ( procpidpathinfo = 0xb procpidpathinfosize = 1024 proccallnumpidinfo = 0x2 ) buf := make([]byte, procpidpathinfosize) _, _, errno := syscall.Syscall6( syscall.SYS_PROC_INFO, proccallnumpidinfo, uintptr(pid), procpidpathinfo, 0, uintptr(unsafe.Pointer(&buf[0])), procpidpathinfosize) if errno != 0 { return "", errno } return unix.ByteSliceToString(buf), nil } func readNativeUint32(b []byte) uint32 { return *(*uint32)(unsafe.Pointer(&b[0])) }
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/common/process/searcher_linux_shared.go
Bcore/windows/resources/sing-box-main/common/process/searcher_linux_shared.go
//go:build linux package process import ( "bytes" "encoding/binary" "fmt" "net" "net/netip" "os" "path" "strings" "syscall" "unicode" "unsafe" "github.com/sagernet/sing/common/buf" E "github.com/sagernet/sing/common/exceptions" N "github.com/sagernet/sing/common/network" ) // from https://github.com/vishvananda/netlink/blob/bca67dfc8220b44ef582c9da4e9172bf1c9ec973/nl/nl_linux.go#L52-L62 var nativeEndian = func() binary.ByteOrder { var x uint32 = 0x01020304 if *(*byte)(unsafe.Pointer(&x)) == 0x01 { return binary.BigEndian } return binary.LittleEndian }() const ( sizeOfSocketDiagRequest = syscall.SizeofNlMsghdr + 8 + 48 socketDiagByFamily = 20 pathProc = "/proc" ) func resolveSocketByNetlink(network string, source netip.AddrPort, destination netip.AddrPort) (inode, uid uint32, err error) { var family uint8 var protocol uint8 switch network { case N.NetworkTCP: protocol = syscall.IPPROTO_TCP case N.NetworkUDP: protocol = syscall.IPPROTO_UDP default: return 0, 0, os.ErrInvalid } if source.Addr().Is4() { family = syscall.AF_INET } else { family = syscall.AF_INET6 } req := packSocketDiagRequest(family, protocol, source) socket, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_INET_DIAG) if err != nil { return 0, 0, E.Cause(err, "dial netlink") } defer syscall.Close(socket) syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_SNDTIMEO, &syscall.Timeval{Usec: 100}) syscall.SetsockoptTimeval(socket, syscall.SOL_SOCKET, syscall.SO_RCVTIMEO, &syscall.Timeval{Usec: 100}) err = syscall.Connect(socket, &syscall.SockaddrNetlink{ Family: syscall.AF_NETLINK, Pad: 0, Pid: 0, Groups: 0, }) if err != nil { return } _, err = syscall.Write(socket, req) if err != nil { return 0, 0, E.Cause(err, "write netlink request") } buffer := buf.New() defer buffer.Release() n, err := syscall.Read(socket, buffer.FreeBytes()) if err != nil { return 0, 0, E.Cause(err, "read netlink response") } buffer.Truncate(n) messages, err := syscall.ParseNetlinkMessage(buffer.Bytes()) if err != nil { return 0, 0, E.Cause(err, "parse netlink message") } else if len(messages) == 0 { return 0, 0, E.New("unexcepted netlink response") } message := messages[0] if message.Header.Type&syscall.NLMSG_ERROR != 0 { return 0, 0, E.New("netlink message: NLMSG_ERROR") } inode, uid = unpackSocketDiagResponse(&messages[0]) return } func packSocketDiagRequest(family, protocol byte, source netip.AddrPort) []byte { s := make([]byte, 16) copy(s, source.Addr().AsSlice()) buf := make([]byte, sizeOfSocketDiagRequest) nativeEndian.PutUint32(buf[0:4], sizeOfSocketDiagRequest) nativeEndian.PutUint16(buf[4:6], socketDiagByFamily) nativeEndian.PutUint16(buf[6:8], syscall.NLM_F_REQUEST|syscall.NLM_F_DUMP) nativeEndian.PutUint32(buf[8:12], 0) nativeEndian.PutUint32(buf[12:16], 0) buf[16] = family buf[17] = protocol buf[18] = 0 buf[19] = 0 nativeEndian.PutUint32(buf[20:24], 0xFFFFFFFF) binary.BigEndian.PutUint16(buf[24:26], source.Port()) binary.BigEndian.PutUint16(buf[26:28], 0) copy(buf[28:44], s) copy(buf[44:60], net.IPv6zero) nativeEndian.PutUint32(buf[60:64], 0) nativeEndian.PutUint64(buf[64:72], 0xFFFFFFFFFFFFFFFF) return buf } func unpackSocketDiagResponse(msg *syscall.NetlinkMessage) (inode, uid uint32) { if len(msg.Data) < 72 { return 0, 0 } data := msg.Data uid = nativeEndian.Uint32(data[64:68]) inode = nativeEndian.Uint32(data[68:72]) return } func resolveProcessNameByProcSearch(inode, uid uint32) (string, error) { files, err := os.ReadDir(pathProc) if err != nil { return "", err } buffer := make([]byte, syscall.PathMax) socket := []byte(fmt.Sprintf("socket:[%d]", inode)) for _, f := range files { if !f.IsDir() || !isPid(f.Name()) { continue } info, err := f.Info() if err != nil { return "", err } if info.Sys().(*syscall.Stat_t).Uid != uid { continue } processPath := path.Join(pathProc, f.Name()) fdPath := path.Join(processPath, "fd") fds, err := os.ReadDir(fdPath) if err != nil { continue } for _, fd := range fds { n, err := syscall.Readlink(path.Join(fdPath, fd.Name()), buffer) if err != nil { continue } if bytes.Equal(buffer[:n], socket) { return os.Readlink(path.Join(processPath, "exe")) } } } return "", fmt.Errorf("process of uid(%d),inode(%d) not found", uid, inode) } func isPid(s string) bool { return strings.IndexFunc(s, func(r rune) bool { return !unicode.IsDigit(r) }) == -1 }
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/common/process/searcher_linux.go
Bcore/windows/resources/sing-box-main/common/process/searcher_linux.go
//go:build linux && !android package process import ( "context" "net/netip" "github.com/sagernet/sing-box/log" ) var _ Searcher = (*linuxSearcher)(nil) type linuxSearcher struct { logger log.ContextLogger } func NewSearcher(config Config) (Searcher, error) { return &linuxSearcher{config.Logger}, nil } func (s *linuxSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) { inode, uid, err := resolveSocketByNetlink(network, source, destination) if err != nil { return nil, err } processPath, err := resolveProcessNameByProcSearch(inode, uid) if err != nil { s.logger.DebugContext(ctx, "find process path: ", err) } return &Info{ UserId: int32(uid), ProcessPath: processPath, }, 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/common/tls/reality_stub.go
Bcore/windows/resources/sing-box-main/common/tls/reality_stub.go
//go:build !with_reality_server package tls import ( "context" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) func NewRealityServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) { return nil, E.New(`reality server is not included in this build, rebuild with -tags with_reality_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/common/tls/ech_quic.go
Bcore/windows/resources/sing-box-main/common/tls/ech_quic.go
//go:build with_quic && with_ech package tls import ( "context" "net" "net/http" "github.com/sagernet/cloudflare-tls" "github.com/sagernet/quic-go/ech" "github.com/sagernet/quic-go/http3_ech" "github.com/sagernet/sing-quic" M "github.com/sagernet/sing/common/metadata" ) var ( _ qtls.Config = (*echClientConfig)(nil) _ qtls.ServerConfig = (*echServerConfig)(nil) ) func (c *echClientConfig) Dial(ctx context.Context, conn net.PacketConn, addr net.Addr, config *quic.Config) (quic.Connection, error) { return quic.Dial(ctx, conn, addr, c.config, config) } func (c *echClientConfig) DialEarly(ctx context.Context, conn net.PacketConn, addr net.Addr, config *quic.Config) (quic.EarlyConnection, error) { return quic.DialEarly(ctx, conn, addr, c.config, config) } func (c *echClientConfig) CreateTransport(conn net.PacketConn, quicConnPtr *quic.EarlyConnection, serverAddr M.Socksaddr, quicConfig *quic.Config) http.RoundTripper { return &http3.RoundTripper{ TLSClientConfig: c.config, QUICConfig: quicConfig, Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) { quicConn, err := quic.DialEarly(ctx, conn, serverAddr.UDPAddr(), tlsCfg, cfg) if err != nil { return nil, err } *quicConnPtr = quicConn return quicConn, nil }, } } func (c *echServerConfig) Listen(conn net.PacketConn, config *quic.Config) (qtls.Listener, error) { return quic.Listen(conn, c.config, config) } func (c *echServerConfig) ListenEarly(conn net.PacketConn, config *quic.Config) (qtls.EarlyListener, error) { return quic.ListenEarly(conn, c.config, config) } func (c *echServerConfig) ConfigureHTTP3() { http3.ConfigureTLSConfig(c.config) }
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/common/tls/client.go
Bcore/windows/resources/sing-box-main/common/tls/client.go
package tls import ( "context" "net" "os" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/badtls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" aTLS "github.com/sagernet/sing/common/tls" ) func NewDialerFromOptions(ctx context.Context, router adapter.Router, dialer N.Dialer, serverAddress string, options option.OutboundTLSOptions) (N.Dialer, error) { if !options.Enabled { return dialer, nil } config, err := NewClient(ctx, serverAddress, options) if err != nil { return nil, err } return NewDialer(dialer, config), nil } func NewClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) { if !options.Enabled { return nil, nil } if options.ECH != nil && options.ECH.Enabled { return NewECHClient(ctx, serverAddress, options) } else if options.Reality != nil && options.Reality.Enabled { return NewRealityClient(ctx, serverAddress, options) } else if options.UTLS != nil && options.UTLS.Enabled { return NewUTLSClient(ctx, serverAddress, options) } else { return NewSTDClient(ctx, serverAddress, options) } } func ClientHandshake(ctx context.Context, conn net.Conn, config Config) (Conn, error) { ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout) defer cancel() tlsConn, err := aTLS.ClientHandshake(ctx, conn, config) if err != nil { return nil, err } readWaitConn, err := badtls.NewReadWaitConn(tlsConn) if err == nil { return readWaitConn, nil } else if err != os.ErrInvalid { return nil, err } return tlsConn, nil } type Dialer struct { dialer N.Dialer config Config } func NewDialer(dialer N.Dialer, config Config) N.Dialer { return &Dialer{dialer, config} } func (d *Dialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) { if network != N.NetworkTCP { return nil, os.ErrInvalid } conn, err := d.dialer.DialContext(ctx, network, destination) if err != nil { return nil, err } return ClientHandshake(ctx, conn, d.config) } func (d *Dialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, 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/common/tls/ech_keygen.go
Bcore/windows/resources/sing-box-main/common/tls/ech_keygen.go
//go:build with_ech package tls import ( "bytes" "encoding/binary" "encoding/pem" cftls "github.com/sagernet/cloudflare-tls" E "github.com/sagernet/sing/common/exceptions" "github.com/cloudflare/circl/hpke" "github.com/cloudflare/circl/kem" ) func ECHKeygenDefault(serverName string, pqSignatureSchemesEnabled bool) (configPem string, keyPem string, err error) { cipherSuites := []echCipherSuite{ { kdf: hpke.KDF_HKDF_SHA256, aead: hpke.AEAD_AES128GCM, }, { kdf: hpke.KDF_HKDF_SHA256, aead: hpke.AEAD_ChaCha20Poly1305, }, } keyConfig := []myECHKeyConfig{ {id: 0, kem: hpke.KEM_X25519_HKDF_SHA256}, } if pqSignatureSchemesEnabled { keyConfig = append(keyConfig, myECHKeyConfig{id: 1, kem: hpke.KEM_X25519_KYBER768_DRAFT00}) } keyPairs, err := echKeygen(0xfe0d, serverName, keyConfig, cipherSuites) if err != nil { return } var configBuffer bytes.Buffer var totalLen uint16 for _, keyPair := range keyPairs { totalLen += uint16(len(keyPair.rawConf)) } binary.Write(&configBuffer, binary.BigEndian, totalLen) for _, keyPair := range keyPairs { configBuffer.Write(keyPair.rawConf) } var keyBuffer bytes.Buffer for _, keyPair := range keyPairs { keyBuffer.Write(keyPair.rawKey) } configPem = string(pem.EncodeToMemory(&pem.Block{Type: "ECH CONFIGS", Bytes: configBuffer.Bytes()})) keyPem = string(pem.EncodeToMemory(&pem.Block{Type: "ECH KEYS", Bytes: keyBuffer.Bytes()})) return } type echKeyConfigPair struct { id uint8 key cftls.EXP_ECHKey rawKey []byte conf myECHKeyConfig rawConf []byte } type echCipherSuite struct { kdf hpke.KDF aead hpke.AEAD } type myECHKeyConfig struct { id uint8 kem hpke.KEM seed []byte } func echKeygen(version uint16, serverName string, conf []myECHKeyConfig, suite []echCipherSuite) ([]echKeyConfigPair, error) { be := binary.BigEndian // prepare for future update if version != 0xfe0d { return nil, E.New("unsupported ECH version", version) } suiteBuf := make([]byte, 0, len(suite)*4+2) suiteBuf = be.AppendUint16(suiteBuf, uint16(len(suite))*4) for _, s := range suite { if !s.kdf.IsValid() || !s.aead.IsValid() { return nil, E.New("invalid HPKE cipher suite") } suiteBuf = be.AppendUint16(suiteBuf, uint16(s.kdf)) suiteBuf = be.AppendUint16(suiteBuf, uint16(s.aead)) } pairs := []echKeyConfigPair{} for _, c := range conf { pair := echKeyConfigPair{} pair.id = c.id pair.conf = c if !c.kem.IsValid() { return nil, E.New("invalid HPKE KEM") } kpGenerator := c.kem.Scheme().GenerateKeyPair if len(c.seed) > 0 { kpGenerator = func() (kem.PublicKey, kem.PrivateKey, error) { pub, sec := c.kem.Scheme().DeriveKeyPair(c.seed) return pub, sec, nil } if len(c.seed) < c.kem.Scheme().PrivateKeySize() { return nil, E.New("HPKE KEM seed too short") } } pub, sec, err := kpGenerator() if err != nil { return nil, E.Cause(err, "generate ECH config key pair") } b := []byte{} b = be.AppendUint16(b, version) b = be.AppendUint16(b, 0) // length field // contents // key config b = append(b, c.id) b = be.AppendUint16(b, uint16(c.kem)) pubBuf, err := pub.MarshalBinary() if err != nil { return nil, E.Cause(err, "serialize ECH public key") } b = be.AppendUint16(b, uint16(len(pubBuf))) b = append(b, pubBuf...) b = append(b, suiteBuf...) // end key config // max name len, not supported b = append(b, 0) // server name b = append(b, byte(len(serverName))) b = append(b, []byte(serverName)...) // extensions, not supported b = be.AppendUint16(b, 0) be.PutUint16(b[2:], uint16(len(b)-4)) pair.rawConf = b secBuf, err := sec.MarshalBinary() sk := []byte{} sk = be.AppendUint16(sk, uint16(len(secBuf))) sk = append(sk, secBuf...) sk = be.AppendUint16(sk, uint16(len(b))) sk = append(sk, b...) cfECHKeys, err := cftls.EXP_UnmarshalECHKeys(sk) if err != nil { return nil, E.Cause(err, "bug: can't parse generated ECH server key") } if len(cfECHKeys) != 1 { return nil, E.New("bug: unexpected server key count") } pair.key = cfECHKeys[0] pair.rawKey = sk pairs = append(pairs, pair) } return pairs, 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/common/tls/acme_stub.go
Bcore/windows/resources/sing-box-main/common/tls/acme_stub.go
//go:build !with_acme package tls import ( "context" "crypto/tls" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) func startACME(ctx context.Context, options option.InboundACMEOptions) (*tls.Config, adapter.Service, error) { return nil, nil, E.New(`ACME is not included in this build, rebuild with -tags with_acme`) }
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/common/tls/reality_client.go
Bcore/windows/resources/sing-box-main/common/tls/reality_client.go
//go:build with_utls package tls import ( "bytes" "context" "crypto/aes" "crypto/cipher" "crypto/ecdh" "crypto/ed25519" "crypto/hmac" "crypto/sha256" "crypto/sha512" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/binary" "encoding/hex" "fmt" "io" mRand "math/rand" "net" "net/http" "reflect" "strings" "time" "unsafe" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/debug" E "github.com/sagernet/sing/common/exceptions" aTLS "github.com/sagernet/sing/common/tls" utls "github.com/sagernet/utls" "golang.org/x/crypto/hkdf" "golang.org/x/net/http2" ) var _ ConfigCompat = (*RealityClientConfig)(nil) type RealityClientConfig struct { uClient *UTLSClientConfig publicKey []byte shortID [8]byte } func NewRealityClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (*RealityClientConfig, error) { if options.UTLS == nil || !options.UTLS.Enabled { return nil, E.New("uTLS is required by reality client") } uClient, err := NewUTLSClient(ctx, serverAddress, options) if err != nil { return nil, err } publicKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PublicKey) if err != nil { return nil, E.Cause(err, "decode public_key") } if len(publicKey) != 32 { return nil, E.New("invalid public_key") } var shortID [8]byte decodedLen, err := hex.Decode(shortID[:], []byte(options.Reality.ShortID)) if err != nil { return nil, E.Cause(err, "decode short_id") } if decodedLen > 8 { return nil, E.New("invalid short_id") } return &RealityClientConfig{uClient, publicKey, shortID}, nil } func (e *RealityClientConfig) ServerName() string { return e.uClient.ServerName() } func (e *RealityClientConfig) SetServerName(serverName string) { e.uClient.SetServerName(serverName) } func (e *RealityClientConfig) NextProtos() []string { return e.uClient.NextProtos() } func (e *RealityClientConfig) SetNextProtos(nextProto []string) { e.uClient.SetNextProtos(nextProto) } func (e *RealityClientConfig) Config() (*STDConfig, error) { return nil, E.New("unsupported usage for reality") } func (e *RealityClientConfig) Client(conn net.Conn) (Conn, error) { return ClientHandshake(context.Background(), conn, e) } func (e *RealityClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) { verifier := &realityVerifier{ serverName: e.uClient.ServerName(), } uConfig := e.uClient.config.Clone() uConfig.InsecureSkipVerify = true uConfig.SessionTicketsDisabled = true uConfig.VerifyPeerCertificate = verifier.VerifyPeerCertificate uConn := utls.UClient(conn, uConfig, e.uClient.id) verifier.UConn = uConn err := uConn.BuildHandshakeState() if err != nil { return nil, err } if len(uConfig.NextProtos) > 0 { for _, extension := range uConn.Extensions { if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN { alpnExtension.AlpnProtocols = uConfig.NextProtos break } } } hello := uConn.HandshakeState.Hello hello.SessionId = make([]byte, 32) copy(hello.Raw[39:], hello.SessionId) var nowTime time.Time if uConfig.Time != nil { nowTime = uConfig.Time() } else { nowTime = time.Now() } binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix())) hello.SessionId[0] = 1 hello.SessionId[1] = 8 hello.SessionId[2] = 1 binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix())) copy(hello.SessionId[8:], e.shortID[:]) if debug.Enabled { fmt.Printf("REALITY hello.sessionId[:16]: %v\n", hello.SessionId[:16]) } publicKey, err := ecdh.X25519().NewPublicKey(e.publicKey) if err != nil { return nil, err } ecdheKey := uConn.HandshakeState.State13.EcdheKey if ecdheKey == nil { return nil, E.New("nil ecdhe_key") } authKey, err := ecdheKey.ECDH(publicKey) if err != nil { return nil, err } if authKey == nil { return nil, E.New("nil auth_key") } verifier.authKey = authKey _, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey) if err != nil { return nil, err } aesBlock, _ := aes.NewCipher(authKey) aesGcmCipher, _ := cipher.NewGCM(aesBlock) aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw) copy(hello.Raw[39:], hello.SessionId) if debug.Enabled { fmt.Printf("REALITY hello.sessionId: %v\n", hello.SessionId) fmt.Printf("REALITY uConn.AuthKey: %v\n", authKey) } err = uConn.HandshakeContext(ctx) if err != nil { return nil, err } if debug.Enabled { fmt.Printf("REALITY Conn.Verified: %v\n", verifier.verified) } if !verifier.verified { go realityClientFallback(uConn, e.uClient.ServerName(), e.uClient.id) return nil, E.New("reality verification failed") } return &utlsConnWrapper{uConn}, nil } func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) { defer uConn.Close() client := &http.Client{ Transport: &http2.Transport{ DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) { return uConn, nil }, }, } request, _ := http.NewRequest("GET", "https://"+serverName, nil) request.Header.Set("User-Agent", fingerprint.Client) request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", mRand.Intn(32)+30)}) response, err := client.Do(request) if err != nil { return } _, _ = io.Copy(io.Discard, response.Body) response.Body.Close() } func (e *RealityClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) { e.uClient.config.SessionIDGenerator = generator } func (e *RealityClientConfig) Clone() Config { return &RealityClientConfig{ e.uClient.Clone().(*UTLSClientConfig), e.publicKey, e.shortID, } } type realityVerifier struct { *utls.UConn serverName string authKey []byte verified bool } func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates") certs := *(*([]*x509.Certificate))(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + p.Offset)) if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok { h := hmac.New(sha512.New, c.authKey) h.Write(pub) if bytes.Equal(h.Sum(nil), certs[0].Signature) { c.verified = true return nil } } opts := x509.VerifyOptions{ DNSName: c.serverName, Intermediates: x509.NewCertPool(), } for _, cert := range certs[1:] { opts.Intermediates.AddCert(cert) } if _, err := certs[0].Verify(opts); 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/common/tls/config.go
Bcore/windows/resources/sing-box-main/common/tls/config.go
package tls import ( "crypto/tls" E "github.com/sagernet/sing/common/exceptions" aTLS "github.com/sagernet/sing/common/tls" ) type ( Config = aTLS.Config ConfigCompat = aTLS.ConfigCompat ServerConfig = aTLS.ServerConfig ServerConfigCompat = aTLS.ServerConfigCompat WithSessionIDGenerator = aTLS.WithSessionIDGenerator Conn = aTLS.Conn STDConfig = tls.Config STDConn = tls.Conn ConnectionState = tls.ConnectionState ) func ParseTLSVersion(version string) (uint16, error) { switch version { case "1.0": return tls.VersionTLS10, nil case "1.1": return tls.VersionTLS11, nil case "1.2": return tls.VersionTLS12, nil case "1.3": return tls.VersionTLS13, nil default: return 0, E.New("unknown tls version:", version) } }
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/common/tls/acme_contstant.go
Bcore/windows/resources/sing-box-main/common/tls/acme_contstant.go
package tls const ACMETLS1Protocol = "acme-tls/1"
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/common/tls/std_client.go
Bcore/windows/resources/sing-box-main/common/tls/std_client.go
package tls import ( "context" "crypto/tls" "crypto/x509" "net" "net/netip" "os" "strings" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/ntp" ) type STDClientConfig struct { config *tls.Config } func (s *STDClientConfig) ServerName() string { return s.config.ServerName } func (s *STDClientConfig) SetServerName(serverName string) { s.config.ServerName = serverName } func (s *STDClientConfig) NextProtos() []string { return s.config.NextProtos } func (s *STDClientConfig) SetNextProtos(nextProto []string) { s.config.NextProtos = nextProto } func (s *STDClientConfig) Config() (*STDConfig, error) { return s.config, nil } func (s *STDClientConfig) Client(conn net.Conn) (Conn, error) { return tls.Client(conn, s.config), nil } func (s *STDClientConfig) Clone() Config { return &STDClientConfig{s.config.Clone()} } func NewSTDClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) { var serverName string if options.ServerName != "" { serverName = options.ServerName } else if serverAddress != "" { if _, err := netip.ParseAddr(serverName); err != nil { serverName = serverAddress } } if serverName == "" && !options.Insecure { return nil, E.New("missing server_name or insecure=true") } var tlsConfig tls.Config tlsConfig.Time = ntp.TimeFuncFromContext(ctx) if options.DisableSNI { tlsConfig.ServerName = "127.0.0.1" } else { tlsConfig.ServerName = serverName } if options.Insecure { tlsConfig.InsecureSkipVerify = options.Insecure } else if options.DisableSNI { tlsConfig.InsecureSkipVerify = true tlsConfig.VerifyConnection = func(state tls.ConnectionState) error { verifyOptions := x509.VerifyOptions{ DNSName: serverName, Intermediates: x509.NewCertPool(), } for _, cert := range state.PeerCertificates[1:] { verifyOptions.Intermediates.AddCert(cert) } _, err := state.PeerCertificates[0].Verify(verifyOptions) return err } } if len(options.ALPN) > 0 { tlsConfig.NextProtos = options.ALPN } if options.MinVersion != "" { minVersion, err := ParseTLSVersion(options.MinVersion) if err != nil { return nil, E.Cause(err, "parse min_version") } tlsConfig.MinVersion = minVersion } if options.MaxVersion != "" { maxVersion, err := ParseTLSVersion(options.MaxVersion) if err != nil { return nil, E.Cause(err, "parse max_version") } tlsConfig.MaxVersion = maxVersion } if options.CipherSuites != nil { find: for _, cipherSuite := range options.CipherSuites { for _, tlsCipherSuite := range tls.CipherSuites() { if cipherSuite == tlsCipherSuite.Name { tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID) continue find } } return nil, E.New("unknown cipher_suite: ", cipherSuite) } } var certificate []byte if len(options.Certificate) > 0 { certificate = []byte(strings.Join(options.Certificate, "\n")) } else if options.CertificatePath != "" { content, err := os.ReadFile(options.CertificatePath) if err != nil { return nil, E.Cause(err, "read certificate") } certificate = content } if len(certificate) > 0 { certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(certificate) { return nil, E.New("failed to parse certificate:\n\n", certificate) } tlsConfig.RootCAs = certPool } return &STDClientConfig{&tlsConfig}, 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/common/tls/mkcert.go
Bcore/windows/resources/sing-box-main/common/tls/mkcert.go
package tls import ( "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "math/big" "time" ) func GenerateCertificate(timeFunc func() time.Time, serverName string) (*tls.Certificate, error) { privateKeyPem, publicKeyPem, err := GenerateKeyPair(timeFunc, serverName, timeFunc().Add(time.Hour)) if err != nil { return nil, err } certificate, err := tls.X509KeyPair(publicKeyPem, privateKeyPem) if err != nil { return nil, err } return &certificate, err } func GenerateKeyPair(timeFunc func() time.Time, serverName string, expire time.Time) (privateKeyPem []byte, publicKeyPem []byte, err error) { if timeFunc == nil { timeFunc = time.Now } key, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return } serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) if err != nil { return } template := &x509.Certificate{ SerialNumber: serialNumber, NotBefore: timeFunc().Add(time.Hour * -1), NotAfter: expire, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, Subject: pkix.Name{ CommonName: serverName, }, DNSNames: []string{serverName}, } publicDer, err := x509.CreateCertificate(rand.Reader, template, template, key.Public(), key) if err != nil { return } privateDer, err := x509.MarshalPKCS8PrivateKey(key) if err != nil { return } publicKeyPem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: publicDer}) privateKeyPem = pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: privateDer}) return }
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/common/tls/acme.go
Bcore/windows/resources/sing-box-main/common/tls/acme.go
//go:build with_acme package tls import ( "context" "crypto/tls" "os" "strings" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/caddyserver/certmagic" "github.com/libdns/alidns" "github.com/libdns/cloudflare" "github.com/mholt/acmez/acme" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) type acmeWrapper struct { ctx context.Context cfg *certmagic.Config cache *certmagic.Cache domain []string } func (w *acmeWrapper) Start() error { return w.cfg.ManageSync(w.ctx, w.domain) } func (w *acmeWrapper) Close() error { w.cache.Stop() return nil } func startACME(ctx context.Context, options option.InboundACMEOptions) (*tls.Config, adapter.Service, error) { var acmeServer string switch options.Provider { case "", "letsencrypt": acmeServer = certmagic.LetsEncryptProductionCA case "zerossl": acmeServer = certmagic.ZeroSSLProductionCA default: if !strings.HasPrefix(options.Provider, "https://") { return nil, nil, E.New("unsupported acme provider: " + options.Provider) } acmeServer = options.Provider } var storage certmagic.Storage if options.DataDirectory != "" { storage = &certmagic.FileStorage{ Path: options.DataDirectory, } } else { storage = certmagic.Default.Storage } config := &certmagic.Config{ DefaultServerName: options.DefaultServerName, Storage: storage, Logger: zap.New(zapcore.NewCore( zapcore.NewConsoleEncoder(zap.NewProductionEncoderConfig()), os.Stderr, zap.InfoLevel, )), } acmeConfig := certmagic.ACMEIssuer{ CA: acmeServer, Email: options.Email, Agreed: true, DisableHTTPChallenge: options.DisableHTTPChallenge, DisableTLSALPNChallenge: options.DisableTLSALPNChallenge, AltHTTPPort: int(options.AlternativeHTTPPort), AltTLSALPNPort: int(options.AlternativeTLSPort), Logger: config.Logger, } if dnsOptions := options.DNS01Challenge; dnsOptions != nil && dnsOptions.Provider != "" { var solver certmagic.DNS01Solver switch dnsOptions.Provider { case C.DNSProviderAliDNS: solver.DNSProvider = &alidns.Provider{ AccKeyID: dnsOptions.AliDNSOptions.AccessKeyID, AccKeySecret: dnsOptions.AliDNSOptions.AccessKeySecret, RegionID: dnsOptions.AliDNSOptions.RegionID, } case C.DNSProviderCloudflare: solver.DNSProvider = &cloudflare.Provider{ APIToken: dnsOptions.CloudflareOptions.APIToken, } default: return nil, nil, E.New("unsupported ACME DNS01 provider type: " + dnsOptions.Provider) } acmeConfig.DNS01Solver = &solver } if options.ExternalAccount != nil && options.ExternalAccount.KeyID != "" { acmeConfig.ExternalAccount = (*acme.EAB)(options.ExternalAccount) } config.Issuers = []certmagic.Issuer{certmagic.NewACMEIssuer(config, acmeConfig)} cache := certmagic.NewCache(certmagic.CacheOptions{ GetConfigForCert: func(certificate certmagic.Certificate) (*certmagic.Config, error) { return config, nil }, }) config = certmagic.New(cache, *config) var tlsConfig *tls.Config if acmeConfig.DisableTLSALPNChallenge || acmeConfig.DNS01Solver != nil { tlsConfig = &tls.Config{ GetCertificate: config.GetCertificate, } } else { tlsConfig = &tls.Config{ GetCertificate: config.GetCertificate, NextProtos: []string{ACMETLS1Protocol}, } } return tlsConfig, &acmeWrapper{ctx: ctx, cfg: config, cache: cache, domain: options.Domain}, 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/common/tls/utls_client.go
Bcore/windows/resources/sing-box-main/common/tls/utls_client.go
//go:build with_utls package tls import ( "context" "crypto/tls" "crypto/x509" "math/rand" "net" "net/netip" "os" "strings" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/ntp" utls "github.com/sagernet/utls" "golang.org/x/net/http2" ) type UTLSClientConfig struct { config *utls.Config id utls.ClientHelloID } func (e *UTLSClientConfig) ServerName() string { return e.config.ServerName } func (e *UTLSClientConfig) SetServerName(serverName string) { e.config.ServerName = serverName } func (e *UTLSClientConfig) NextProtos() []string { return e.config.NextProtos } func (e *UTLSClientConfig) SetNextProtos(nextProto []string) { if len(nextProto) == 1 && nextProto[0] == http2.NextProtoTLS { nextProto = append(nextProto, "http/1.1") } e.config.NextProtos = nextProto } func (e *UTLSClientConfig) Config() (*STDConfig, error) { return nil, E.New("unsupported usage for uTLS") } func (e *UTLSClientConfig) Client(conn net.Conn) (Conn, error) { return &utlsALPNWrapper{utlsConnWrapper{utls.UClient(conn, e.config.Clone(), e.id)}, e.config.NextProtos}, nil } func (e *UTLSClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) { e.config.SessionIDGenerator = generator } func (e *UTLSClientConfig) Clone() Config { return &UTLSClientConfig{ config: e.config.Clone(), id: e.id, } } type utlsConnWrapper struct { *utls.UConn } func (c *utlsConnWrapper) ConnectionState() tls.ConnectionState { state := c.Conn.ConnectionState() return tls.ConnectionState{ Version: state.Version, HandshakeComplete: state.HandshakeComplete, DidResume: state.DidResume, CipherSuite: state.CipherSuite, NegotiatedProtocol: state.NegotiatedProtocol, NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual, ServerName: state.ServerName, PeerCertificates: state.PeerCertificates, VerifiedChains: state.VerifiedChains, SignedCertificateTimestamps: state.SignedCertificateTimestamps, OCSPResponse: state.OCSPResponse, TLSUnique: state.TLSUnique, } } func (c *utlsConnWrapper) Upstream() any { return c.UConn } type utlsALPNWrapper struct { utlsConnWrapper nextProtocols []string } func (c *utlsALPNWrapper) HandshakeContext(ctx context.Context) error { if len(c.nextProtocols) > 0 { err := c.BuildHandshakeState() if err != nil { return err } for _, extension := range c.Extensions { if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN { alpnExtension.AlpnProtocols = c.nextProtocols err = c.BuildHandshakeState() if err != nil { return err } break } } } return c.UConn.HandshakeContext(ctx) } func NewUTLSClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (*UTLSClientConfig, error) { var serverName string if options.ServerName != "" { serverName = options.ServerName } else if serverAddress != "" { if _, err := netip.ParseAddr(serverName); err != nil { serverName = serverAddress } } if serverName == "" && !options.Insecure { return nil, E.New("missing server_name or insecure=true") } var tlsConfig utls.Config tlsConfig.Time = ntp.TimeFuncFromContext(ctx) if options.DisableSNI { tlsConfig.ServerName = "127.0.0.1" } else { tlsConfig.ServerName = serverName } if options.Insecure { tlsConfig.InsecureSkipVerify = options.Insecure } else if options.DisableSNI { return nil, E.New("disable_sni is unsupported in uTLS") } if len(options.ALPN) > 0 { tlsConfig.NextProtos = options.ALPN } if options.MinVersion != "" { minVersion, err := ParseTLSVersion(options.MinVersion) if err != nil { return nil, E.Cause(err, "parse min_version") } tlsConfig.MinVersion = minVersion } if options.MaxVersion != "" { maxVersion, err := ParseTLSVersion(options.MaxVersion) if err != nil { return nil, E.Cause(err, "parse max_version") } tlsConfig.MaxVersion = maxVersion } if options.CipherSuites != nil { find: for _, cipherSuite := range options.CipherSuites { for _, tlsCipherSuite := range tls.CipherSuites() { if cipherSuite == tlsCipherSuite.Name { tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID) continue find } } return nil, E.New("unknown cipher_suite: ", cipherSuite) } } var certificate []byte if len(options.Certificate) > 0 { certificate = []byte(strings.Join(options.Certificate, "\n")) } else if options.CertificatePath != "" { content, err := os.ReadFile(options.CertificatePath) if err != nil { return nil, E.Cause(err, "read certificate") } certificate = content } if len(certificate) > 0 { certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(certificate) { return nil, E.New("failed to parse certificate:\n\n", certificate) } tlsConfig.RootCAs = certPool } id, err := uTLSClientHelloID(options.UTLS.Fingerprint) if err != nil { return nil, err } return &UTLSClientConfig{&tlsConfig, id}, nil } var ( randomFingerprint utls.ClientHelloID randomizedFingerprint utls.ClientHelloID ) func init() { modernFingerprints := []utls.ClientHelloID{ utls.HelloChrome_Auto, utls.HelloFirefox_Auto, utls.HelloEdge_Auto, utls.HelloSafari_Auto, utls.HelloIOS_Auto, } randomFingerprint = modernFingerprints[rand.Intn(len(modernFingerprints))] weights := utls.DefaultWeights weights.TLSVersMax_Set_VersionTLS13 = 1 weights.FirstKeyShare_Set_CurveP256 = 0 randomizedFingerprint = utls.HelloRandomized randomizedFingerprint.Seed, _ = utls.NewPRNGSeed() randomizedFingerprint.Weights = &weights } func uTLSClientHelloID(name string) (utls.ClientHelloID, error) { switch name { case "chrome_psk", "chrome_psk_shuffle", "chrome_padding_psk_shuffle", "chrome_pq": fallthrough case "chrome", "": return utls.HelloChrome_Auto, nil case "firefox": return utls.HelloFirefox_Auto, nil case "edge": return utls.HelloEdge_Auto, nil case "safari": return utls.HelloSafari_Auto, nil case "360": return utls.Hello360_Auto, nil case "qq": return utls.HelloQQ_Auto, nil case "ios": return utls.HelloIOS_Auto, nil case "android": return utls.HelloAndroid_11_OkHttp, nil case "random": return randomFingerprint, nil case "randomized": return randomizedFingerprint, nil default: return utls.ClientHelloID{}, E.New("unknown uTLS fingerprint: ", name) } }
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/common/tls/ech_stub.go
Bcore/windows/resources/sing-box-main/common/tls/ech_stub.go
//go:build !with_ech package tls import ( "context" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) var errECHNotIncluded = E.New(`ECH is not included in this build, rebuild with -tags with_ech`) func NewECHServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) { return nil, errECHNotIncluded } func NewECHClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) { return nil, errECHNotIncluded } func ECHKeygenDefault(host string, pqSignatureSchemesEnabled bool) (configPem string, keyPem string, err error) { return "", "", errECHNotIncluded }
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/common/tls/reality_server.go
Bcore/windows/resources/sing-box-main/common/tls/reality_server.go
//go:build with_reality_server package tls import ( "context" "crypto/tls" "encoding/base64" "encoding/hex" "net" "time" "github.com/sagernet/reality" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/common/dialer" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common/debug" 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/ntp" ) var _ ServerConfigCompat = (*RealityServerConfig)(nil) type RealityServerConfig struct { config *reality.Config } func NewRealityServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (*RealityServerConfig, error) { var tlsConfig reality.Config if options.ACME != nil && len(options.ACME.Domain) > 0 { return nil, E.New("acme is unavailable in reality") } tlsConfig.Time = ntp.TimeFuncFromContext(ctx) if options.ServerName != "" { tlsConfig.ServerName = options.ServerName } if len(options.ALPN) > 0 { tlsConfig.NextProtos = append(tlsConfig.NextProtos, options.ALPN...) } if options.MinVersion != "" { minVersion, err := ParseTLSVersion(options.MinVersion) if err != nil { return nil, E.Cause(err, "parse min_version") } tlsConfig.MinVersion = minVersion } if options.MaxVersion != "" { maxVersion, err := ParseTLSVersion(options.MaxVersion) if err != nil { return nil, E.Cause(err, "parse max_version") } tlsConfig.MaxVersion = maxVersion } if options.CipherSuites != nil { find: for _, cipherSuite := range options.CipherSuites { for _, tlsCipherSuite := range tls.CipherSuites() { if cipherSuite == tlsCipherSuite.Name { tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID) continue find } } return nil, E.New("unknown cipher_suite: ", cipherSuite) } } if len(options.Certificate) > 0 || options.CertificatePath != "" { return nil, E.New("certificate is unavailable in reality") } if len(options.Key) > 0 || options.KeyPath != "" { return nil, E.New("key is unavailable in reality") } tlsConfig.SessionTicketsDisabled = true tlsConfig.Type = N.NetworkTCP tlsConfig.Dest = options.Reality.Handshake.ServerOptions.Build().String() tlsConfig.ServerNames = map[string]bool{options.ServerName: true} privateKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PrivateKey) if err != nil { return nil, E.Cause(err, "decode private key") } if len(privateKey) != 32 { return nil, E.New("invalid private key") } tlsConfig.PrivateKey = privateKey tlsConfig.MaxTimeDiff = time.Duration(options.Reality.MaxTimeDifference) tlsConfig.ShortIds = make(map[[8]byte]bool) for i, shortIDString := range options.Reality.ShortID { var shortID [8]byte decodedLen, err := hex.Decode(shortID[:], []byte(shortIDString)) if err != nil { return nil, E.Cause(err, "decode short_id[", i, "]: ", shortIDString) } if decodedLen > 8 { return nil, E.New("invalid short_id[", i, "]: ", shortIDString) } tlsConfig.ShortIds[shortID] = true } handshakeDialer, err := dialer.New(adapter.RouterFromContext(ctx), options.Reality.Handshake.DialerOptions) if err != nil { return nil, err } tlsConfig.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { return handshakeDialer.DialContext(ctx, network, M.ParseSocksaddr(addr)) } if debug.Enabled { tlsConfig.Show = true } return &RealityServerConfig{&tlsConfig}, nil } func (c *RealityServerConfig) ServerName() string { return c.config.ServerName } func (c *RealityServerConfig) SetServerName(serverName string) { c.config.ServerName = serverName } func (c *RealityServerConfig) NextProtos() []string { return c.config.NextProtos } func (c *RealityServerConfig) SetNextProtos(nextProto []string) { c.config.NextProtos = nextProto } func (c *RealityServerConfig) Config() (*tls.Config, error) { return nil, E.New("unsupported usage for reality") } func (c *RealityServerConfig) Client(conn net.Conn) (Conn, error) { return ClientHandshake(context.Background(), conn, c) } func (c *RealityServerConfig) Start() error { return nil } func (c *RealityServerConfig) Close() error { return nil } func (c *RealityServerConfig) Server(conn net.Conn) (Conn, error) { return ServerHandshake(context.Background(), conn, c) } func (c *RealityServerConfig) ServerHandshake(ctx context.Context, conn net.Conn) (Conn, error) { tlsConn, err := reality.Server(ctx, conn, c.config) if err != nil { return nil, err } return &realityConnWrapper{Conn: tlsConn}, nil } func (c *RealityServerConfig) Clone() Config { return &RealityServerConfig{ config: c.config.Clone(), } } var _ Conn = (*realityConnWrapper)(nil) type realityConnWrapper struct { *reality.Conn } func (c *realityConnWrapper) ConnectionState() ConnectionState { state := c.Conn.ConnectionState() return tls.ConnectionState{ Version: state.Version, HandshakeComplete: state.HandshakeComplete, DidResume: state.DidResume, CipherSuite: state.CipherSuite, NegotiatedProtocol: state.NegotiatedProtocol, NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual, ServerName: state.ServerName, PeerCertificates: state.PeerCertificates, VerifiedChains: state.VerifiedChains, SignedCertificateTimestamps: state.SignedCertificateTimestamps, OCSPResponse: state.OCSPResponse, TLSUnique: state.TLSUnique, } } func (c *realityConnWrapper) Upstream() any { return c.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/common/tls/server.go
Bcore/windows/resources/sing-box-main/common/tls/server.go
package tls import ( "context" "net" "os" "github.com/sagernet/sing-box/common/badtls" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" aTLS "github.com/sagernet/sing/common/tls" ) func NewServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) { if !options.Enabled { return nil, nil } if options.ECH != nil && options.ECH.Enabled { return NewECHServer(ctx, logger, options) } else if options.Reality != nil && options.Reality.Enabled { return NewRealityServer(ctx, logger, options) } else { return NewSTDServer(ctx, logger, options) } } func ServerHandshake(ctx context.Context, conn net.Conn, config ServerConfig) (Conn, error) { ctx, cancel := context.WithTimeout(ctx, C.TCPTimeout) defer cancel() tlsConn, err := aTLS.ServerHandshake(ctx, conn, config) if err != nil { return nil, err } readWaitConn, err := badtls.NewReadWaitConn(tlsConn) if err == nil { return readWaitConn, nil } else if err != os.ErrInvalid { return nil, err } return tlsConn, 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/common/tls/ech_client.go
Bcore/windows/resources/sing-box-main/common/tls/ech_client.go
//go:build with_ech package tls import ( "context" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/pem" "net" "net/netip" "os" "strings" cftls "github.com/sagernet/cloudflare-tls" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-dns" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/ntp" mDNS "github.com/miekg/dns" ) type echClientConfig struct { config *cftls.Config } func (c *echClientConfig) ServerName() string { return c.config.ServerName } func (c *echClientConfig) SetServerName(serverName string) { c.config.ServerName = serverName } func (c *echClientConfig) NextProtos() []string { return c.config.NextProtos } func (c *echClientConfig) SetNextProtos(nextProto []string) { c.config.NextProtos = nextProto } func (c *echClientConfig) Config() (*STDConfig, error) { return nil, E.New("unsupported usage for ECH") } func (c *echClientConfig) Client(conn net.Conn) (Conn, error) { return &echConnWrapper{cftls.Client(conn, c.config)}, nil } func (c *echClientConfig) Clone() Config { return &echClientConfig{ config: c.config.Clone(), } } type echConnWrapper struct { *cftls.Conn } func (c *echConnWrapper) ConnectionState() tls.ConnectionState { state := c.Conn.ConnectionState() return tls.ConnectionState{ Version: state.Version, HandshakeComplete: state.HandshakeComplete, DidResume: state.DidResume, CipherSuite: state.CipherSuite, NegotiatedProtocol: state.NegotiatedProtocol, NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual, ServerName: state.ServerName, PeerCertificates: state.PeerCertificates, VerifiedChains: state.VerifiedChains, SignedCertificateTimestamps: state.SignedCertificateTimestamps, OCSPResponse: state.OCSPResponse, TLSUnique: state.TLSUnique, } } func (c *echConnWrapper) Upstream() any { return c.Conn } func NewECHClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) { var serverName string if options.ServerName != "" { serverName = options.ServerName } else if serverAddress != "" { if _, err := netip.ParseAddr(serverName); err != nil { serverName = serverAddress } } if serverName == "" && !options.Insecure { return nil, E.New("missing server_name or insecure=true") } var tlsConfig cftls.Config tlsConfig.Time = ntp.TimeFuncFromContext(ctx) if options.DisableSNI { tlsConfig.ServerName = "127.0.0.1" } else { tlsConfig.ServerName = serverName } if options.Insecure { tlsConfig.InsecureSkipVerify = options.Insecure } else if options.DisableSNI { tlsConfig.InsecureSkipVerify = true tlsConfig.VerifyConnection = func(state cftls.ConnectionState) error { verifyOptions := x509.VerifyOptions{ DNSName: serverName, Intermediates: x509.NewCertPool(), } for _, cert := range state.PeerCertificates[1:] { verifyOptions.Intermediates.AddCert(cert) } _, err := state.PeerCertificates[0].Verify(verifyOptions) return err } } if len(options.ALPN) > 0 { tlsConfig.NextProtos = options.ALPN } if options.MinVersion != "" { minVersion, err := ParseTLSVersion(options.MinVersion) if err != nil { return nil, E.Cause(err, "parse min_version") } tlsConfig.MinVersion = minVersion } if options.MaxVersion != "" { maxVersion, err := ParseTLSVersion(options.MaxVersion) if err != nil { return nil, E.Cause(err, "parse max_version") } tlsConfig.MaxVersion = maxVersion } if options.CipherSuites != nil { find: for _, cipherSuite := range options.CipherSuites { for _, tlsCipherSuite := range cftls.CipherSuites() { if cipherSuite == tlsCipherSuite.Name { tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID) continue find } } return nil, E.New("unknown cipher_suite: ", cipherSuite) } } var certificate []byte if len(options.Certificate) > 0 { certificate = []byte(strings.Join(options.Certificate, "\n")) } else if options.CertificatePath != "" { content, err := os.ReadFile(options.CertificatePath) if err != nil { return nil, E.Cause(err, "read certificate") } certificate = content } if len(certificate) > 0 { certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(certificate) { return nil, E.New("failed to parse certificate:\n\n", certificate) } tlsConfig.RootCAs = certPool } // ECH Config tlsConfig.ECHEnabled = true tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled var echConfig []byte if len(options.ECH.Config) > 0 { echConfig = []byte(strings.Join(options.ECH.Config, "\n")) } else if options.ECH.ConfigPath != "" { content, err := os.ReadFile(options.ECH.ConfigPath) if err != nil { return nil, E.Cause(err, "read ECH config") } echConfig = content } if len(echConfig) > 0 { block, rest := pem.Decode(echConfig) if block == nil || block.Type != "ECH CONFIGS" || len(rest) > 0 { return nil, E.New("invalid ECH configs pem") } echConfigs, err := cftls.UnmarshalECHConfigs(block.Bytes) if err != nil { return nil, E.Cause(err, "parse ECH configs") } tlsConfig.ClientECHConfigs = echConfigs } else { tlsConfig.GetClientECHConfigs = fetchECHClientConfig(ctx) } return &echClientConfig{&tlsConfig}, nil } func fetchECHClientConfig(ctx context.Context) func(_ context.Context, serverName string) ([]cftls.ECHConfig, error) { return func(_ context.Context, serverName string) ([]cftls.ECHConfig, error) { message := &mDNS.Msg{ MsgHdr: mDNS.MsgHdr{ RecursionDesired: true, }, Question: []mDNS.Question{ { Name: serverName + ".", Qtype: mDNS.TypeHTTPS, Qclass: mDNS.ClassINET, }, }, } response, err := adapter.RouterFromContext(ctx).Exchange(ctx, message) if err != nil { return nil, err } if response.Rcode != mDNS.RcodeSuccess { return nil, dns.RCodeError(response.Rcode) } for _, rr := range response.Answer { switch resource := rr.(type) { case *mDNS.HTTPS: for _, value := range resource.Value { if value.Key().String() == "ech" { echConfig, err := base64.StdEncoding.DecodeString(value.String()) if err != nil { return nil, E.Cause(err, "decode ECH config") } return cftls.UnmarshalECHConfigs(echConfig) } } default: return nil, E.New("unknown resource record type: ", resource.Header().Rrtype) } } return nil, E.New("no ECH config found") } }
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/common/tls/utls_stub.go
Bcore/windows/resources/sing-box-main/common/tls/utls_stub.go
//go:build !with_utls package tls import ( "context" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" ) func NewUTLSClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) { return nil, E.New(`uTLS is not included in this build, rebuild with -tags with_utls`) } func NewRealityClient(ctx context.Context, serverAddress string, options option.OutboundTLSOptions) (Config, error) { return nil, E.New(`uTLS, which is required by reality client is not included in this build, rebuild with -tags with_utls`) }
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/common/tls/ech_server.go
Bcore/windows/resources/sing-box-main/common/tls/ech_server.go
//go:build with_ech package tls import ( "context" "crypto/tls" "encoding/pem" "net" "os" "strings" cftls "github.com/sagernet/cloudflare-tls" "github.com/sagernet/fswatch" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/ntp" ) type echServerConfig struct { config *cftls.Config logger log.Logger certificate []byte key []byte certificatePath string keyPath string echKeyPath string watcher *fswatch.Watcher } func (c *echServerConfig) ServerName() string { return c.config.ServerName } func (c *echServerConfig) SetServerName(serverName string) { c.config.ServerName = serverName } func (c *echServerConfig) NextProtos() []string { return c.config.NextProtos } func (c *echServerConfig) SetNextProtos(nextProto []string) { c.config.NextProtos = nextProto } func (c *echServerConfig) Config() (*STDConfig, error) { return nil, E.New("unsupported usage for ECH") } func (c *echServerConfig) Client(conn net.Conn) (Conn, error) { return &echConnWrapper{cftls.Client(conn, c.config)}, nil } func (c *echServerConfig) Server(conn net.Conn) (Conn, error) { return &echConnWrapper{cftls.Server(conn, c.config)}, nil } func (c *echServerConfig) Clone() Config { return &echServerConfig{ config: c.config.Clone(), } } func (c *echServerConfig) Start() error { err := c.startWatcher() if err != nil { c.logger.Warn("create credentials watcher: ", err) } return nil } func (c *echServerConfig) startWatcher() error { var watchPath []string if c.certificatePath != "" { watchPath = append(watchPath, c.certificatePath) } if c.keyPath != "" { watchPath = append(watchPath, c.keyPath) } if c.echKeyPath != "" { watchPath = append(watchPath, c.echKeyPath) } if len(watchPath) == 0 { return nil } watcher, err := fswatch.NewWatcher(fswatch.Options{ Path: watchPath, Callback: func(path string) { err := c.credentialsUpdated(path) if err != nil { c.logger.Error(E.Cause(err, "reload credentials from ", path)) } }, }) if err != nil { return err } c.watcher = watcher return nil } func (c *echServerConfig) credentialsUpdated(path string) error { if path == c.certificatePath || path == c.keyPath { if path == c.certificatePath { certificate, err := os.ReadFile(c.certificatePath) if err != nil { return err } c.certificate = certificate } else { key, err := os.ReadFile(c.keyPath) if err != nil { return err } c.key = key } keyPair, err := cftls.X509KeyPair(c.certificate, c.key) if err != nil { return E.Cause(err, "parse key pair") } c.config.Certificates = []cftls.Certificate{keyPair} c.logger.Info("reloaded TLS certificate") } else { echKeyContent, err := os.ReadFile(c.echKeyPath) if err != nil { return err } block, rest := pem.Decode(echKeyContent) if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 { return E.New("invalid ECH keys pem") } echKeys, err := cftls.EXP_UnmarshalECHKeys(block.Bytes) if err != nil { return E.Cause(err, "parse ECH keys") } echKeySet, err := cftls.EXP_NewECHKeySet(echKeys) if err != nil { return E.Cause(err, "create ECH key set") } c.config.ServerECHProvider = echKeySet c.logger.Info("reloaded ECH keys") } return nil } func (c *echServerConfig) Close() error { var err error if c.watcher != nil { err = E.Append(err, c.watcher.Close(), func(err error) error { return E.Cause(err, "close credentials watcher") }) } return err } func NewECHServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) { if !options.Enabled { return nil, nil } var tlsConfig cftls.Config if options.ACME != nil && len(options.ACME.Domain) > 0 { return nil, E.New("acme is unavailable in ech") } tlsConfig.Time = ntp.TimeFuncFromContext(ctx) if options.ServerName != "" { tlsConfig.ServerName = options.ServerName } if len(options.ALPN) > 0 { tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...) } if options.MinVersion != "" { minVersion, err := ParseTLSVersion(options.MinVersion) if err != nil { return nil, E.Cause(err, "parse min_version") } tlsConfig.MinVersion = minVersion } if options.MaxVersion != "" { maxVersion, err := ParseTLSVersion(options.MaxVersion) if err != nil { return nil, E.Cause(err, "parse max_version") } tlsConfig.MaxVersion = maxVersion } if options.CipherSuites != nil { find: for _, cipherSuite := range options.CipherSuites { for _, tlsCipherSuite := range tls.CipherSuites() { if cipherSuite == tlsCipherSuite.Name { tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID) continue find } } return nil, E.New("unknown cipher_suite: ", cipherSuite) } } var certificate []byte var key []byte if len(options.Certificate) > 0 { certificate = []byte(strings.Join(options.Certificate, "\n")) } else if options.CertificatePath != "" { content, err := os.ReadFile(options.CertificatePath) if err != nil { return nil, E.Cause(err, "read certificate") } certificate = content } if len(options.Key) > 0 { key = []byte(strings.Join(options.Key, "\n")) } else if options.KeyPath != "" { content, err := os.ReadFile(options.KeyPath) if err != nil { return nil, E.Cause(err, "read key") } key = content } if certificate == nil { return nil, E.New("missing certificate") } else if key == nil { return nil, E.New("missing key") } keyPair, err := cftls.X509KeyPair(certificate, key) if err != nil { return nil, E.Cause(err, "parse x509 key pair") } tlsConfig.Certificates = []cftls.Certificate{keyPair} var echKey []byte if len(options.ECH.Key) > 0 { echKey = []byte(strings.Join(options.ECH.Key, "\n")) } else if options.KeyPath != "" { content, err := os.ReadFile(options.ECH.KeyPath) if err != nil { return nil, E.Cause(err, "read ECH key") } echKey = content } else { return nil, E.New("missing ECH key") } block, rest := pem.Decode(echKey) if block == nil || block.Type != "ECH KEYS" || len(rest) > 0 { return nil, E.New("invalid ECH keys pem") } echKeys, err := cftls.EXP_UnmarshalECHKeys(block.Bytes) if err != nil { return nil, E.Cause(err, "parse ECH keys") } echKeySet, err := cftls.EXP_NewECHKeySet(echKeys) if err != nil { return nil, E.Cause(err, "create ECH key set") } tlsConfig.ECHEnabled = true tlsConfig.PQSignatureSchemesEnabled = options.ECH.PQSignatureSchemesEnabled tlsConfig.DynamicRecordSizingDisabled = options.ECH.DynamicRecordSizingDisabled tlsConfig.ServerECHProvider = echKeySet return &echServerConfig{ config: &tlsConfig, logger: logger, certificate: certificate, key: key, certificatePath: options.CertificatePath, keyPath: options.KeyPath, echKeyPath: options.ECH.KeyPath, }, 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/common/tls/std_server.go
Bcore/windows/resources/sing-box-main/common/tls/std_server.go
package tls import ( "context" "crypto/tls" "net" "os" "strings" "github.com/sagernet/fswatch" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/ntp" ) var errInsecureUnused = E.New("tls: insecure unused") type STDServerConfig struct { config *tls.Config logger log.Logger acmeService adapter.Service certificate []byte key []byte certificatePath string keyPath string watcher *fswatch.Watcher } func (c *STDServerConfig) ServerName() string { return c.config.ServerName } func (c *STDServerConfig) SetServerName(serverName string) { c.config.ServerName = serverName } func (c *STDServerConfig) NextProtos() []string { if c.acmeService != nil && len(c.config.NextProtos) > 1 && c.config.NextProtos[0] == ACMETLS1Protocol { return c.config.NextProtos[1:] } else { return c.config.NextProtos } } func (c *STDServerConfig) SetNextProtos(nextProto []string) { if c.acmeService != nil && len(c.config.NextProtos) > 1 && c.config.NextProtos[0] == ACMETLS1Protocol { c.config.NextProtos = append(c.config.NextProtos[:1], nextProto...) } else { c.config.NextProtos = nextProto } } func (c *STDServerConfig) Config() (*STDConfig, error) { return c.config, nil } func (c *STDServerConfig) Client(conn net.Conn) (Conn, error) { return tls.Client(conn, c.config), nil } func (c *STDServerConfig) Server(conn net.Conn) (Conn, error) { return tls.Server(conn, c.config), nil } func (c *STDServerConfig) Clone() Config { return &STDServerConfig{ config: c.config.Clone(), } } func (c *STDServerConfig) Start() error { if c.acmeService != nil { return c.acmeService.Start() } else { if c.certificatePath == "" && c.keyPath == "" { return nil } err := c.startWatcher() if err != nil { c.logger.Warn("create fsnotify watcher: ", err) } return nil } } func (c *STDServerConfig) startWatcher() error { var watchPath []string if c.certificatePath != "" { watchPath = append(watchPath, c.certificatePath) } if c.keyPath != "" { watchPath = append(watchPath, c.keyPath) } watcher, err := fswatch.NewWatcher(fswatch.Options{ Path: watchPath, Callback: func(path string) { err := c.certificateUpdated(path) if err != nil { c.logger.Error(err) } }, }) if err != nil { return err } c.watcher = watcher return nil } func (c *STDServerConfig) certificateUpdated(path string) error { if path == c.certificatePath { certificate, err := os.ReadFile(c.certificatePath) if err != nil { return E.Cause(err, "reload certificate from ", c.certificatePath) } c.certificate = certificate } else if path == c.keyPath { key, err := os.ReadFile(c.keyPath) if err != nil { return E.Cause(err, "reload key from ", c.keyPath) } c.key = key } keyPair, err := tls.X509KeyPair(c.certificate, c.key) if err != nil { return E.Cause(err, "reload key pair") } c.config.Certificates = []tls.Certificate{keyPair} c.logger.Info("reloaded TLS certificate") return nil } func (c *STDServerConfig) Close() error { if c.acmeService != nil { return c.acmeService.Close() } if c.watcher != nil { return c.watcher.Close() } return nil } func NewSTDServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (ServerConfig, error) { if !options.Enabled { return nil, nil } var tlsConfig *tls.Config var acmeService adapter.Service var err error if options.ACME != nil && len(options.ACME.Domain) > 0 { //nolint:staticcheck tlsConfig, acmeService, err = startACME(ctx, common.PtrValueOrDefault(options.ACME)) if err != nil { return nil, err } if options.Insecure { return nil, errInsecureUnused } } else { tlsConfig = &tls.Config{} } tlsConfig.Time = ntp.TimeFuncFromContext(ctx) if options.ServerName != "" { tlsConfig.ServerName = options.ServerName } if len(options.ALPN) > 0 { tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...) } if options.MinVersion != "" { minVersion, err := ParseTLSVersion(options.MinVersion) if err != nil { return nil, E.Cause(err, "parse min_version") } tlsConfig.MinVersion = minVersion } if options.MaxVersion != "" { maxVersion, err := ParseTLSVersion(options.MaxVersion) if err != nil { return nil, E.Cause(err, "parse max_version") } tlsConfig.MaxVersion = maxVersion } if options.CipherSuites != nil { find: for _, cipherSuite := range options.CipherSuites { for _, tlsCipherSuite := range tls.CipherSuites() { if cipherSuite == tlsCipherSuite.Name { tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID) continue find } } return nil, E.New("unknown cipher_suite: ", cipherSuite) } } var certificate []byte var key []byte if acmeService == nil { if len(options.Certificate) > 0 { certificate = []byte(strings.Join(options.Certificate, "\n")) } else if options.CertificatePath != "" { content, err := os.ReadFile(options.CertificatePath) if err != nil { return nil, E.Cause(err, "read certificate") } certificate = content } if len(options.Key) > 0 { key = []byte(strings.Join(options.Key, "\n")) } else if options.KeyPath != "" { content, err := os.ReadFile(options.KeyPath) if err != nil { return nil, E.Cause(err, "read key") } key = content } if certificate == nil && key == nil && options.Insecure { tlsConfig.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) { return GenerateCertificate(ntp.TimeFuncFromContext(ctx), info.ServerName) } } else { if certificate == nil { return nil, E.New("missing certificate") } else if key == nil { return nil, E.New("missing key") } keyPair, err := tls.X509KeyPair(certificate, key) if err != nil { return nil, E.Cause(err, "parse x509 key pair") } tlsConfig.Certificates = []tls.Certificate{keyPair} } } return &STDServerConfig{ config: tlsConfig, logger: logger, acmeService: acmeService, certificate: certificate, key: key, certificatePath: options.CertificatePath, keyPath: options.KeyPath, }, 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/common/tls/common.go
Bcore/windows/resources/sing-box-main/common/tls/common.go
package tls const ( VersionTLS10 = 0x0301 VersionTLS11 = 0x0302 VersionTLS12 = 0x0303 VersionTLS13 = 0x0304 // Deprecated: SSLv3 is cryptographically broken, and is no longer // supported by this package. See golang.org/issue/32716. VersionSSL30 = 0x0300 )
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/common/redir/tproxy_other.go
Bcore/windows/resources/sing-box-main/common/redir/tproxy_other.go
//go:build !linux package redir import ( "net/netip" "os" "github.com/sagernet/sing/common/control" ) func TProxy(fd uintptr, isIPv6 bool) error { return os.ErrInvalid } func TProxyWriteBack() control.Func { return nil } func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) { return netip.AddrPort{}, 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/common/redir/redir_darwin.go
Bcore/windows/resources/sing-box-main/common/redir/redir_darwin.go
package redir import ( "net" "net/netip" "syscall" "unsafe" M "github.com/sagernet/sing/common/metadata" ) const ( PF_OUT = 0x2 DIOCNATLOOK = 0xc0544417 ) func GetOriginalDestination(conn net.Conn) (destination netip.AddrPort, err error) { fd, err := syscall.Open("/dev/pf", 0, syscall.O_RDONLY) if err != nil { return netip.AddrPort{}, err } defer syscall.Close(fd) nl := struct { saddr, daddr, rsaddr, rdaddr [16]byte sxport, dxport, rsxport, rdxport [4]byte af, proto, protoVariant, direction uint8 }{ af: syscall.AF_INET, proto: syscall.IPPROTO_TCP, direction: PF_OUT, } la := conn.LocalAddr().(*net.TCPAddr) ra := conn.RemoteAddr().(*net.TCPAddr) raIP, laIP := ra.IP, la.IP raPort, laPort := ra.Port, la.Port switch { case raIP.To4() != nil: copy(nl.saddr[:net.IPv4len], raIP.To4()) copy(nl.daddr[:net.IPv4len], laIP.To4()) nl.af = syscall.AF_INET default: copy(nl.saddr[:], raIP.To16()) copy(nl.daddr[:], laIP.To16()) nl.af = syscall.AF_INET6 } nl.sxport[0], nl.sxport[1] = byte(raPort>>8), byte(raPort) nl.dxport[0], nl.dxport[1] = byte(laPort>>8), byte(laPort) if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), DIOCNATLOOK, uintptr(unsafe.Pointer(&nl))); errno != 0 { return netip.AddrPort{}, errno } var ip net.IP switch nl.af { case syscall.AF_INET: ip = make(net.IP, net.IPv4len) copy(ip, nl.rdaddr[:net.IPv4len]) case syscall.AF_INET6: ip = make(net.IP, net.IPv6len) copy(ip, nl.rdaddr[:]) } port := uint16(nl.rdxport[0])<<8 | uint16(nl.rdxport[1]) destination = netip.AddrPortFrom(M.AddrFromIP(ip), port) return }
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/common/redir/redir_other.go
Bcore/windows/resources/sing-box-main/common/redir/redir_other.go
//go:build !linux && !darwin package redir import ( "net" "net/netip" "os" ) func GetOriginalDestination(conn net.Conn) (destination netip.AddrPort, err error) { return netip.AddrPort{}, 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/common/redir/tproxy_linux.go
Bcore/windows/resources/sing-box-main/common/redir/tproxy_linux.go
package redir import ( "encoding/binary" "net/netip" "syscall" "github.com/sagernet/sing/common/control" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" "golang.org/x/sys/unix" ) func TProxy(fd uintptr, isIPv6 bool) error { err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1) if err == nil { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1) } if err == nil && isIPv6 { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, unix.IPV6_TRANSPARENT, 1) } if err == nil { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR, 1) } if err == nil && isIPv6 { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, unix.IPV6_RECVORIGDSTADDR, 1) } return err } func TProxyWriteBack() control.Func { return func(network, address string, conn syscall.RawConn) error { return control.Raw(conn, func(fd uintptr) error { if M.ParseSocksaddr(address).Addr.Is6() { return syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, unix.IPV6_TRANSPARENT, 1) } else { return syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1) } }) } } func GetOriginalDestinationFromOOB(oob []byte) (netip.AddrPort, error) { controlMessages, err := unix.ParseSocketControlMessage(oob) if err != nil { return netip.AddrPort{}, err } for _, message := range controlMessages { if message.Header.Level == unix.SOL_IP && message.Header.Type == unix.IP_RECVORIGDSTADDR { return netip.AddrPortFrom(M.AddrFromIP(message.Data[4:8]), binary.BigEndian.Uint16(message.Data[2:4])), nil } else if message.Header.Level == unix.SOL_IPV6 && message.Header.Type == unix.IPV6_RECVORIGDSTADDR { return netip.AddrPortFrom(M.AddrFromIP(message.Data[8:24]), binary.BigEndian.Uint16(message.Data[2:4])), nil } } return netip.AddrPort{}, E.New("not found") }
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/common/redir/redir_linux.go
Bcore/windows/resources/sing-box-main/common/redir/redir_linux.go
package redir import ( "encoding/binary" "net" "net/netip" "os" "syscall" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/control" M "github.com/sagernet/sing/common/metadata" ) func GetOriginalDestination(conn net.Conn) (destination netip.AddrPort, err error) { syscallConn, ok := common.Cast[syscall.Conn](conn) if !ok { return netip.AddrPort{}, os.ErrInvalid } err = control.Conn(syscallConn, func(fd uintptr) error { const SO_ORIGINAL_DST = 80 if conn.RemoteAddr().(*net.TCPAddr).IP.To4() != nil { raw, err := syscall.GetsockoptIPv6Mreq(int(fd), syscall.IPPROTO_IP, SO_ORIGINAL_DST) if err != nil { return err } destination = netip.AddrPortFrom(M.AddrFromIP(raw.Multiaddr[4:8]), uint16(raw.Multiaddr[2])<<8+uint16(raw.Multiaddr[3])) } else { raw, err := syscall.GetsockoptIPv6MTUInfo(int(fd), syscall.IPPROTO_IPV6, SO_ORIGINAL_DST) if err != nil { return err } var port [2]byte binary.BigEndian.PutUint16(port[:], raw.Addr.Port) destination = netip.AddrPortFrom(M.AddrFromIP(raw.Addr.Addr[:]), binary.LittleEndian.Uint16(port[:])) } return nil }) return }
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/common/srs/ip_set.go
Bcore/windows/resources/sing-box-main/common/srs/ip_set.go
package srs import ( "encoding/binary" "net/netip" "os" "unsafe" "github.com/sagernet/sing/common" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/varbin" "go4.org/netipx" ) type myIPSet struct { rr []myIPRange } type myIPRange struct { from netip.Addr to netip.Addr } type myIPRangeData struct { From []byte To []byte } func readIPSet(reader varbin.Reader) (*netipx.IPSet, error) { version, err := reader.ReadByte() if err != nil { return nil, err } if version != 1 { return nil, os.ErrInvalid } // WTF why using uint64 here var length uint64 err = binary.Read(reader, binary.BigEndian, &length) if err != nil { return nil, err } ranges := make([]myIPRangeData, length) err = varbin.Read(reader, binary.BigEndian, &ranges) if err != nil { return nil, err } mySet := &myIPSet{ rr: make([]myIPRange, len(ranges)), } for i, rangeData := range ranges { mySet.rr[i].from = M.AddrFromIP(rangeData.From) mySet.rr[i].to = M.AddrFromIP(rangeData.To) } return (*netipx.IPSet)(unsafe.Pointer(mySet)), nil } func writeIPSet(writer varbin.Writer, set *netipx.IPSet) error { err := writer.WriteByte(1) if err != nil { return err } dataList := common.Map((*myIPSet)(unsafe.Pointer(set)).rr, func(rr myIPRange) myIPRangeData { return myIPRangeData{ From: rr.from.AsSlice(), To: rr.to.AsSlice(), } }) err = binary.Write(writer, binary.BigEndian, uint64(len(dataList))) if err != nil { return err } for _, data := range dataList { err = varbin.Write(writer, binary.BigEndian, data) 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/common/srs/binary.go
Bcore/windows/resources/sing-box-main/common/srs/binary.go
package srs import ( "bufio" "compress/zlib" "encoding/binary" "io" "net/netip" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/domain" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/varbin" "go4.org/netipx" ) var MagicBytes = [3]byte{0x53, 0x52, 0x53} // SRS const ( ruleItemQueryType uint8 = iota ruleItemNetwork ruleItemDomain ruleItemDomainKeyword ruleItemDomainRegex ruleItemSourceIPCIDR ruleItemIPCIDR ruleItemSourcePort ruleItemSourcePortRange ruleItemPort ruleItemPortRange ruleItemProcessName ruleItemProcessPath ruleItemPackageName ruleItemWIFISSID ruleItemWIFIBSSID ruleItemAdGuardDomain ruleItemProcessPathRegex ruleItemFinal uint8 = 0xFF ) func Read(reader io.Reader, recover bool) (ruleSet option.PlainRuleSet, err error) { var magicBytes [3]byte _, err = io.ReadFull(reader, magicBytes[:]) if err != nil { return } if magicBytes != MagicBytes { err = E.New("invalid sing-box rule-set file") return } var version uint8 err = binary.Read(reader, binary.BigEndian, &version) if err != nil { return ruleSet, err } if version > C.RuleSetVersion2 { return ruleSet, E.New("unsupported version: ", version) } compressReader, err := zlib.NewReader(reader) if err != nil { return } bReader := bufio.NewReader(compressReader) length, err := binary.ReadUvarint(bReader) if err != nil { return } ruleSet.Rules = make([]option.HeadlessRule, length) for i := uint64(0); i < length; i++ { ruleSet.Rules[i], err = readRule(bReader, recover) if err != nil { err = E.Cause(err, "read rule[", i, "]") return } } return } func Write(writer io.Writer, ruleSet option.PlainRuleSet, generateUnstable bool) error { _, err := writer.Write(MagicBytes[:]) if err != nil { return err } var version uint8 if generateUnstable { version = C.RuleSetVersion2 } else { version = C.RuleSetVersion1 } err = binary.Write(writer, binary.BigEndian, version) if err != nil { return err } compressWriter, err := zlib.NewWriterLevel(writer, zlib.BestCompression) if err != nil { return err } bWriter := bufio.NewWriter(compressWriter) _, err = varbin.WriteUvarint(bWriter, uint64(len(ruleSet.Rules))) if err != nil { return err } for _, rule := range ruleSet.Rules { err = writeRule(bWriter, rule, generateUnstable) if err != nil { return err } } err = bWriter.Flush() if err != nil { return err } return compressWriter.Close() } func readRule(reader varbin.Reader, recover bool) (rule option.HeadlessRule, err error) { var ruleType uint8 err = binary.Read(reader, binary.BigEndian, &ruleType) if err != nil { return } switch ruleType { case 0: rule.Type = C.RuleTypeDefault rule.DefaultOptions, err = readDefaultRule(reader, recover) case 1: rule.Type = C.RuleTypeLogical rule.LogicalOptions, err = readLogicalRule(reader, recover) default: err = E.New("unknown rule type: ", ruleType) } return } func writeRule(writer varbin.Writer, rule option.HeadlessRule, generateUnstable bool) error { switch rule.Type { case C.RuleTypeDefault: return writeDefaultRule(writer, rule.DefaultOptions, generateUnstable) case C.RuleTypeLogical: return writeLogicalRule(writer, rule.LogicalOptions, generateUnstable) default: panic("unknown rule type: " + rule.Type) } } func readDefaultRule(reader varbin.Reader, recover bool) (rule option.DefaultHeadlessRule, err error) { var lastItemType uint8 for { var itemType uint8 err = binary.Read(reader, binary.BigEndian, &itemType) if err != nil { return } switch itemType { case ruleItemQueryType: var rawQueryType []uint16 rawQueryType, err = readRuleItemUint16(reader) if err != nil { return } rule.QueryType = common.Map(rawQueryType, func(it uint16) option.DNSQueryType { return option.DNSQueryType(it) }) case ruleItemNetwork: rule.Network, err = readRuleItemString(reader) case ruleItemDomain: var matcher *domain.Matcher matcher, err = domain.ReadMatcher(reader) if err != nil { return } rule.DomainMatcher = matcher if recover { rule.Domain, rule.DomainSuffix = matcher.Dump() } case ruleItemDomainKeyword: rule.DomainKeyword, err = readRuleItemString(reader) case ruleItemDomainRegex: rule.DomainRegex, err = readRuleItemString(reader) case ruleItemSourceIPCIDR: rule.SourceIPSet, err = readIPSet(reader) if err != nil { return } if recover { rule.SourceIPCIDR = common.Map(rule.SourceIPSet.Prefixes(), netip.Prefix.String) } case ruleItemIPCIDR: rule.IPSet, err = readIPSet(reader) if err != nil { return } if recover { rule.IPCIDR = common.Map(rule.IPSet.Prefixes(), netip.Prefix.String) } case ruleItemSourcePort: rule.SourcePort, err = readRuleItemUint16(reader) case ruleItemSourcePortRange: rule.SourcePortRange, err = readRuleItemString(reader) case ruleItemPort: rule.Port, err = readRuleItemUint16(reader) case ruleItemPortRange: rule.PortRange, err = readRuleItemString(reader) case ruleItemProcessName: rule.ProcessName, err = readRuleItemString(reader) case ruleItemProcessPath: rule.ProcessPath, err = readRuleItemString(reader) case ruleItemProcessPathRegex: rule.ProcessPathRegex, err = readRuleItemString(reader) case ruleItemPackageName: rule.PackageName, err = readRuleItemString(reader) case ruleItemWIFISSID: rule.WIFISSID, err = readRuleItemString(reader) case ruleItemWIFIBSSID: rule.WIFIBSSID, err = readRuleItemString(reader) case ruleItemAdGuardDomain: if recover { err = E.New("unable to decompile binary AdGuard rules to rule-set") return } var matcher *domain.AdGuardMatcher matcher, err = domain.ReadAdGuardMatcher(reader) if err != nil { return } rule.AdGuardDomainMatcher = matcher case ruleItemFinal: err = binary.Read(reader, binary.BigEndian, &rule.Invert) return default: err = E.New("unknown rule item type: ", itemType, ", last type: ", lastItemType) } if err != nil { return } lastItemType = itemType } } func writeDefaultRule(writer varbin.Writer, rule option.DefaultHeadlessRule, generateUnstable bool) error { err := binary.Write(writer, binary.BigEndian, uint8(0)) if err != nil { return err } if len(rule.QueryType) > 0 { err = writeRuleItemUint16(writer, ruleItemQueryType, common.Map(rule.QueryType, func(it option.DNSQueryType) uint16 { return uint16(it) })) if err != nil { return err } } if len(rule.Network) > 0 { err = writeRuleItemString(writer, ruleItemNetwork, rule.Network) if err != nil { return err } } if len(rule.Domain) > 0 || len(rule.DomainSuffix) > 0 { err = binary.Write(writer, binary.BigEndian, ruleItemDomain) if err != nil { return err } err = domain.NewMatcher(rule.Domain, rule.DomainSuffix, !generateUnstable).Write(writer) if err != nil { return err } } if len(rule.DomainKeyword) > 0 { err = writeRuleItemString(writer, ruleItemDomainKeyword, rule.DomainKeyword) if err != nil { return err } } if len(rule.DomainRegex) > 0 { err = writeRuleItemString(writer, ruleItemDomainRegex, rule.DomainRegex) if err != nil { return err } } if len(rule.SourceIPCIDR) > 0 { err = writeRuleItemCIDR(writer, ruleItemSourceIPCIDR, rule.SourceIPCIDR) if err != nil { return E.Cause(err, "source_ip_cidr") } } if len(rule.IPCIDR) > 0 { err = writeRuleItemCIDR(writer, ruleItemIPCIDR, rule.IPCIDR) if err != nil { return E.Cause(err, "ipcidr") } } if len(rule.SourcePort) > 0 { err = writeRuleItemUint16(writer, ruleItemSourcePort, rule.SourcePort) if err != nil { return err } } if len(rule.SourcePortRange) > 0 { err = writeRuleItemString(writer, ruleItemSourcePortRange, rule.SourcePortRange) if err != nil { return err } } if len(rule.Port) > 0 { err = writeRuleItemUint16(writer, ruleItemPort, rule.Port) if err != nil { return err } } if len(rule.PortRange) > 0 { err = writeRuleItemString(writer, ruleItemPortRange, rule.PortRange) if err != nil { return err } } if len(rule.ProcessName) > 0 { err = writeRuleItemString(writer, ruleItemProcessName, rule.ProcessName) if err != nil { return err } } if len(rule.ProcessPath) > 0 { err = writeRuleItemString(writer, ruleItemProcessPath, rule.ProcessPath) if err != nil { return err } } if len(rule.ProcessPathRegex) > 0 { err = writeRuleItemString(writer, ruleItemProcessPathRegex, rule.ProcessPathRegex) if err != nil { return err } } if len(rule.PackageName) > 0 { err = writeRuleItemString(writer, ruleItemPackageName, rule.PackageName) if err != nil { return err } } if len(rule.WIFISSID) > 0 { err = writeRuleItemString(writer, ruleItemWIFISSID, rule.WIFISSID) if err != nil { return err } } if len(rule.WIFIBSSID) > 0 { err = writeRuleItemString(writer, ruleItemWIFIBSSID, rule.WIFIBSSID) if err != nil { return err } } if len(rule.AdGuardDomain) > 0 { err = binary.Write(writer, binary.BigEndian, ruleItemAdGuardDomain) if err != nil { return err } err = domain.NewAdGuardMatcher(rule.AdGuardDomain).Write(writer) if err != nil { return err } } err = binary.Write(writer, binary.BigEndian, ruleItemFinal) if err != nil { return err } err = binary.Write(writer, binary.BigEndian, rule.Invert) if err != nil { return err } return nil } func readRuleItemString(reader varbin.Reader) ([]string, error) { return varbin.ReadValue[[]string](reader, binary.BigEndian) } func writeRuleItemString(writer varbin.Writer, itemType uint8, value []string) error { err := writer.WriteByte(itemType) if err != nil { return err } return varbin.Write(writer, binary.BigEndian, value) } func readRuleItemUint16(reader varbin.Reader) ([]uint16, error) { return varbin.ReadValue[[]uint16](reader, binary.BigEndian) } func writeRuleItemUint16(writer varbin.Writer, itemType uint8, value []uint16) error { err := writer.WriteByte(itemType) if err != nil { return err } return varbin.Write(writer, binary.BigEndian, value) } func writeRuleItemCIDR(writer varbin.Writer, itemType uint8, value []string) error { var builder netipx.IPSetBuilder for i, prefixString := range value { prefix, err := netip.ParsePrefix(prefixString) if err == nil { builder.AddPrefix(prefix) continue } addr, addrErr := netip.ParseAddr(prefixString) if addrErr == nil { builder.Add(addr) continue } return E.Cause(err, "parse [", i, "]") } ipSet, err := builder.IPSet() if err != nil { return err } err = binary.Write(writer, binary.BigEndian, itemType) if err != nil { return err } return writeIPSet(writer, ipSet) } func readLogicalRule(reader varbin.Reader, recovery bool) (logicalRule option.LogicalHeadlessRule, err error) { mode, err := reader.ReadByte() if err != nil { return } switch mode { case 0: logicalRule.Mode = C.LogicalTypeAnd case 1: logicalRule.Mode = C.LogicalTypeOr default: err = E.New("unknown logical mode: ", mode) return } length, err := binary.ReadUvarint(reader) if err != nil { return } logicalRule.Rules = make([]option.HeadlessRule, length) for i := uint64(0); i < length; i++ { logicalRule.Rules[i], err = readRule(reader, recovery) if err != nil { err = E.Cause(err, "read logical rule [", i, "]") return } } err = binary.Read(reader, binary.BigEndian, &logicalRule.Invert) if err != nil { return } return } func writeLogicalRule(writer varbin.Writer, logicalRule option.LogicalHeadlessRule, generateUnstable bool) error { err := binary.Write(writer, binary.BigEndian, uint8(1)) if err != nil { return err } switch logicalRule.Mode { case C.LogicalTypeAnd: err = binary.Write(writer, binary.BigEndian, uint8(0)) case C.LogicalTypeOr: err = binary.Write(writer, binary.BigEndian, uint8(1)) default: panic("unknown logical mode: " + logicalRule.Mode) } if err != nil { return err } _, err = varbin.WriteUvarint(writer, uint64(len(logicalRule.Rules))) if err != nil { return err } for _, rule := range logicalRule.Rules { err = writeRule(writer, rule, generateUnstable) if err != nil { return err } } err = binary.Write(writer, binary.BigEndian, logicalRule.Invert) 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/common/uot/router.go
Bcore/windows/resources/sing-box-main/common/uot/router.go
package uot import ( "context" "net" "net/netip" "github.com/sagernet/sing-box/adapter" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/logger" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" "github.com/sagernet/sing/common/uot" ) var _ adapter.ConnectionRouter = (*Router)(nil) type Router struct { router adapter.ConnectionRouter logger logger.ContextLogger } func NewRouter(router adapter.ConnectionRouter, logger logger.ContextLogger) *Router { return &Router{router, logger} } func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { switch metadata.Destination.Fqdn { case uot.MagicAddress: request, err := uot.ReadRequest(conn) if err != nil { return E.Cause(err, "read UoT request") } if request.IsConnect { r.logger.InfoContext(ctx, "inbound UoT connect connection to ", request.Destination) } else { r.logger.InfoContext(ctx, "inbound UoT connection to ", request.Destination) } metadata.Domain = metadata.Destination.Fqdn metadata.Destination = request.Destination return r.router.RoutePacketConnection(ctx, uot.NewConn(conn, *request), metadata) case uot.LegacyMagicAddress: r.logger.InfoContext(ctx, "inbound legacy UoT connection") metadata.Domain = metadata.Destination.Fqdn metadata.Destination = M.Socksaddr{Addr: netip.IPv4Unspecified()} return r.RoutePacketConnection(ctx, uot.NewConn(conn, uot.Request{}), metadata) } return r.router.RouteConnection(ctx, conn, metadata) } func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return r.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/common/pipelistener/listener.go
Bcore/windows/resources/sing-box-main/common/pipelistener/listener.go
package pipelistener import ( "io" "net" ) var _ net.Listener = (*Listener)(nil) type Listener struct { pipe chan net.Conn done chan struct{} } func New(channelSize int) *Listener { return &Listener{ pipe: make(chan net.Conn, channelSize), done: make(chan struct{}), } } func (l *Listener) Serve(conn net.Conn) { l.pipe <- conn } func (l *Listener) Accept() (net.Conn, error) { select { case conn := <-l.pipe: return conn, nil case <-l.done: return nil, io.ErrClosedPipe } } func (l *Listener) Close() error { select { case <-l.done: return io.ErrClosedPipe default: } close(l.done) return nil } func (l *Listener) Addr() net.Addr { return addr{} } type addr struct{} func (a addr) Network() string { return "pipe" } func (a addr) String() string { return "pipe" }
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/common/settings/time_stub.go
Bcore/windows/resources/sing-box-main/common/settings/time_stub.go
//go:build !(windows || linux || darwin) package settings import ( "os" "time" ) func SetSystemTime(nowTime time.Time) 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/common/settings/proxy_linux.go
Bcore/windows/resources/sing-box-main/common/settings/proxy_linux.go
//go:build linux && !android package settings import ( "context" "os" "os/exec" "strings" "github.com/sagernet/sing/common" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/shell" ) type LinuxSystemProxy struct { hasGSettings bool kWriteConfigCmd string sudoUser string serverAddr M.Socksaddr supportSOCKS bool isEnabled bool } func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (*LinuxSystemProxy, error) { hasGSettings := common.Error(exec.LookPath("gsettings")) == nil kWriteConfigCmds := []string{ "kwriteconfig5", "kwriteconfig6", } var kWriteConfigCmd string for _, cmd := range kWriteConfigCmds { if common.Error(exec.LookPath(cmd)) == nil { kWriteConfigCmd = cmd break } } var sudoUser string if os.Getuid() == 0 { sudoUser = os.Getenv("SUDO_USER") } if !hasGSettings && kWriteConfigCmd == "" { return nil, E.New("unsupported desktop environment") } return &LinuxSystemProxy{ hasGSettings: hasGSettings, kWriteConfigCmd: kWriteConfigCmd, sudoUser: sudoUser, serverAddr: serverAddr, supportSOCKS: supportSOCKS, }, nil } func (p *LinuxSystemProxy) IsEnabled() bool { return p.isEnabled } func (p *LinuxSystemProxy) Enable() error { if p.hasGSettings { err := p.runAsUser("gsettings", "set", "org.gnome.system.proxy.http", "enabled", "true") if err != nil { return err } if p.supportSOCKS { err = p.setGnomeProxy("ftp", "http", "https", "socks") } else { err = p.setGnomeProxy("http", "https") } if err != nil { return err } err = p.runAsUser("gsettings", "set", "org.gnome.system.proxy", "use-same-proxy", F.ToString(p.supportSOCKS)) if err != nil { return err } err = p.runAsUser("gsettings", "set", "org.gnome.system.proxy", "mode", "manual") if err != nil { return err } } if p.kWriteConfigCmd != "" { err := p.runAsUser(p.kWriteConfigCmd, "--file", "kioslaverc", "--group", "Proxy Settings", "--key", "ProxyType", "1") if err != nil { return err } if p.supportSOCKS { err = p.setKDEProxy("ftp", "http", "https", "socks") } else { err = p.setKDEProxy("http", "https") } if err != nil { return err } err = p.runAsUser(p.kWriteConfigCmd, "--file", "kioslaverc", "--group", "Proxy Settings", "--key", "Authmode", "0") if err != nil { return err } err = p.runAsUser("dbus-send", "--type=signal", "/KIO/Scheduler", "org.kde.KIO.Scheduler.reparseSlaveConfiguration", "string:''") if err != nil { return err } } p.isEnabled = true return nil } func (p *LinuxSystemProxy) Disable() error { if p.hasGSettings { err := p.runAsUser("gsettings", "set", "org.gnome.system.proxy", "mode", "none") if err != nil { return err } } if p.kWriteConfigCmd != "" { err := p.runAsUser(p.kWriteConfigCmd, "--file", "kioslaverc", "--group", "Proxy Settings", "--key", "ProxyType", "0") if err != nil { return err } err = p.runAsUser("dbus-send", "--type=signal", "/KIO/Scheduler", "org.kde.KIO.Scheduler.reparseSlaveConfiguration", "string:''") if err != nil { return err } } p.isEnabled = false return nil } func (p *LinuxSystemProxy) runAsUser(name string, args ...string) error { if os.Getuid() != 0 { return shell.Exec(name, args...).Attach().Run() } else if p.sudoUser != "" { return shell.Exec("su", "-", p.sudoUser, "-c", F.ToString(name, " ", strings.Join(args, " "))).Attach().Run() } else { return E.New("set system proxy: unable to set as root") } } func (p *LinuxSystemProxy) setGnomeProxy(proxyTypes ...string) error { for _, proxyType := range proxyTypes { err := p.runAsUser("gsettings", "set", "org.gnome.system.proxy."+proxyType, "host", p.serverAddr.AddrString()) if err != nil { return err } err = p.runAsUser("gsettings", "set", "org.gnome.system.proxy."+proxyType, "port", F.ToString(p.serverAddr.Port)) if err != nil { return err } } return nil } func (p *LinuxSystemProxy) setKDEProxy(proxyTypes ...string) error { for _, proxyType := range proxyTypes { var proxyUrl string if proxyType == "socks" { proxyUrl = "socks://" + p.serverAddr.String() } else { proxyUrl = "http://" + p.serverAddr.String() } err := p.runAsUser( p.kWriteConfigCmd, "--file", "kioslaverc", "--group", "Proxy Settings", "--key", proxyType+"Proxy", proxyUrl, ) 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/common/settings/time_unix.go
Bcore/windows/resources/sing-box-main/common/settings/time_unix.go
//go:build linux || darwin package settings import ( "time" "golang.org/x/sys/unix" ) func SetSystemTime(nowTime time.Time) error { timeVal := unix.NsecToTimeval(nowTime.UnixNano()) return unix.Settimeofday(&timeVal) }
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/common/settings/system_proxy.go
Bcore/windows/resources/sing-box-main/common/settings/system_proxy.go
package settings type SystemProxy interface { IsEnabled() bool Enable() error Disable() 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/common/settings/time_windows.go
Bcore/windows/resources/sing-box-main/common/settings/time_windows.go
package settings import ( "time" "unsafe" "golang.org/x/sys/windows" ) func SetSystemTime(nowTime time.Time) error { var systemTime windows.Systemtime systemTime.Year = uint16(nowTime.Year()) systemTime.Month = uint16(nowTime.Month()) systemTime.Day = uint16(nowTime.Day()) systemTime.Hour = uint16(nowTime.Hour()) systemTime.Minute = uint16(nowTime.Minute()) systemTime.Second = uint16(nowTime.Second()) systemTime.Milliseconds = uint16(nowTime.UnixMilli() - nowTime.Unix()*1000) dllKernel32 := windows.NewLazySystemDLL("kernel32.dll") proc := dllKernel32.NewProc("SetSystemTime") _, _, err := proc.Call( uintptr(unsafe.Pointer(&systemTime)), ) if err != nil && err.Error() != "The operation completed successfully." { 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/common/settings/proxy_darwin.go
Bcore/windows/resources/sing-box-main/common/settings/proxy_darwin.go
package settings import ( "context" "net/netip" "strconv" "strings" "github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-tun" E "github.com/sagernet/sing/common/exceptions" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/shell" "github.com/sagernet/sing/common/x/list" ) type DarwinSystemProxy struct { monitor tun.DefaultInterfaceMonitor interfaceName string element *list.Element[tun.DefaultInterfaceUpdateCallback] serverAddr M.Socksaddr supportSOCKS bool isEnabled bool } func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (*DarwinSystemProxy, error) { interfaceMonitor := adapter.RouterFromContext(ctx).InterfaceMonitor() if interfaceMonitor == nil { return nil, E.New("missing interface monitor") } proxy := &DarwinSystemProxy{ monitor: interfaceMonitor, serverAddr: serverAddr, supportSOCKS: supportSOCKS, } proxy.element = interfaceMonitor.RegisterCallback(proxy.update) return proxy, nil } func (p *DarwinSystemProxy) IsEnabled() bool { return p.isEnabled } func (p *DarwinSystemProxy) Enable() error { return p.update0() } func (p *DarwinSystemProxy) Disable() error { interfaceDisplayName, err := getInterfaceDisplayName(p.interfaceName) if err != nil { return err } if p.supportSOCKS { err = shell.Exec("networksetup", "-setsocksfirewallproxystate", interfaceDisplayName, "off").Attach().Run() } if err == nil { err = shell.Exec("networksetup", "-setwebproxystate", interfaceDisplayName, "off").Attach().Run() } if err == nil { err = shell.Exec("networksetup", "-setsecurewebproxystate", interfaceDisplayName, "off").Attach().Run() } if err == nil { p.isEnabled = false } return err } func (p *DarwinSystemProxy) update(event int) { if event&tun.EventInterfaceUpdate == 0 { return } if !p.isEnabled { return } _ = p.update0() } func (p *DarwinSystemProxy) update0() error { newInterfaceName := p.monitor.DefaultInterfaceName(netip.IPv4Unspecified()) if p.interfaceName == newInterfaceName { return nil } if p.interfaceName != "" { _ = p.Disable() } p.interfaceName = newInterfaceName interfaceDisplayName, err := getInterfaceDisplayName(p.interfaceName) if err != nil { return err } if p.supportSOCKS { err = shell.Exec("networksetup", "-setsocksfirewallproxy", interfaceDisplayName, p.serverAddr.AddrString(), strconv.Itoa(int(p.serverAddr.Port))).Attach().Run() } if err != nil { return err } err = shell.Exec("networksetup", "-setwebproxy", interfaceDisplayName, p.serverAddr.AddrString(), strconv.Itoa(int(p.serverAddr.Port))).Attach().Run() if err != nil { return err } err = shell.Exec("networksetup", "-setsecurewebproxy", interfaceDisplayName, p.serverAddr.AddrString(), strconv.Itoa(int(p.serverAddr.Port))).Attach().Run() if err != nil { return err } p.isEnabled = true return nil } func getInterfaceDisplayName(name string) (string, error) { content, err := shell.Exec("networksetup", "-listallhardwareports").ReadOutput() if err != nil { return "", err } for _, deviceSpan := range strings.Split(string(content), "Ethernet Address") { if strings.Contains(deviceSpan, "Device: "+name) { substr := "Hardware Port: " deviceSpan = deviceSpan[strings.Index(deviceSpan, substr)+len(substr):] deviceSpan = deviceSpan[:strings.Index(deviceSpan, "\n")] return deviceSpan, nil } } return "", E.New(name, " not found in networksetup -listallhardwareports") }
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/common/settings/proxy_stub.go
Bcore/windows/resources/sing-box-main/common/settings/proxy_stub.go
//go:build !(windows || linux || darwin) package settings import ( "context" "os" M "github.com/sagernet/sing/common/metadata" ) func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (SystemProxy, 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/common/settings/proxy_windows.go
Bcore/windows/resources/sing-box-main/common/settings/proxy_windows.go
package settings import ( "context" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/wininet" ) type WindowsSystemProxy struct { serverAddr M.Socksaddr supportSOCKS bool isEnabled bool } func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (*WindowsSystemProxy, error) { return &WindowsSystemProxy{ serverAddr: serverAddr, supportSOCKS: supportSOCKS, }, nil } func (p *WindowsSystemProxy) IsEnabled() bool { return p.isEnabled } func (p *WindowsSystemProxy) Enable() error { err := wininet.SetSystemProxy("http://"+p.serverAddr.String(), "") if err != nil { return err } p.isEnabled = true return nil } func (p *WindowsSystemProxy) Disable() error { err := wininet.ClearSystemProxy() if err != nil { return err } p.isEnabled = false 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/common/settings/proxy_android.go
Bcore/windows/resources/sing-box-main/common/settings/proxy_android.go
package settings import ( "context" "os" "strings" C "github.com/sagernet/sing-box/constant" E "github.com/sagernet/sing/common/exceptions" F "github.com/sagernet/sing/common/format" M "github.com/sagernet/sing/common/metadata" "github.com/sagernet/sing/common/shell" ) type AndroidSystemProxy struct { useRish bool rishPath string serverAddr M.Socksaddr supportSOCKS bool isEnabled bool } func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (*AndroidSystemProxy, error) { userId := os.Getuid() var ( useRish bool rishPath string ) if userId == 0 || userId == 1000 || userId == 2000 { useRish = false } else { rishPath, useRish = C.FindPath("rish") if !useRish { return nil, E.Cause(os.ErrPermission, "root or system (adb) permission is required for set system proxy") } } return &AndroidSystemProxy{ useRish: useRish, rishPath: rishPath, serverAddr: serverAddr, supportSOCKS: supportSOCKS, }, nil } func (p *AndroidSystemProxy) IsEnabled() bool { return p.isEnabled } func (p *AndroidSystemProxy) Enable() error { err := p.runAndroidShell("settings", "put", "global", "http_proxy", p.serverAddr.String()) if err != nil { return err } p.isEnabled = true return nil } func (p *AndroidSystemProxy) Disable() error { err := p.runAndroidShell("settings", "put", "global", "http_proxy", ":0") if err != nil { return err } p.isEnabled = false return nil } func (p *AndroidSystemProxy) runAndroidShell(name string, args ...string) error { if !p.useRish { return shell.Exec(name, args...).Attach().Run() } else { return shell.Exec("sh", p.rishPath, "-c", F.ToString(name, " ", strings.Join(args, " "))).Attach().Run() } }
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/common/geosite/geosite_test.go
Bcore/windows/resources/sing-box-main/common/geosite/geosite_test.go
package geosite_test import ( "bytes" "testing" "github.com/sagernet/sing-box/common/geosite" "github.com/stretchr/testify/require" ) func TestGeosite(t *testing.T) { t.Parallel() var buffer bytes.Buffer err := geosite.Write(&buffer, map[string][]geosite.Item{ "test": { { Type: geosite.RuleTypeDomain, Value: "example.org", }, }, }) require.NoError(t, err) reader, codes, err := geosite.NewReader(bytes.NewReader(buffer.Bytes())) require.NoError(t, err) require.Equal(t, []string{"test"}, codes) items, err := reader.Read("test") require.NoError(t, err) require.Equal(t, []geosite.Item{{ Type: geosite.RuleTypeDomain, Value: "example.org", }}, items) }
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/common/geosite/writer.go
Bcore/windows/resources/sing-box-main/common/geosite/writer.go
package geosite import ( "bytes" "encoding/binary" "sort" "github.com/sagernet/sing/common/varbin" ) func Write(writer varbin.Writer, domains map[string][]Item) error { keys := make([]string, 0, len(domains)) for code := range domains { keys = append(keys, code) } sort.Strings(keys) content := &bytes.Buffer{} index := make(map[string]int) for _, code := range keys { index[code] = content.Len() for _, item := range domains[code] { err := varbin.Write(content, binary.BigEndian, item) if err != nil { return err } } } err := writer.WriteByte(0) if err != nil { return err } _, err = varbin.WriteUvarint(writer, uint64(len(keys))) if err != nil { return err } for _, code := range keys { err = varbin.Write(writer, binary.BigEndian, code) if err != nil { return err } _, err = varbin.WriteUvarint(writer, uint64(index[code])) if err != nil { return err } _, err = varbin.WriteUvarint(writer, uint64(len(domains[code]))) if err != nil { return err } } _, err = writer.Write(content.Bytes()) 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/common/geosite/reader.go
Bcore/windows/resources/sing-box-main/common/geosite/reader.go
package geosite import ( "bufio" "encoding/binary" "io" "os" "sync" "sync/atomic" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/varbin" ) type Reader struct { access sync.Mutex reader io.ReadSeeker bufferedReader *bufio.Reader metadataIndex int64 domainIndex map[string]int domainLength map[string]int } func Open(path string) (*Reader, []string, error) { content, err := os.Open(path) if err != nil { return nil, nil, err } reader, codes, err := NewReader(content) if err != nil { content.Close() return nil, nil, err } return reader, codes, nil } func NewReader(readSeeker io.ReadSeeker) (*Reader, []string, error) { reader := &Reader{ reader: readSeeker, } err := reader.readMetadata() if err != nil { return nil, nil, err } codes := make([]string, 0, len(reader.domainIndex)) for code := range reader.domainIndex { codes = append(codes, code) } return reader, codes, nil } type geositeMetadata struct { Code string Index uint64 Length uint64 } func (r *Reader) readMetadata() error { counter := &readCounter{Reader: r.reader} reader := bufio.NewReader(counter) version, err := reader.ReadByte() if err != nil { return err } if version != 0 { return E.New("unknown version") } entryLength, err := binary.ReadUvarint(reader) if err != nil { return err } keys := make([]string, entryLength) domainIndex := make(map[string]int) domainLength := make(map[string]int) for i := 0; i < int(entryLength); i++ { var ( code string codeIndex uint64 codeLength uint64 ) code, err = varbin.ReadValue[string](reader, binary.BigEndian) if err != nil { return err } keys[i] = code codeIndex, err = binary.ReadUvarint(reader) if err != nil { return err } codeLength, err = binary.ReadUvarint(reader) if err != nil { return err } domainIndex[code] = int(codeIndex) domainLength[code] = int(codeLength) } r.domainIndex = domainIndex r.domainLength = domainLength r.metadataIndex = counter.count - int64(reader.Buffered()) r.bufferedReader = reader return nil } func (r *Reader) Read(code string) ([]Item, error) { index, exists := r.domainIndex[code] if !exists { return nil, E.New("code ", code, " not exists!") } _, err := r.reader.Seek(r.metadataIndex+int64(index), io.SeekStart) if err != nil { return nil, err } r.bufferedReader.Reset(r.reader) itemList := make([]Item, r.domainLength[code]) err = varbin.Read(r.bufferedReader, binary.BigEndian, &itemList) if err != nil { return nil, err } return itemList, nil } func (r *Reader) Upstream() any { return r.reader } type readCounter struct { io.Reader count int64 } func (r *readCounter) Read(p []byte) (n int, err error) { n, err = r.Reader.Read(p) if n > 0 { atomic.AddInt64(&r.count, int64(n)) } return }
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/common/geosite/rule.go
Bcore/windows/resources/sing-box-main/common/geosite/rule.go
package geosite import "github.com/sagernet/sing-box/option" type ItemType = uint8 const ( RuleTypeDomain ItemType = iota RuleTypeDomainSuffix RuleTypeDomainKeyword RuleTypeDomainRegex ) type Item struct { Type ItemType Value string } func Compile(code []Item) option.DefaultRule { var domainLength int var domainSuffixLength int var domainKeywordLength int var domainRegexLength int for _, item := range code { switch item.Type { case RuleTypeDomain: domainLength++ case RuleTypeDomainSuffix: domainSuffixLength++ case RuleTypeDomainKeyword: domainKeywordLength++ case RuleTypeDomainRegex: domainRegexLength++ } } var codeRule option.DefaultRule if domainLength > 0 { codeRule.Domain = make([]string, 0, domainLength) } if domainSuffixLength > 0 { codeRule.DomainSuffix = make([]string, 0, domainSuffixLength) } if domainKeywordLength > 0 { codeRule.DomainKeyword = make([]string, 0, domainKeywordLength) } if domainRegexLength > 0 { codeRule.DomainRegex = make([]string, 0, domainRegexLength) } for _, item := range code { switch item.Type { case RuleTypeDomain: codeRule.Domain = append(codeRule.Domain, item.Value) case RuleTypeDomainSuffix: codeRule.DomainSuffix = append(codeRule.DomainSuffix, item.Value) case RuleTypeDomainKeyword: codeRule.DomainKeyword = append(codeRule.DomainKeyword, item.Value) case RuleTypeDomainRegex: codeRule.DomainRegex = append(codeRule.DomainRegex, item.Value) } } return codeRule } func Merge(rules []option.DefaultRule) option.DefaultRule { var domainLength int var domainSuffixLength int var domainKeywordLength int var domainRegexLength int for _, subRule := range rules { domainLength += len(subRule.Domain) domainSuffixLength += len(subRule.DomainSuffix) domainKeywordLength += len(subRule.DomainKeyword) domainRegexLength += len(subRule.DomainRegex) } var rule option.DefaultRule if domainLength > 0 { rule.Domain = make([]string, 0, domainLength) } if domainSuffixLength > 0 { rule.DomainSuffix = make([]string, 0, domainSuffixLength) } if domainKeywordLength > 0 { rule.DomainKeyword = make([]string, 0, domainKeywordLength) } if domainRegexLength > 0 { rule.DomainRegex = make([]string, 0, domainRegexLength) } for _, subRule := range rules { if len(subRule.Domain) > 0 { rule.Domain = append(rule.Domain, subRule.Domain...) } if len(subRule.DomainSuffix) > 0 { rule.DomainSuffix = append(rule.DomainSuffix, subRule.DomainSuffix...) } if len(subRule.DomainKeyword) > 0 { rule.DomainKeyword = append(rule.DomainKeyword, subRule.DomainKeyword...) } if len(subRule.DomainRegex) > 0 { rule.DomainRegex = append(rule.DomainRegex, subRule.DomainRegex...) } } return rule }
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/common/mux/client.go
Bcore/windows/resources/sing-box-main/common/mux/client.go
package mux import ( "context" "net" "github.com/sagernet/sing-box/adapter" C "github.com/sagernet/sing-box/constant" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-mux" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/logger" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type Client = mux.Client func NewClientWithOptions(dialer N.Dialer, logger logger.Logger, options option.OutboundMultiplexOptions) (*Client, error) { if !options.Enabled { return nil, nil } var brutalOptions mux.BrutalOptions if options.Brutal != nil && options.Brutal.Enabled { brutalOptions = mux.BrutalOptions{ Enabled: true, SendBPS: uint64(options.Brutal.UpMbps * C.MbpsToBps), ReceiveBPS: uint64(options.Brutal.DownMbps * C.MbpsToBps), } if brutalOptions.SendBPS < mux.BrutalMinSpeedBPS { return nil, E.New("brutal: invalid upload speed") } if brutalOptions.ReceiveBPS < mux.BrutalMinSpeedBPS { return nil, E.New("brutal: invalid download speed") } } return mux.NewClient(mux.Options{ Dialer: &clientDialer{dialer}, Logger: logger, Protocol: options.Protocol, MaxConnections: options.MaxConnections, MinStreams: options.MinStreams, MaxStreams: options.MaxStreams, Padding: options.Padding, Brutal: brutalOptions, }) } type clientDialer struct { N.Dialer } func (d *clientDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) { return d.Dialer.DialContext(adapter.OverrideContext(ctx), network, destination) } func (d *clientDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) { return d.Dialer.ListenPacket(adapter.OverrideContext(ctx), 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/common/mux/router.go
Bcore/windows/resources/sing-box-main/common/mux/router.go
package mux 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-box/option" "github.com/sagernet/sing-mux" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/logger" N "github.com/sagernet/sing/common/network" ) type Router struct { router adapter.ConnectionRouter service *mux.Service } func NewRouterWithOptions(router adapter.ConnectionRouter, logger logger.ContextLogger, options option.InboundMultiplexOptions) (adapter.ConnectionRouter, error) { if !options.Enabled { return router, nil } var brutalOptions mux.BrutalOptions if options.Brutal != nil && options.Brutal.Enabled { brutalOptions = mux.BrutalOptions{ Enabled: true, SendBPS: uint64(options.Brutal.UpMbps * C.MbpsToBps), ReceiveBPS: uint64(options.Brutal.DownMbps * C.MbpsToBps), } if brutalOptions.SendBPS < mux.BrutalMinSpeedBPS { return nil, E.New("brutal: invalid upload speed") } if brutalOptions.ReceiveBPS < mux.BrutalMinSpeedBPS { return nil, E.New("brutal: invalid download speed") } } service, err := mux.NewService(mux.ServiceOptions{ NewStreamContext: func(ctx context.Context, conn net.Conn) context.Context { return log.ContextWithNewID(ctx) }, Logger: logger, Handler: adapter.NewRouteContextHandler(router, logger), Padding: options.Padding, Brutal: brutalOptions, }) if err != nil { return nil, err } return &Router{router, service}, nil } func (r *Router) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { if metadata.Destination == mux.Destination { return r.service.NewConnection(adapter.WithContext(ctx, &metadata), conn, adapter.UpstreamMetadata(metadata)) } else { return r.router.RouteConnection(ctx, conn, metadata) } } func (r *Router) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return r.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/common/mux/v2ray_legacy.go
Bcore/windows/resources/sing-box-main/common/mux/v2ray_legacy.go
package mux import ( "context" "net" "github.com/sagernet/sing-box/adapter" vmess "github.com/sagernet/sing-vmess" "github.com/sagernet/sing/common/logger" N "github.com/sagernet/sing/common/network" ) type V2RayLegacyRouter struct { router adapter.ConnectionRouter logger logger.ContextLogger } func NewV2RayLegacyRouter(router adapter.ConnectionRouter, logger logger.ContextLogger) adapter.ConnectionRouter { return &V2RayLegacyRouter{router, logger} } func (r *V2RayLegacyRouter) RouteConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error { if metadata.Destination.Fqdn == vmess.MuxDestination.Fqdn { r.logger.InfoContext(ctx, "inbound legacy multiplex connection") return vmess.HandleMuxConnection(ctx, conn, adapter.NewRouteHandler(metadata, r.router, r.logger)) } return r.router.RouteConnection(ctx, conn, metadata) } func (r *V2RayLegacyRouter) RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error { return r.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/common/urltest/urltest.go
Bcore/windows/resources/sing-box-main/common/urltest/urltest.go
package urltest import ( "context" "net" "net/http" "net/url" "sync" "time" "github.com/sagernet/sing/common" M "github.com/sagernet/sing/common/metadata" N "github.com/sagernet/sing/common/network" ) type History struct { Time time.Time `json:"time"` Delay uint16 `json:"delay"` } type HistoryStorage struct { access sync.RWMutex delayHistory map[string]*History updateHook chan<- struct{} } func NewHistoryStorage() *HistoryStorage { return &HistoryStorage{ delayHistory: make(map[string]*History), } } func (s *HistoryStorage) SetHook(hook chan<- struct{}) { s.updateHook = hook } func (s *HistoryStorage) LoadURLTestHistory(tag string) *History { if s == nil { return nil } s.access.RLock() defer s.access.RUnlock() return s.delayHistory[tag] } func (s *HistoryStorage) DeleteURLTestHistory(tag string) { s.access.Lock() delete(s.delayHistory, tag) s.access.Unlock() s.notifyUpdated() } func (s *HistoryStorage) StoreURLTestHistory(tag string, history *History) { s.access.Lock() s.delayHistory[tag] = history s.access.Unlock() s.notifyUpdated() } func (s *HistoryStorage) notifyUpdated() { updateHook := s.updateHook if updateHook != nil { select { case updateHook <- struct{}{}: default: } } } func (s *HistoryStorage) Close() error { s.updateHook = nil return nil } func URLTest(ctx context.Context, link string, detour N.Dialer) (t uint16, err error) { if link == "" { link = "https://www.gstatic.com/generate_204" } linkURL, err := url.Parse(link) if err != nil { return } hostname := linkURL.Hostname() port := linkURL.Port() if port == "" { switch linkURL.Scheme { case "http": port = "80" case "https": port = "443" } } start := time.Now() instance, err := detour.DialContext(ctx, "tcp", M.ParseSocksaddrHostPortStr(hostname, port)) if err != nil { return } defer instance.Close() if earlyConn, isEarlyConn := common.Cast[N.EarlyConn](instance); isEarlyConn && earlyConn.NeedHandshake() { start = time.Now() } req, err := http.NewRequest(http.MethodHead, link, nil) if err != nil { return } client := http.Client{ Transport: &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return instance, nil }, }, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } defer client.CloseIdleConnections() resp, err := client.Do(req.WithContext(ctx)) if err != nil { return } resp.Body.Close() t = uint16(time.Since(start) / time.Millisecond) return }
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/common/ja3/parser.go
Bcore/windows/resources/sing-box-main/common/ja3/parser.go
// Copyright (c) 2018, Open Systems AG. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. package ja3 import ( "encoding/binary" "strconv" ) const ( // Constants used for parsing recordLayerHeaderLen int = 5 handshakeHeaderLen int = 6 randomDataLen int = 32 sessionIDHeaderLen int = 1 cipherSuiteHeaderLen int = 2 compressMethodHeaderLen int = 1 extensionsHeaderLen int = 2 extensionHeaderLen int = 4 sniExtensionHeaderLen int = 5 ecExtensionHeaderLen int = 2 ecpfExtensionHeaderLen int = 1 versionExtensionHeaderLen int = 1 signatureAlgorithmsExtensionHeaderLen int = 2 contentType uint8 = 22 handshakeType uint8 = 1 sniExtensionType uint16 = 0 sniNameDNSHostnameType uint8 = 0 ecExtensionType uint16 = 10 ecpfExtensionType uint16 = 11 versionExtensionType uint16 = 43 signatureAlgorithmsExtensionType uint16 = 13 // Versions // The bitmask covers the versions SSL3.0 to TLS1.2 tlsVersionBitmask uint16 = 0xFFFC tls13 uint16 = 0x0304 // GREASE values // The bitmask covers all GREASE values GreaseBitmask uint16 = 0x0F0F // Constants used for marshalling dashByte = byte(45) commaByte = byte(44) ) // parseSegment to populate the corresponding ClientHello object or return an error func (j *ClientHello) parseSegment(segment []byte) error { // Check if we can decode the next fields if len(segment) < recordLayerHeaderLen { return &ParseError{LengthErr, 1} } // Check if we have "Content Type: Handshake (22)" contType := uint8(segment[0]) if contType != contentType { return &ParseError{errType: ContentTypeErr} } // Check if TLS record layer version is supported tlsRecordVersion := uint16(segment[1])<<8 | uint16(segment[2]) if tlsRecordVersion&tlsVersionBitmask != 0x0300 && tlsRecordVersion != tls13 { return &ParseError{VersionErr, 1} } // Check that the Handshake is as long as expected from the length field segmentLen := uint16(segment[3])<<8 | uint16(segment[4]) if len(segment[recordLayerHeaderLen:]) < int(segmentLen) { return &ParseError{LengthErr, 2} } // Keep the Handshake messege, ignore any additional following record types hs := segment[recordLayerHeaderLen : recordLayerHeaderLen+int(segmentLen)] err := j.parseHandshake(hs) return err } // parseHandshake body func (j *ClientHello) parseHandshake(hs []byte) error { // Check if we can decode the next fields if len(hs) < handshakeHeaderLen+randomDataLen+sessionIDHeaderLen { return &ParseError{LengthErr, 3} } // Check if we have "Handshake Type: Client Hello (1)" handshType := uint8(hs[0]) if handshType != handshakeType { return &ParseError{errType: HandshakeTypeErr} } // Check if actual length of handshake matches (this is a great exclusion criterion for false positives, // as these fields have to match the actual length of the rest of the segment) handshakeLen := uint32(hs[1])<<16 | uint32(hs[2])<<8 | uint32(hs[3]) if len(hs[4:]) != int(handshakeLen) { return &ParseError{LengthErr, 4} } // Check if Client Hello version is supported tlsVersion := uint16(hs[4])<<8 | uint16(hs[5]) if tlsVersion&tlsVersionBitmask != 0x0300 && tlsVersion != tls13 { return &ParseError{VersionErr, 2} } j.Version = tlsVersion // Check if we can decode the next fields sessionIDLen := uint8(hs[38]) if len(hs) < handshakeHeaderLen+randomDataLen+sessionIDHeaderLen+int(sessionIDLen) { return &ParseError{LengthErr, 5} } // Cipher Suites cs := hs[handshakeHeaderLen+randomDataLen+sessionIDHeaderLen+int(sessionIDLen):] // Check if we can decode the next fields if len(cs) < cipherSuiteHeaderLen { return &ParseError{LengthErr, 6} } csLen := uint16(cs[0])<<8 | uint16(cs[1]) numCiphers := int(csLen / 2) cipherSuites := make([]uint16, 0, numCiphers) // Check if we can decode the next fields if len(cs) < cipherSuiteHeaderLen+int(csLen)+compressMethodHeaderLen { return &ParseError{LengthErr, 7} } for i := 0; i < numCiphers; i++ { cipherSuite := uint16(cs[2+i<<1])<<8 | uint16(cs[3+i<<1]) cipherSuites = append(cipherSuites, cipherSuite) } j.CipherSuites = cipherSuites // Check if we can decode the next fields compressMethodLen := uint16(cs[cipherSuiteHeaderLen+int(csLen)]) if len(cs) < cipherSuiteHeaderLen+int(csLen)+compressMethodHeaderLen+int(compressMethodLen) { return &ParseError{LengthErr, 8} } // Extensions exs := cs[cipherSuiteHeaderLen+int(csLen)+compressMethodHeaderLen+int(compressMethodLen):] err := j.parseExtensions(exs) return err } // parseExtensions of the handshake func (j *ClientHello) parseExtensions(exs []byte) error { // Check for no extensions, this fields header is nonexistent if no body is used if len(exs) == 0 { return nil } // Check if we can decode the next fields if len(exs) < extensionsHeaderLen { return &ParseError{LengthErr, 9} } exsLen := uint16(exs[0])<<8 | uint16(exs[1]) exs = exs[extensionsHeaderLen:] // Check if we can decode the next fields if len(exs) < int(exsLen) { return &ParseError{LengthErr, 10} } var sni []byte var extensions, ellipticCurves []uint16 var ellipticCurvePF []uint8 var versions []uint16 var signatureAlgorithms []uint16 for len(exs) > 0 { // Check if we can decode the next fields if len(exs) < extensionHeaderLen { return &ParseError{LengthErr, 11} } exType := uint16(exs[0])<<8 | uint16(exs[1]) exLen := uint16(exs[2])<<8 | uint16(exs[3]) // Ignore any GREASE extensions extensions = append(extensions, exType) // Check if we can decode the next fields if len(exs) < extensionHeaderLen+int(exLen) { return &ParseError{LengthErr, 12} } sex := exs[extensionHeaderLen : extensionHeaderLen+int(exLen)] switch exType { case sniExtensionType: // Extensions: server_name // Check if we can decode the next fields if len(sex) < sniExtensionHeaderLen { return &ParseError{LengthErr, 13} } sniType := uint8(sex[2]) sniLen := uint16(sex[3])<<8 | uint16(sex[4]) sex = sex[sniExtensionHeaderLen:] // Check if we can decode the next fields if len(sex) != int(sniLen) { return &ParseError{LengthErr, 14} } switch sniType { case sniNameDNSHostnameType: sni = sex default: return &ParseError{errType: SNITypeErr} } case ecExtensionType: // Extensions: supported_groups // Check if we can decode the next fields if len(sex) < ecExtensionHeaderLen { return &ParseError{LengthErr, 15} } ecsLen := uint16(sex[0])<<8 | uint16(sex[1]) numCurves := int(ecsLen / 2) ellipticCurves = make([]uint16, 0, numCurves) sex = sex[ecExtensionHeaderLen:] // Check if we can decode the next fields if len(sex) != int(ecsLen) { return &ParseError{LengthErr, 16} } for i := 0; i < numCurves; i++ { ecType := uint16(sex[i*2])<<8 | uint16(sex[1+i*2]) ellipticCurves = append(ellipticCurves, ecType) } case ecpfExtensionType: // Extensions: ec_point_formats // Check if we can decode the next fields if len(sex) < ecpfExtensionHeaderLen { return &ParseError{LengthErr, 17} } ecpfsLen := uint8(sex[0]) numPF := int(ecpfsLen) ellipticCurvePF = make([]uint8, numPF) sex = sex[ecpfExtensionHeaderLen:] // Check if we can decode the next fields if len(sex) != numPF { return &ParseError{LengthErr, 18} } for i := 0; i < numPF; i++ { ellipticCurvePF[i] = uint8(sex[i]) } case versionExtensionType: if len(sex) < versionExtensionHeaderLen { return &ParseError{LengthErr, 19} } versionsLen := int(sex[0]) for i := 0; i < versionsLen; i += 2 { versions = append(versions, binary.BigEndian.Uint16(sex[1:][i:])) } case signatureAlgorithmsExtensionType: if len(sex) < signatureAlgorithmsExtensionHeaderLen { return &ParseError{LengthErr, 20} } ssaLen := binary.BigEndian.Uint16(sex) for i := 0; i < int(ssaLen); i += 2 { signatureAlgorithms = append(signatureAlgorithms, binary.BigEndian.Uint16(sex[2:][i:])) } } exs = exs[4+exLen:] } j.ServerName = string(sni) j.Extensions = extensions j.EllipticCurves = ellipticCurves j.EllipticCurvePF = ellipticCurvePF j.Versions = versions j.SignatureAlgorithms = signatureAlgorithms return nil } // marshalJA3 into a byte string func (j *ClientHello) marshalJA3() { // An uint16 can contain numbers with up to 5 digits and an uint8 can contain numbers with up to 3 digits, but we // also need a byte for each separating character, except at the end. byteStringLen := 6*(1+len(j.CipherSuites)+len(j.Extensions)+len(j.EllipticCurves)) + 4*len(j.EllipticCurvePF) - 1 byteString := make([]byte, 0, byteStringLen) // Version byteString = strconv.AppendUint(byteString, uint64(j.Version), 10) byteString = append(byteString, commaByte) // Cipher Suites if len(j.CipherSuites) != 0 { for _, val := range j.CipherSuites { if val&GreaseBitmask != 0x0A0A { continue } byteString = strconv.AppendUint(byteString, uint64(val), 10) byteString = append(byteString, dashByte) } // Replace last dash with a comma byteString[len(byteString)-1] = commaByte } else { byteString = append(byteString, commaByte) } // Extensions if len(j.Extensions) != 0 { for _, val := range j.Extensions { if val&GreaseBitmask != 0x0A0A { continue } byteString = strconv.AppendUint(byteString, uint64(val), 10) byteString = append(byteString, dashByte) } // Replace last dash with a comma byteString[len(byteString)-1] = commaByte } else { byteString = append(byteString, commaByte) } // Elliptic curves if len(j.EllipticCurves) != 0 { for _, val := range j.EllipticCurves { if val&GreaseBitmask != 0x0A0A { continue } byteString = strconv.AppendUint(byteString, uint64(val), 10) byteString = append(byteString, dashByte) } // Replace last dash with a comma byteString[len(byteString)-1] = commaByte } else { byteString = append(byteString, commaByte) } // ECPF if len(j.EllipticCurvePF) != 0 { for _, val := range j.EllipticCurvePF { byteString = strconv.AppendUint(byteString, uint64(val), 10) byteString = append(byteString, dashByte) } // Remove last dash byteString = byteString[:len(byteString)-1] } j.ja3ByteString = byteString }
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/common/ja3/error.go
Bcore/windows/resources/sing-box-main/common/ja3/error.go
// Copyright (c) 2018, Open Systems AG. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. package ja3 import "fmt" // Error types const ( LengthErr string = "length check %v failed" ContentTypeErr string = "content type not matching" VersionErr string = "version check %v failed" HandshakeTypeErr string = "handshake type not matching" SNITypeErr string = "SNI type not supported" ) // ParseError can be encountered while parsing a segment type ParseError struct { errType string check int } func (e *ParseError) Error() string { if e.errType == LengthErr || e.errType == VersionErr { return fmt.Sprintf(e.errType, e.check) } return fmt.Sprint(e.errType) }
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/common/ja3/ja3.go
Bcore/windows/resources/sing-box-main/common/ja3/ja3.go
// Copyright (c) 2018, Open Systems AG. All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. package ja3 import ( "crypto/md5" "encoding/hex" "golang.org/x/exp/slices" ) type ClientHello struct { Version uint16 CipherSuites []uint16 Extensions []uint16 EllipticCurves []uint16 EllipticCurvePF []uint8 Versions []uint16 SignatureAlgorithms []uint16 ServerName string ja3ByteString []byte ja3Hash string } func (j *ClientHello) Equals(another *ClientHello, ignoreExtensionsSequence bool) bool { if j.Version != another.Version { return false } if !slices.Equal(j.CipherSuites, another.CipherSuites) { return false } if !ignoreExtensionsSequence && !slices.Equal(j.Extensions, another.Extensions) { return false } if ignoreExtensionsSequence && !slices.Equal(j.Extensions, another.sortedExtensions()) { return false } if !slices.Equal(j.EllipticCurves, another.EllipticCurves) { return false } if !slices.Equal(j.EllipticCurvePF, another.EllipticCurvePF) { return false } if !slices.Equal(j.SignatureAlgorithms, another.SignatureAlgorithms) { return false } return true } func (j *ClientHello) sortedExtensions() []uint16 { extensions := make([]uint16, len(j.Extensions)) copy(extensions, j.Extensions) slices.Sort(extensions) return extensions } func Compute(payload []byte) (*ClientHello, error) { ja3 := ClientHello{} err := ja3.parseSegment(payload) return &ja3, err } func (j *ClientHello) String() string { if j.ja3ByteString == nil { j.marshalJA3() } return string(j.ja3ByteString) } func (j *ClientHello) Hash() string { if j.ja3ByteString == nil { j.marshalJA3() } if j.ja3Hash == "" { h := md5.Sum(j.ja3ByteString) j.ja3Hash = hex.EncodeToString(h[:]) } return j.ja3Hash }
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/common/interrupt/group.go
Bcore/windows/resources/sing-box-main/common/interrupt/group.go
package interrupt import ( "io" "net" "sync" "github.com/sagernet/sing/common/x/list" ) type Group struct { access sync.Mutex connections list.List[*groupConnItem] } type groupConnItem struct { conn io.Closer isExternal bool } func NewGroup() *Group { return &Group{} } func (g *Group) NewConn(conn net.Conn, isExternal bool) net.Conn { g.access.Lock() defer g.access.Unlock() item := g.connections.PushBack(&groupConnItem{conn, isExternal}) return &Conn{Conn: conn, group: g, element: item} } func (g *Group) NewPacketConn(conn net.PacketConn, isExternal bool) net.PacketConn { g.access.Lock() defer g.access.Unlock() item := g.connections.PushBack(&groupConnItem{conn, isExternal}) return &PacketConn{PacketConn: conn, group: g, element: item} } func (g *Group) Interrupt(interruptExternalConnections bool) { g.access.Lock() defer g.access.Unlock() var toDelete []*list.Element[*groupConnItem] for element := g.connections.Front(); element != nil; element = element.Next() { if !element.Value.isExternal || interruptExternalConnections { element.Value.conn.Close() toDelete = append(toDelete, element) } } for _, element := range toDelete { g.connections.Remove(element) } }
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/common/interrupt/conn.go
Bcore/windows/resources/sing-box-main/common/interrupt/conn.go
package interrupt import ( "net" "github.com/sagernet/sing/common/x/list" ) /*type GroupedConn interface { MarkAsInternal() } func MarkAsInternal(conn any) { if groupedConn, isGroupConn := common.Cast[GroupedConn](conn); isGroupConn { groupedConn.MarkAsInternal() } }*/ type Conn struct { net.Conn group *Group element *list.Element[*groupConnItem] } /*func (c *Conn) MarkAsInternal() { c.element.Value.internal = true }*/ func (c *Conn) Close() error { c.group.access.Lock() defer c.group.access.Unlock() c.group.connections.Remove(c.element) return c.Conn.Close() } func (c *Conn) ReaderReplaceable() bool { return true } func (c *Conn) WriterReplaceable() bool { return true } func (c *Conn) Upstream() any { return c.Conn } type PacketConn struct { net.PacketConn group *Group element *list.Element[*groupConnItem] } /*func (c *PacketConn) MarkAsInternal() { c.element.Value.internal = true }*/ func (c *PacketConn) Close() error { c.group.access.Lock() defer c.group.access.Unlock() c.group.connections.Remove(c.element) return c.PacketConn.Close() } func (c *PacketConn) ReaderReplaceable() bool { return true } func (c *PacketConn) WriterReplaceable() bool { return true } func (c *PacketConn) Upstream() any { return c.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/common/interrupt/context.go
Bcore/windows/resources/sing-box-main/common/interrupt/context.go
package interrupt import "context" type contextKeyIsExternalConnection struct{} func ContextWithIsExternalConnection(ctx context.Context) context.Context { return context.WithValue(ctx, contextKeyIsExternalConnection{}, true) } func IsExternalConnectionFromContext(ctx context.Context) bool { return ctx.Value(contextKeyIsExternalConnection{}) != 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/common/humanize/bytes.go
Bcore/windows/resources/sing-box-main/common/humanize/bytes.go
package humanize import ( "fmt" "math" "strconv" "strings" "unicode" ) // IEC Sizes. // kibis of bits const ( Byte = 1 << (iota * 10) KiByte MiByte GiByte TiByte PiByte EiByte ) // SI Sizes. const ( IByte = 1 KByte = IByte * 1000 MByte = KByte * 1000 GByte = MByte * 1000 TByte = GByte * 1000 PByte = TByte * 1000 EByte = PByte * 1000 ) var defaultSizeTable = map[string]uint64{ "b": Byte, "kib": KiByte, "kb": KByte, "mib": MiByte, "mb": MByte, "gib": GiByte, "gb": GByte, "tib": TiByte, "tb": TByte, "pib": PiByte, "pb": PByte, "eib": EiByte, "eb": EByte, // Without suffix "": Byte, "ki": KiByte, "k": KByte, "mi": MiByte, "m": MByte, "gi": GiByte, "g": GByte, "ti": TiByte, "t": TByte, "pi": PiByte, "p": PByte, "ei": EiByte, "e": EByte, } var memorysSizeTable = map[string]uint64{ "b": Byte, "kb": KiByte, "mb": MiByte, "gb": GiByte, "tb": TiByte, "pb": PiByte, "eb": EiByte, "": Byte, "k": KiByte, "m": MiByte, "g": GiByte, "t": TiByte, "p": PiByte, "e": EiByte, } var ( defaultSizes = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"} iSizes = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"} ) func Bytes(s uint64) string { return humanateBytes(s, 1000, defaultSizes) } func MemoryBytes(s uint64) string { return humanateBytes(s, 1024, defaultSizes) } func IBytes(s uint64) string { return humanateBytes(s, 1024, iSizes) } func logn(n, b float64) float64 { return math.Log(n) / math.Log(b) } func humanateBytes(s uint64, base float64, sizes []string) string { if s < 10 { return fmt.Sprintf("%d B", s) } e := math.Floor(logn(float64(s), base)) suffix := sizes[int(e)] val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10 f := "%.0f %s" if val < 10 { f = "%.1f %s" } return fmt.Sprintf(f, val, suffix) } func ParseBytes(s string) (uint64, error) { return parseBytes0(s, defaultSizeTable) } func ParseMemoryBytes(s string) (uint64, error) { return parseBytes0(s, memorysSizeTable) } func parseBytes0(s string, sizeTable map[string]uint64) (uint64, error) { lastDigit := 0 hasComma := false for _, r := range s { if !(unicode.IsDigit(r) || r == '.' || r == ',') { break } if r == ',' { hasComma = true } lastDigit++ } num := s[:lastDigit] if hasComma { num = strings.Replace(num, ",", "", -1) } f, err := strconv.ParseFloat(num, 64) if err != nil { return 0, err } extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) if m, ok := sizeTable[extra]; ok { f *= float64(m) if f >= math.MaxUint64 { return 0, fmt.Errorf("too large: %v", s) } return uint64(f), nil } return 0, fmt.Errorf("unhandled size name: %v", extra) }
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/common/badversion/version_json.go
Bcore/windows/resources/sing-box-main/common/badversion/version_json.go
package badversion import "github.com/sagernet/sing/common/json" func (v Version) MarshalJSON() ([]byte, error) { return json.Marshal(v.String()) } func (v *Version) UnmarshalJSON(data []byte) error { var version string err := json.Unmarshal(data, &version) if err != nil { return err } *v = Parse(version) 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/common/badversion/version_test.go
Bcore/windows/resources/sing-box-main/common/badversion/version_test.go
package badversion import ( "testing" "github.com/stretchr/testify/require" ) func TestCompareVersion(t *testing.T) { t.Parallel() require.Equal(t, "1.3.0-beta.1", Parse("v1.3.0-beta1").String()) require.Equal(t, "1.3-beta1", Parse("v1.3.0-beta.1").BadString()) require.True(t, Parse("1.3.0").After(Parse("1.3-beta1"))) require.True(t, Parse("1.3.0").After(Parse("1.3.0-beta1"))) require.True(t, Parse("1.3.0-beta1").After(Parse("1.3.0-alpha1"))) require.True(t, Parse("1.3.1").After(Parse("1.3.0"))) require.True(t, Parse("1.4").After(Parse("1.3"))) }
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/common/badversion/version.go
Bcore/windows/resources/sing-box-main/common/badversion/version.go
package badversion import ( "strconv" "strings" F "github.com/sagernet/sing/common/format" ) type Version struct { Major int Minor int Patch int Commit string PreReleaseIdentifier string PreReleaseVersion int } func (v Version) After(anotherVersion Version) bool { if v.Major > anotherVersion.Major { return true } else if v.Major < anotherVersion.Major { return false } if v.Minor > anotherVersion.Minor { return true } else if v.Minor < anotherVersion.Minor { return false } if v.Patch > anotherVersion.Patch { return true } else if v.Patch < anotherVersion.Patch { return false } if v.PreReleaseIdentifier == "" && anotherVersion.PreReleaseIdentifier != "" { return true } else if v.PreReleaseIdentifier != "" && anotherVersion.PreReleaseIdentifier == "" { return false } if v.PreReleaseIdentifier != "" && anotherVersion.PreReleaseIdentifier != "" { if v.PreReleaseIdentifier == anotherVersion.PreReleaseIdentifier { if v.PreReleaseVersion > anotherVersion.PreReleaseVersion { return true } else if v.PreReleaseVersion < anotherVersion.PreReleaseVersion { return false } } else if v.PreReleaseIdentifier == "rc" && anotherVersion.PreReleaseIdentifier == "beta" { return true } else if v.PreReleaseIdentifier == "beta" && anotherVersion.PreReleaseIdentifier == "rc" { return false } else if v.PreReleaseIdentifier == "beta" && anotherVersion.PreReleaseIdentifier == "alpha" { return true } else if v.PreReleaseIdentifier == "alpha" && anotherVersion.PreReleaseIdentifier == "beta" { return false } } return false } func (v Version) VersionString() string { return F.ToString(v.Major, ".", v.Minor, ".", v.Patch) } func (v Version) String() string { version := F.ToString(v.Major, ".", v.Minor, ".", v.Patch) if v.PreReleaseIdentifier != "" { version = F.ToString(version, "-", v.PreReleaseIdentifier, ".", v.PreReleaseVersion) } return version } func (v Version) BadString() string { version := F.ToString(v.Major, ".", v.Minor) if v.Patch > 0 { version = F.ToString(version, ".", v.Patch) } if v.PreReleaseIdentifier != "" { version = F.ToString(version, "-", v.PreReleaseIdentifier) if v.PreReleaseVersion > 0 { version = F.ToString(version, v.PreReleaseVersion) } } return version } func Parse(versionName string) (version Version) { if strings.HasPrefix(versionName, "v") { versionName = versionName[1:] } if strings.Contains(versionName, "-") { parts := strings.Split(versionName, "-") versionName = parts[0] identifier := parts[1] if strings.Contains(identifier, ".") { identifierParts := strings.Split(identifier, ".") version.PreReleaseIdentifier = identifierParts[0] if len(identifierParts) >= 2 { version.PreReleaseVersion, _ = strconv.Atoi(identifierParts[1]) } } else { if strings.HasPrefix(identifier, "alpha") { version.PreReleaseIdentifier = "alpha" version.PreReleaseVersion, _ = strconv.Atoi(identifier[5:]) } else if strings.HasPrefix(identifier, "beta") { version.PreReleaseIdentifier = "beta" version.PreReleaseVersion, _ = strconv.Atoi(identifier[4:]) } else { version.Commit = identifier } } } versionElements := strings.Split(versionName, ".") versionLen := len(versionElements) if versionLen >= 1 { version.Major, _ = strconv.Atoi(versionElements[0]) } if versionLen >= 2 { version.Minor, _ = strconv.Atoi(versionElements[1]) } if versionLen >= 3 { version.Patch, _ = strconv.Atoi(versionElements[2]) } return }
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/common/conntrack/track_disable.go
Bcore/windows/resources/sing-box-main/common/conntrack/track_disable.go
//go:build !with_conntrack package conntrack const Enabled = false
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/common/conntrack/killer.go
Bcore/windows/resources/sing-box-main/common/conntrack/killer.go
package conntrack import ( runtimeDebug "runtime/debug" "time" E "github.com/sagernet/sing/common/exceptions" "github.com/sagernet/sing/common/memory" ) var ( KillerEnabled bool MemoryLimit uint64 killerLastCheck time.Time ) func KillerCheck() error { if !KillerEnabled { return nil } nowTime := time.Now() if nowTime.Sub(killerLastCheck) < 3*time.Second { return nil } killerLastCheck = nowTime if memory.Total() > MemoryLimit { Close() go func() { time.Sleep(time.Second) runtimeDebug.FreeOSMemory() }() return E.New("out of memory") } 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/common/conntrack/conn.go
Bcore/windows/resources/sing-box-main/common/conntrack/conn.go
package conntrack import ( "io" "net" "github.com/sagernet/sing/common/x/list" ) type Conn struct { net.Conn element *list.Element[io.Closer] } func NewConn(conn net.Conn) (net.Conn, error) { connAccess.Lock() element := openConnection.PushBack(conn) connAccess.Unlock() if KillerEnabled { err := KillerCheck() if err != nil { conn.Close() return nil, err } } return &Conn{ Conn: conn, element: element, }, nil } func (c *Conn) Close() error { if c.element.Value != nil { connAccess.Lock() if c.element.Value != nil { openConnection.Remove(c.element) c.element.Value = nil } connAccess.Unlock() } return c.Conn.Close() } func (c *Conn) Upstream() any { return c.Conn } func (c *Conn) ReaderReplaceable() bool { return true } func (c *Conn) WriterReplaceable() 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/common/conntrack/packet_conn.go
Bcore/windows/resources/sing-box-main/common/conntrack/packet_conn.go
package conntrack import ( "io" "net" "github.com/sagernet/sing/common/bufio" "github.com/sagernet/sing/common/x/list" ) type PacketConn struct { net.PacketConn element *list.Element[io.Closer] } func NewPacketConn(conn net.PacketConn) (net.PacketConn, error) { connAccess.Lock() element := openConnection.PushBack(conn) connAccess.Unlock() if KillerEnabled { err := KillerCheck() if err != nil { conn.Close() return nil, err } } return &PacketConn{ PacketConn: conn, element: element, }, nil } func (c *PacketConn) Close() error { if c.element.Value != nil { connAccess.Lock() if c.element.Value != nil { openConnection.Remove(c.element) c.element.Value = nil } connAccess.Unlock() } return c.PacketConn.Close() } func (c *PacketConn) Upstream() any { return bufio.NewPacketConn(c.PacketConn) } func (c *PacketConn) ReaderReplaceable() bool { return true } func (c *PacketConn) WriterReplaceable() 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/common/conntrack/track.go
Bcore/windows/resources/sing-box-main/common/conntrack/track.go
package conntrack import ( "io" "sync" "github.com/sagernet/sing/common" "github.com/sagernet/sing/common/x/list" ) var ( connAccess sync.RWMutex openConnection list.List[io.Closer] ) func Count() int { if !Enabled { return 0 } return openConnection.Len() } func List() []io.Closer { if !Enabled { return nil } connAccess.RLock() defer connAccess.RUnlock() connList := make([]io.Closer, 0, openConnection.Len()) for element := openConnection.Front(); element != nil; element = element.Next() { connList = append(connList, element.Value) } return connList } func Close() { if !Enabled { return } connAccess.Lock() defer connAccess.Unlock() for element := openConnection.Front(); element != nil; element = element.Next() { common.Close(element.Value) element.Value = nil } openConnection.Init() }
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/common/conntrack/track_enable.go
Bcore/windows/resources/sing-box-main/common/conntrack/track_enable.go
//go:build with_conntrack package conntrack const Enabled = 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/common/badtls/read_wait_stub.go
Bcore/windows/resources/sing-box-main/common/badtls/read_wait_stub.go
//go:build !go1.21 || without_badtls package badtls import ( "os" "github.com/sagernet/sing/common/tls" ) func NewReadWaitConn(conn tls.Conn) (tls.Conn, 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/common/badtls/read_wait_ech.go
Bcore/windows/resources/sing-box-main/common/badtls/read_wait_ech.go
//go:build go1.21 && !without_badtls && with_ech package badtls import ( "net" _ "unsafe" "github.com/sagernet/cloudflare-tls" "github.com/sagernet/sing/common" ) func init() { tlsRegistry = append(tlsRegistry, func(conn net.Conn) (loaded bool, tlsReadRecord func() error, tlsHandlePostHandshakeMessage func() error) { tlsConn, loaded := common.Cast[*tls.Conn](conn) if !loaded { return } return true, func() error { return echReadRecord(tlsConn) }, func() error { return echHandlePostHandshakeMessage(tlsConn) } }) } //go:linkname echReadRecord github.com/sagernet/cloudflare-tls.(*Conn).readRecord func echReadRecord(c *tls.Conn) error //go:linkname echHandlePostHandshakeMessage github.com/sagernet/cloudflare-tls.(*Conn).handlePostHandshakeMessage func echHandlePostHandshakeMessage(c *tls.Conn) 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/common/badtls/read_wait_utls.go
Bcore/windows/resources/sing-box-main/common/badtls/read_wait_utls.go
//go:build go1.21 && !without_badtls && with_utls package badtls import ( "net" _ "unsafe" "github.com/sagernet/sing/common" "github.com/sagernet/utls" ) func init() { tlsRegistry = append(tlsRegistry, func(conn net.Conn) (loaded bool, tlsReadRecord func() error, tlsHandlePostHandshakeMessage func() error) { tlsConn, loaded := common.Cast[*tls.UConn](conn) if !loaded { return } return true, func() error { return utlsReadRecord(tlsConn.Conn) }, func() error { return utlsHandlePostHandshakeMessage(tlsConn.Conn) } }) } //go:linkname utlsReadRecord github.com/sagernet/utls.(*Conn).readRecord func utlsReadRecord(c *tls.Conn) error //go:linkname utlsHandlePostHandshakeMessage github.com/sagernet/utls.(*Conn).handlePostHandshakeMessage func utlsHandlePostHandshakeMessage(c *tls.Conn) error
go
MIT
8c374326e7569db68ccfb9e0b5c2daa124d44545
2026-01-07T09:45:34.255374Z
false