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
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/filterencoder.go
modules/logging/filterencoder.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "encoding/json" "fmt" "os" "time" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" "golang.org/x/term" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(FilterEncoder{}) } // FilterEncoder can filter (manipulate) fields on // log entries before they are actually encoded by // an underlying encoder. type FilterEncoder struct { // The underlying encoder that actually encodes the // log entries. If not specified, defaults to "json", // unless the output is a terminal, in which case // it defaults to "console". WrappedRaw json.RawMessage `json:"wrap,omitempty" caddy:"namespace=caddy.logging.encoders inline_key=format"` // A map of field names to their filters. Note that this // is not a module map; the keys are field names. // // Nested fields can be referenced by representing a // layer of nesting with `>`. In other words, for an // object like `{"a":{"b":0}}`, the inner field can // be referenced as `a>b`. // // The following fields are fundamental to the log and // cannot be filtered because they are added by the // underlying logging library as special cases: ts, // level, logger, and msg. FieldsRaw map[string]json.RawMessage `json:"fields,omitempty" caddy:"namespace=caddy.logging.encoders.filter inline_key=filter"` wrapped zapcore.Encoder Fields map[string]LogFieldFilter `json:"-"` // used to keep keys unique across nested objects keyPrefix string wrappedIsDefault bool ctx caddy.Context } // CaddyModule returns the Caddy module information. func (FilterEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter", New: func() caddy.Module { return new(FilterEncoder) }, } } // Provision sets up the encoder. func (fe *FilterEncoder) Provision(ctx caddy.Context) error { fe.ctx = ctx if fe.WrappedRaw == nil { // if wrap is not specified, default to JSON fe.wrapped = &JSONEncoder{} if p, ok := fe.wrapped.(caddy.Provisioner); ok { if err := p.Provision(ctx); err != nil { return fmt.Errorf("provisioning fallback encoder module: %v", err) } } fe.wrappedIsDefault = true } else { // set up wrapped encoder val, err := ctx.LoadModule(fe, "WrappedRaw") if err != nil { return fmt.Errorf("loading fallback encoder module: %v", err) } fe.wrapped = val.(zapcore.Encoder) } // set up each field filter if fe.Fields == nil { fe.Fields = make(map[string]LogFieldFilter) } vals, err := ctx.LoadModule(fe, "FieldsRaw") if err != nil { return fmt.Errorf("loading log filter modules: %v", err) } for fieldName, modIface := range vals.(map[string]any) { fe.Fields[fieldName] = modIface.(LogFieldFilter) } return nil } // ConfigureDefaultFormat will set the default format to "console" // if the writer is a terminal. If already configured as a filter // encoder, it passes through the writer so a deeply nested filter // encoder can configure its own default format. func (fe *FilterEncoder) ConfigureDefaultFormat(wo caddy.WriterOpener) error { if !fe.wrappedIsDefault { if cfd, ok := fe.wrapped.(caddy.ConfiguresFormatterDefault); ok { return cfd.ConfigureDefaultFormat(wo) } return nil } if caddy.IsWriterStandardStream(wo) && term.IsTerminal(int(os.Stderr.Fd())) { fe.wrapped = &ConsoleEncoder{} if p, ok := fe.wrapped.(caddy.Provisioner); ok { if err := p.Provision(fe.ctx); err != nil { return fmt.Errorf("provisioning fallback encoder module: %v", err) } } } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // filter { // wrap <another encoder> // fields { // <field> <filter> { // <filter options> // } // } // <field> <filter> { // <filter options> // } // } func (fe *FilterEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume encoder name // Track regexp filters for automatic merging regexpFilters := make(map[string][]*RegexpFilter) // parse a field parseField := func() error { if fe.FieldsRaw == nil { fe.FieldsRaw = make(map[string]json.RawMessage) } field := d.Val() if !d.NextArg() { return d.ArgErr() } filterName := d.Val() moduleID := "caddy.logging.encoders.filter." + filterName unm, err := caddyfile.UnmarshalModule(d, moduleID) if err != nil { return err } filter, ok := unm.(LogFieldFilter) if !ok { return d.Errf("module %s (%T) is not a logging.LogFieldFilter", moduleID, unm) } // Special handling for regexp filters to support multiple instances if regexpFilter, isRegexp := filter.(*RegexpFilter); isRegexp { regexpFilters[field] = append(regexpFilters[field], regexpFilter) return nil // Don't set FieldsRaw yet, we'll merge them later } // Check if we're trying to add a non-regexp filter to a field that already has regexp filters if _, hasRegexpFilters := regexpFilters[field]; hasRegexpFilters { return d.Errf("cannot mix regexp filters with other filter types for field %s", field) } // Check if field already has a filter and it's not regexp-related if _, exists := fe.FieldsRaw[field]; exists { return d.Errf("field %s already has a filter; multiple non-regexp filters per field are not supported", field) } fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(filter, "filter", filterName, nil) return nil } for d.NextBlock(0) { switch d.Val() { case "wrap": if !d.NextArg() { return d.ArgErr() } moduleName := d.Val() moduleID := "caddy.logging.encoders." + moduleName unm, err := caddyfile.UnmarshalModule(d, moduleID) if err != nil { return err } enc, ok := unm.(zapcore.Encoder) if !ok { return d.Errf("module %s (%T) is not a zapcore.Encoder", moduleID, unm) } fe.WrappedRaw = caddyconfig.JSONModuleObject(enc, "format", moduleName, nil) case "fields": for nesting := d.Nesting(); d.NextBlock(nesting); { err := parseField() if err != nil { return err } } default: // if unknown, assume it's a field so that // the config can be flat err := parseField() if err != nil { return err } } } // After parsing all fields, merge multiple regexp filters into MultiRegexpFilter for field, filters := range regexpFilters { if len(filters) == 1 { // Single regexp filter, use the original RegexpFilter fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(filters[0], "filter", "regexp", nil) } else { // Multiple regexp filters, merge into MultiRegexpFilter multiFilter := &MultiRegexpFilter{} for _, regexpFilter := range filters { err := multiFilter.AddOperation(regexpFilter.RawRegexp, regexpFilter.Value) if err != nil { return fmt.Errorf("adding regexp operation for field %s: %v", field, err) } } fe.FieldsRaw[field] = caddyconfig.JSONModuleObject(multiFilter, "filter", "multi_regexp", nil) } } return nil } // AddArray is part of the zapcore.ObjectEncoder interface. // Array elements do not get filtered. func (fe FilterEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { if filter, ok := fe.Fields[fe.keyPrefix+key]; ok { filter.Filter(zap.Array(key, marshaler)).AddTo(fe.wrapped) return nil } return fe.wrapped.AddArray(key, marshaler) } // AddObject is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { if fe.filtered(key, marshaler) { return nil } fe.keyPrefix += key + ">" return fe.wrapped.AddObject(key, logObjectMarshalerWrapper{ enc: fe, marsh: marshaler, }) } // AddBinary is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddBinary(key string, value []byte) { if !fe.filtered(key, value) { fe.wrapped.AddBinary(key, value) } } // AddByteString is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddByteString(key string, value []byte) { if !fe.filtered(key, value) { fe.wrapped.AddByteString(key, value) } } // AddBool is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddBool(key string, value bool) { if !fe.filtered(key, value) { fe.wrapped.AddBool(key, value) } } // AddComplex128 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddComplex128(key string, value complex128) { if !fe.filtered(key, value) { fe.wrapped.AddComplex128(key, value) } } // AddComplex64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddComplex64(key string, value complex64) { if !fe.filtered(key, value) { fe.wrapped.AddComplex64(key, value) } } // AddDuration is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddDuration(key string, value time.Duration) { if !fe.filtered(key, value) { fe.wrapped.AddDuration(key, value) } } // AddFloat64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddFloat64(key string, value float64) { if !fe.filtered(key, value) { fe.wrapped.AddFloat64(key, value) } } // AddFloat32 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddFloat32(key string, value float32) { if !fe.filtered(key, value) { fe.wrapped.AddFloat32(key, value) } } // AddInt is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt(key string, value int) { if !fe.filtered(key, value) { fe.wrapped.AddInt(key, value) } } // AddInt64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt64(key string, value int64) { if !fe.filtered(key, value) { fe.wrapped.AddInt64(key, value) } } // AddInt32 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt32(key string, value int32) { if !fe.filtered(key, value) { fe.wrapped.AddInt32(key, value) } } // AddInt16 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt16(key string, value int16) { if !fe.filtered(key, value) { fe.wrapped.AddInt16(key, value) } } // AddInt8 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddInt8(key string, value int8) { if !fe.filtered(key, value) { fe.wrapped.AddInt8(key, value) } } // AddString is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddString(key, value string) { if !fe.filtered(key, value) { fe.wrapped.AddString(key, value) } } // AddTime is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddTime(key string, value time.Time) { if !fe.filtered(key, value) { fe.wrapped.AddTime(key, value) } } // AddUint is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint(key string, value uint) { if !fe.filtered(key, value) { fe.wrapped.AddUint(key, value) } } // AddUint64 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint64(key string, value uint64) { if !fe.filtered(key, value) { fe.wrapped.AddUint64(key, value) } } // AddUint32 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint32(key string, value uint32) { if !fe.filtered(key, value) { fe.wrapped.AddUint32(key, value) } } // AddUint16 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint16(key string, value uint16) { if !fe.filtered(key, value) { fe.wrapped.AddUint16(key, value) } } // AddUint8 is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUint8(key string, value uint8) { if !fe.filtered(key, value) { fe.wrapped.AddUint8(key, value) } } // AddUintptr is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddUintptr(key string, value uintptr) { if !fe.filtered(key, value) { fe.wrapped.AddUintptr(key, value) } } // AddReflected is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) AddReflected(key string, value any) error { if !fe.filtered(key, value) { return fe.wrapped.AddReflected(key, value) } return nil } // OpenNamespace is part of the zapcore.ObjectEncoder interface. func (fe FilterEncoder) OpenNamespace(key string) { fe.wrapped.OpenNamespace(key) } // Clone is part of the zapcore.ObjectEncoder interface. // We don't use it as of Oct 2019 (v2 beta 7), I'm not // really sure what it'd be useful for in our case. func (fe FilterEncoder) Clone() zapcore.Encoder { return FilterEncoder{ Fields: fe.Fields, wrapped: fe.wrapped.Clone(), keyPrefix: fe.keyPrefix, } } // EncodeEntry partially implements the zapcore.Encoder interface. func (fe FilterEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { // without this clone and storing it to fe.wrapped, fields // from subsequent log entries get appended to previous // ones, and I'm not 100% sure why; see end of // https://github.com/uber-go/zap/issues/750 fe.wrapped = fe.wrapped.Clone() for _, field := range fields { field.AddTo(fe) } return fe.wrapped.EncodeEntry(ent, nil) } // filtered returns true if the field was filtered. // If true is returned, the field was filtered and // added to the underlying encoder (so do not do // that again). If false was returned, the field has // not yet been added to the underlying encoder. func (fe FilterEncoder) filtered(key string, value any) bool { filter, ok := fe.Fields[fe.keyPrefix+key] if !ok { return false } filter.Filter(zap.Any(key, value)).AddTo(fe.wrapped) return true } // logObjectMarshalerWrapper allows us to recursively // filter fields of objects as they get encoded. type logObjectMarshalerWrapper struct { enc FilterEncoder marsh zapcore.ObjectMarshaler } // MarshalLogObject implements the zapcore.ObjectMarshaler interface. func (mom logObjectMarshalerWrapper) MarshalLogObject(_ zapcore.ObjectEncoder) error { return mom.marsh.MarshalLogObject(mom.enc) } // Interface guards var ( _ zapcore.Encoder = (*FilterEncoder)(nil) _ zapcore.ObjectMarshaler = (*logObjectMarshalerWrapper)(nil) _ caddyfile.Unmarshaler = (*FilterEncoder)(nil) _ caddy.ConfiguresFormatterDefault = (*FilterEncoder)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/filters.go
modules/logging/filters.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "crypto/sha256" "errors" "fmt" "net" "net/http" "net/url" "regexp" "strconv" "strings" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(DeleteFilter{}) caddy.RegisterModule(HashFilter{}) caddy.RegisterModule(ReplaceFilter{}) caddy.RegisterModule(IPMaskFilter{}) caddy.RegisterModule(QueryFilter{}) caddy.RegisterModule(CookieFilter{}) caddy.RegisterModule(RegexpFilter{}) caddy.RegisterModule(RenameFilter{}) caddy.RegisterModule(MultiRegexpFilter{}) } // LogFieldFilter can filter (or manipulate) // a field in a log entry. type LogFieldFilter interface { Filter(zapcore.Field) zapcore.Field } // DeleteFilter is a Caddy log field filter that // deletes the field. type DeleteFilter struct{} // CaddyModule returns the Caddy module information. func (DeleteFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.delete", New: func() caddy.Module { return new(DeleteFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (DeleteFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // Filter filters the input field. func (DeleteFilter) Filter(in zapcore.Field) zapcore.Field { in.Type = zapcore.SkipType return in } // hash returns the first 4 bytes of the SHA-256 hash of the given data as hexadecimal func hash(s string) string { return fmt.Sprintf("%.4x", sha256.Sum256([]byte(s))) } // HashFilter is a Caddy log field filter that // replaces the field with the initial 4 bytes // of the SHA-256 hash of the content. Operates // on string fields, or on arrays of strings // where each string is hashed. type HashFilter struct{} // CaddyModule returns the Caddy module information. func (HashFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.hash", New: func() caddy.Module { return new(HashFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *HashFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // Filter filters the input field with the replacement value. func (f *HashFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { newArray := make(caddyhttp.LoggableStringArray, len(array)) for i, s := range array { newArray[i] = hash(s) } in.Interface = newArray } else { in.String = hash(in.String) } return in } // ReplaceFilter is a Caddy log field filter that // replaces the field with the indicated string. type ReplaceFilter struct { Value string `json:"value,omitempty"` } // CaddyModule returns the Caddy module information. func (ReplaceFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.replace", New: func() caddy.Module { return new(ReplaceFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *ReplaceFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name if d.NextArg() { f.Value = d.Val() } return nil } // Filter filters the input field with the replacement value. func (f *ReplaceFilter) Filter(in zapcore.Field) zapcore.Field { in.Type = zapcore.StringType in.String = f.Value return in } // IPMaskFilter is a Caddy log field filter that // masks IP addresses in a string, or in an array // of strings. The string may be a comma separated // list of IP addresses, where all of the values // will be masked. type IPMaskFilter struct { // The IPv4 mask, as an subnet size CIDR. IPv4MaskRaw int `json:"ipv4_cidr,omitempty"` // The IPv6 mask, as an subnet size CIDR. IPv6MaskRaw int `json:"ipv6_cidr,omitempty"` v4Mask net.IPMask v6Mask net.IPMask } // CaddyModule returns the Caddy module information. func (IPMaskFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.ip_mask", New: func() caddy.Module { return new(IPMaskFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (m *IPMaskFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name args := d.RemainingArgs() if len(args) > 2 { return d.Errf("too many arguments") } if len(args) > 0 { val, err := strconv.Atoi(args[0]) if err != nil { return d.Errf("error parsing %s: %v", args[0], err) } m.IPv4MaskRaw = val if len(args) > 1 { val, err := strconv.Atoi(args[1]) if err != nil { return d.Errf("error parsing %s: %v", args[1], err) } m.IPv6MaskRaw = val } } for d.NextBlock(0) { switch d.Val() { case "ipv4": if !d.NextArg() { return d.ArgErr() } val, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("error parsing %s: %v", d.Val(), err) } m.IPv4MaskRaw = val case "ipv6": if !d.NextArg() { return d.ArgErr() } val, err := strconv.Atoi(d.Val()) if err != nil { return d.Errf("error parsing %s: %v", d.Val(), err) } m.IPv6MaskRaw = val default: return d.Errf("unrecognized subdirective %s", d.Val()) } } return nil } // Provision parses m's IP masks, from integers. func (m *IPMaskFilter) Provision(ctx caddy.Context) error { parseRawToMask := func(rawField int, bitLen int) net.IPMask { if rawField == 0 { return nil } // we assume the int is a subnet size CIDR // e.g. "16" being equivalent to masking the last // two bytes of an ipv4 address, like "255.255.0.0" return net.CIDRMask(rawField, bitLen) } m.v4Mask = parseRawToMask(m.IPv4MaskRaw, 32) m.v6Mask = parseRawToMask(m.IPv6MaskRaw, 128) return nil } // Filter filters the input field. func (m IPMaskFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { newArray := make(caddyhttp.LoggableStringArray, len(array)) for i, s := range array { newArray[i] = m.mask(s) } in.Interface = newArray } else { in.String = m.mask(in.String) } return in } func (m IPMaskFilter) mask(s string) string { output := "" for value := range strings.SplitSeq(s, ",") { value = strings.TrimSpace(value) host, port, err := net.SplitHostPort(value) if err != nil { host = value // assume whole thing was IP address } ipAddr := net.ParseIP(host) if ipAddr == nil { output += value + ", " continue } mask := m.v4Mask if ipAddr.To4() == nil { mask = m.v6Mask } masked := ipAddr.Mask(mask) if port == "" { output += masked.String() + ", " continue } output += net.JoinHostPort(masked.String(), port) + ", " } return strings.TrimSuffix(output, ", ") } type filterAction string const ( // Replace value(s). replaceAction filterAction = "replace" // Hash value(s). hashAction filterAction = "hash" // Delete. deleteAction filterAction = "delete" ) func (a filterAction) IsValid() error { switch a { case replaceAction, deleteAction, hashAction: return nil } return errors.New("invalid action type") } type queryFilterAction struct { // `replace` to replace the value(s) associated with the parameter(s), `hash` to replace them with the 4 initial bytes of the SHA-256 of their content or `delete` to remove them entirely. Type filterAction `json:"type"` // The name of the query parameter. Parameter string `json:"parameter"` // The value to use as replacement if the action is `replace`. Value string `json:"value,omitempty"` } // QueryFilter is a Caddy log field filter that filters // query parameters from a URL. // // This filter updates the logged URL string to remove, replace or hash // query parameters containing sensitive data. For instance, it can be // used to redact any kind of secrets which were passed as query parameters, // such as OAuth access tokens, session IDs, magic link tokens, etc. type QueryFilter struct { // A list of actions to apply to the query parameters of the URL. Actions []queryFilterAction `json:"actions"` } // Validate checks that action types are correct. func (f *QueryFilter) Validate() error { for _, a := range f.Actions { if err := a.Type.IsValid(); err != nil { return err } } return nil } // CaddyModule returns the Caddy module information. func (QueryFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.query", New: func() caddy.Module { return new(QueryFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (m *QueryFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name for d.NextBlock(0) { qfa := queryFilterAction{} switch d.Val() { case "replace": if !d.NextArg() { return d.ArgErr() } qfa.Type = replaceAction qfa.Parameter = d.Val() if !d.NextArg() { return d.ArgErr() } qfa.Value = d.Val() case "hash": if !d.NextArg() { return d.ArgErr() } qfa.Type = hashAction qfa.Parameter = d.Val() case "delete": if !d.NextArg() { return d.ArgErr() } qfa.Type = deleteAction qfa.Parameter = d.Val() default: return d.Errf("unrecognized subdirective %s", d.Val()) } m.Actions = append(m.Actions, qfa) } return nil } // Filter filters the input field. func (m QueryFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { newArray := make(caddyhttp.LoggableStringArray, len(array)) for i, s := range array { newArray[i] = m.processQueryString(s) } in.Interface = newArray } else { in.String = m.processQueryString(in.String) } return in } func (m QueryFilter) processQueryString(s string) string { u, err := url.Parse(s) if err != nil { return s } q := u.Query() for _, a := range m.Actions { switch a.Type { case replaceAction: for i := range q[a.Parameter] { q[a.Parameter][i] = a.Value } case hashAction: for i := range q[a.Parameter] { q[a.Parameter][i] = hash(a.Value) } case deleteAction: q.Del(a.Parameter) } } u.RawQuery = q.Encode() return u.String() } type cookieFilterAction struct { // `replace` to replace the value of the cookie, `hash` to replace it with the 4 initial bytes of the SHA-256 of its content or `delete` to remove it entirely. Type filterAction `json:"type"` // The name of the cookie. Name string `json:"name"` // The value to use as replacement if the action is `replace`. Value string `json:"value,omitempty"` } // CookieFilter is a Caddy log field filter that filters // cookies. // // This filter updates the logged HTTP header string // to remove, replace or hash cookies containing sensitive data. For instance, // it can be used to redact any kind of secrets, such as session IDs. // // If several actions are configured for the same cookie name, only the first // will be applied. type CookieFilter struct { // A list of actions to apply to the cookies. Actions []cookieFilterAction `json:"actions"` } // Validate checks that action types are correct. func (f *CookieFilter) Validate() error { for _, a := range f.Actions { if err := a.Type.IsValid(); err != nil { return err } } return nil } // CaddyModule returns the Caddy module information. func (CookieFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.cookie", New: func() caddy.Module { return new(CookieFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (m *CookieFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name for d.NextBlock(0) { cfa := cookieFilterAction{} switch d.Val() { case "replace": if !d.NextArg() { return d.ArgErr() } cfa.Type = replaceAction cfa.Name = d.Val() if !d.NextArg() { return d.ArgErr() } cfa.Value = d.Val() case "hash": if !d.NextArg() { return d.ArgErr() } cfa.Type = hashAction cfa.Name = d.Val() case "delete": if !d.NextArg() { return d.ArgErr() } cfa.Type = deleteAction cfa.Name = d.Val() default: return d.Errf("unrecognized subdirective %s", d.Val()) } m.Actions = append(m.Actions, cfa) } return nil } // Filter filters the input field. func (m CookieFilter) Filter(in zapcore.Field) zapcore.Field { cookiesSlice, ok := in.Interface.(caddyhttp.LoggableStringArray) if !ok { return in } // using a dummy Request to make use of the Cookies() function to parse it originRequest := http.Request{Header: http.Header{"Cookie": cookiesSlice}} cookies := originRequest.Cookies() transformedRequest := http.Request{Header: make(http.Header)} OUTER: for _, c := range cookies { for _, a := range m.Actions { if c.Name != a.Name { continue } switch a.Type { case replaceAction: c.Value = a.Value transformedRequest.AddCookie(c) continue OUTER case hashAction: c.Value = hash(c.Value) transformedRequest.AddCookie(c) continue OUTER case deleteAction: continue OUTER } } transformedRequest.AddCookie(c) } in.Interface = caddyhttp.LoggableStringArray(transformedRequest.Header["Cookie"]) return in } // RegexpFilter is a Caddy log field filter that // replaces the field matching the provided regexp // with the indicated string. If the field is an // array of strings, each of them will have the // regexp replacement applied. type RegexpFilter struct { // The regular expression pattern defining what to replace. RawRegexp string `json:"regexp,omitempty"` // The value to use as replacement Value string `json:"value,omitempty"` regexp *regexp.Regexp } // CaddyModule returns the Caddy module information. func (RegexpFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.regexp", New: func() caddy.Module { return new(RegexpFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *RegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name if d.NextArg() { f.RawRegexp = d.Val() } if d.NextArg() { f.Value = d.Val() } return nil } // Provision compiles m's regexp. func (m *RegexpFilter) Provision(ctx caddy.Context) error { r, err := regexp.Compile(m.RawRegexp) if err != nil { return err } m.regexp = r return nil } // Filter filters the input field with the replacement value if it matches the regexp. func (f *RegexpFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { newArray := make(caddyhttp.LoggableStringArray, len(array)) for i, s := range array { newArray[i] = f.regexp.ReplaceAllString(s, f.Value) } in.Interface = newArray } else { in.String = f.regexp.ReplaceAllString(in.String, f.Value) } return in } // regexpFilterOperation represents a single regexp operation // within a MultiRegexpFilter. type regexpFilterOperation struct { // The regular expression pattern defining what to replace. RawRegexp string `json:"regexp,omitempty"` // The value to use as replacement Value string `json:"value,omitempty"` regexp *regexp.Regexp } // MultiRegexpFilter is a Caddy log field filter that // can apply multiple regular expression replacements to // the same field. This filter processes operations in the // order they are defined, applying each regexp replacement // sequentially to the result of the previous operation. // // This allows users to define multiple regexp filters for // the same field without them overwriting each other. // // Security considerations: // - Uses Go's regexp package (RE2 engine) which is safe from ReDoS attacks // - Validates all patterns during provisioning // - Limits the maximum number of operations to prevent resource exhaustion // - Sanitizes input to prevent injection attacks type MultiRegexpFilter struct { // A list of regexp operations to apply in sequence. // Maximum of 50 operations allowed for security and performance. Operations []regexpFilterOperation `json:"operations"` } // Security constants const ( maxRegexpOperations = 50 // Maximum operations to prevent resource exhaustion maxPatternLength = 1000 // Maximum pattern length to prevent abuse ) // CaddyModule returns the Caddy module information. func (MultiRegexpFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.multi_regexp", New: func() caddy.Module { return new(MultiRegexpFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. // Syntax: // // multi_regexp { // regexp <pattern> <replacement> // regexp <pattern> <replacement> // ... // } func (f *MultiRegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name for d.NextBlock(0) { switch d.Val() { case "regexp": // Security check: limit number of operations if len(f.Operations) >= maxRegexpOperations { return d.Errf("too many regexp operations (maximum %d allowed)", maxRegexpOperations) } op := regexpFilterOperation{} if !d.NextArg() { return d.ArgErr() } op.RawRegexp = d.Val() // Security validation: check pattern length if len(op.RawRegexp) > maxPatternLength { return d.Errf("regexp pattern too long (maximum %d characters)", maxPatternLength) } // Security validation: basic pattern validation if op.RawRegexp == "" { return d.Errf("regexp pattern cannot be empty") } if !d.NextArg() { return d.ArgErr() } op.Value = d.Val() f.Operations = append(f.Operations, op) default: return d.Errf("unrecognized subdirective %s", d.Val()) } } // Security check: ensure at least one operation is defined if len(f.Operations) == 0 { return d.Err("multi_regexp filter requires at least one regexp operation") } return nil } // Provision compiles all regexp patterns with security validation. func (f *MultiRegexpFilter) Provision(ctx caddy.Context) error { // Security check: validate operation count if len(f.Operations) > maxRegexpOperations { return fmt.Errorf("too many regexp operations: %d (maximum %d allowed)", len(f.Operations), maxRegexpOperations) } if len(f.Operations) == 0 { return fmt.Errorf("multi_regexp filter requires at least one operation") } for i := range f.Operations { // Security validation: pattern length check if len(f.Operations[i].RawRegexp) > maxPatternLength { return fmt.Errorf("regexp pattern %d too long: %d characters (maximum %d)", i, len(f.Operations[i].RawRegexp), maxPatternLength) } // Security validation: empty pattern check if f.Operations[i].RawRegexp == "" { return fmt.Errorf("regexp pattern %d cannot be empty", i) } // Compile and validate the pattern (uses RE2 engine - safe from ReDoS) r, err := regexp.Compile(f.Operations[i].RawRegexp) if err != nil { return fmt.Errorf("compiling regexp pattern %d (%s): %v", i, f.Operations[i].RawRegexp, err) } f.Operations[i].regexp = r } return nil } // Validate ensures the filter is properly configured with security checks. func (f *MultiRegexpFilter) Validate() error { if len(f.Operations) == 0 { return fmt.Errorf("multi_regexp filter requires at least one operation") } if len(f.Operations) > maxRegexpOperations { return fmt.Errorf("too many regexp operations: %d (maximum %d allowed)", len(f.Operations), maxRegexpOperations) } for i, op := range f.Operations { if op.RawRegexp == "" { return fmt.Errorf("regexp pattern %d cannot be empty", i) } if len(op.RawRegexp) > maxPatternLength { return fmt.Errorf("regexp pattern %d too long: %d characters (maximum %d)", i, len(op.RawRegexp), maxPatternLength) } if op.regexp == nil { return fmt.Errorf("regexp pattern %d not compiled (call Provision first)", i) } } return nil } // Filter applies all regexp operations sequentially to the input field. // Input is sanitized and validated for security. func (f *MultiRegexpFilter) Filter(in zapcore.Field) zapcore.Field { if array, ok := in.Interface.(caddyhttp.LoggableStringArray); ok { newArray := make(caddyhttp.LoggableStringArray, len(array)) for i, s := range array { newArray[i] = f.processString(s) } in.Interface = newArray } else { in.String = f.processString(in.String) } return in } // processString applies all regexp operations to a single string with input validation. func (f *MultiRegexpFilter) processString(s string) string { // Security: validate input string length to prevent resource exhaustion const maxInputLength = 1000000 // 1MB max input size if len(s) > maxInputLength { // Log warning but continue processing (truncated) s = s[:maxInputLength] } result := s for _, op := range f.Operations { // Each regexp operation is applied sequentially // Using RE2 engine which is safe from ReDoS attacks result = op.regexp.ReplaceAllString(result, op.Value) // Ensure result doesn't exceed max length after each operation if len(result) > maxInputLength { result = result[:maxInputLength] } } return result } // AddOperation adds a single regexp operation to the filter with validation. // This is used when merging multiple RegexpFilter instances. func (f *MultiRegexpFilter) AddOperation(rawRegexp, value string) error { // Security checks if len(f.Operations) >= maxRegexpOperations { return fmt.Errorf("cannot add operation: maximum %d operations allowed", maxRegexpOperations) } if rawRegexp == "" { return fmt.Errorf("regexp pattern cannot be empty") } if len(rawRegexp) > maxPatternLength { return fmt.Errorf("regexp pattern too long: %d characters (maximum %d)", len(rawRegexp), maxPatternLength) } f.Operations = append(f.Operations, regexpFilterOperation{ RawRegexp: rawRegexp, Value: value, }) return nil } // RenameFilter is a Caddy log field filter that // renames the field's key with the indicated name. type RenameFilter struct { Name string `json:"name,omitempty"` } // CaddyModule returns the Caddy module information. func (RenameFilter) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.filter.rename", New: func() caddy.Module { return new(RenameFilter) }, } } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. func (f *RenameFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume filter name if d.NextArg() { f.Name = d.Val() } return nil } // Filter renames the input field with the replacement name. func (f *RenameFilter) Filter(in zapcore.Field) zapcore.Field { in.Key = f.Name return in } // Interface guards var ( _ LogFieldFilter = (*DeleteFilter)(nil) _ LogFieldFilter = (*HashFilter)(nil) _ LogFieldFilter = (*ReplaceFilter)(nil) _ LogFieldFilter = (*IPMaskFilter)(nil) _ LogFieldFilter = (*QueryFilter)(nil) _ LogFieldFilter = (*CookieFilter)(nil) _ LogFieldFilter = (*RegexpFilter)(nil) _ LogFieldFilter = (*RenameFilter)(nil) _ LogFieldFilter = (*MultiRegexpFilter)(nil) _ caddyfile.Unmarshaler = (*DeleteFilter)(nil) _ caddyfile.Unmarshaler = (*HashFilter)(nil) _ caddyfile.Unmarshaler = (*ReplaceFilter)(nil) _ caddyfile.Unmarshaler = (*IPMaskFilter)(nil) _ caddyfile.Unmarshaler = (*QueryFilter)(nil) _ caddyfile.Unmarshaler = (*CookieFilter)(nil) _ caddyfile.Unmarshaler = (*RegexpFilter)(nil) _ caddyfile.Unmarshaler = (*RenameFilter)(nil) _ caddyfile.Unmarshaler = (*MultiRegexpFilter)(nil) _ caddy.Provisioner = (*IPMaskFilter)(nil) _ caddy.Provisioner = (*RegexpFilter)(nil) _ caddy.Provisioner = (*MultiRegexpFilter)(nil) _ caddy.Validator = (*QueryFilter)(nil) _ caddy.Validator = (*MultiRegexpFilter)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/cores.go
modules/logging/cores.go
package logging import ( "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(MockCore{}) } // MockCore is a no-op module, purely for testing type MockCore struct { zapcore.Core `json:"-"` } // CaddyModule returns the Caddy module information. func (MockCore) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.cores.mock", New: func() caddy.Module { return new(MockCore) }, } } func (lec *MockCore) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // Interface guards var ( _ zapcore.Core = (*MockCore)(nil) _ caddy.Module = (*MockCore)(nil) _ caddyfile.Unmarshaler = (*MockCore)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/appendencoder.go
modules/logging/appendencoder.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "encoding/json" "fmt" "os" "strings" "time" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" "golang.org/x/term" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(AppendEncoder{}) } // AppendEncoder can be used to add fields to all log entries // that pass through it. It is a wrapper around another // encoder, which it uses to actually encode the log entries. // It is most useful for adding information about the Caddy // instance that is producing the log entries, possibly via // an environment variable. type AppendEncoder struct { // The underlying encoder that actually encodes the // log entries. If not specified, defaults to "json", // unless the output is a terminal, in which case // it defaults to "console". WrappedRaw json.RawMessage `json:"wrap,omitempty" caddy:"namespace=caddy.logging.encoders inline_key=format"` // A map of field names to their values. The values // can be global placeholders (e.g. env vars), or constants. // Note that the encoder does not run as part of an HTTP // request context, so request placeholders are not available. Fields map[string]any `json:"fields,omitempty"` wrapped zapcore.Encoder repl *caddy.Replacer wrappedIsDefault bool ctx caddy.Context } // CaddyModule returns the Caddy module information. func (AppendEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.append", New: func() caddy.Module { return new(AppendEncoder) }, } } // Provision sets up the encoder. func (fe *AppendEncoder) Provision(ctx caddy.Context) error { fe.ctx = ctx fe.repl = caddy.NewReplacer() if fe.WrappedRaw == nil { // if wrap is not specified, default to JSON fe.wrapped = &JSONEncoder{} if p, ok := fe.wrapped.(caddy.Provisioner); ok { if err := p.Provision(ctx); err != nil { return fmt.Errorf("provisioning fallback encoder module: %v", err) } } fe.wrappedIsDefault = true } else { // set up wrapped encoder val, err := ctx.LoadModule(fe, "WrappedRaw") if err != nil { return fmt.Errorf("loading fallback encoder module: %v", err) } fe.wrapped = val.(zapcore.Encoder) } return nil } // ConfigureDefaultFormat will set the default format to "console" // if the writer is a terminal. If already configured, it passes // through the writer so a deeply nested encoder can configure // its own default format. func (fe *AppendEncoder) ConfigureDefaultFormat(wo caddy.WriterOpener) error { if !fe.wrappedIsDefault { if cfd, ok := fe.wrapped.(caddy.ConfiguresFormatterDefault); ok { return cfd.ConfigureDefaultFormat(wo) } return nil } if caddy.IsWriterStandardStream(wo) && term.IsTerminal(int(os.Stderr.Fd())) { fe.wrapped = &ConsoleEncoder{} if p, ok := fe.wrapped.(caddy.Provisioner); ok { if err := p.Provision(fe.ctx); err != nil { return fmt.Errorf("provisioning fallback encoder module: %v", err) } } } return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // append { // wrap <another encoder> // fields { // <field> <value> // } // <field> <value> // } func (fe *AppendEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume encoder name // parse a field parseField := func() error { if fe.Fields == nil { fe.Fields = make(map[string]any) } field := d.Val() if !d.NextArg() { return d.ArgErr() } fe.Fields[field] = d.ScalarVal() if d.NextArg() { return d.ArgErr() } return nil } for d.NextBlock(0) { switch d.Val() { case "wrap": if !d.NextArg() { return d.ArgErr() } moduleName := d.Val() moduleID := "caddy.logging.encoders." + moduleName unm, err := caddyfile.UnmarshalModule(d, moduleID) if err != nil { return err } enc, ok := unm.(zapcore.Encoder) if !ok { return d.Errf("module %s (%T) is not a zapcore.Encoder", moduleID, unm) } fe.WrappedRaw = caddyconfig.JSONModuleObject(enc, "format", moduleName, nil) case "fields": for nesting := d.Nesting(); d.NextBlock(nesting); { err := parseField() if err != nil { return err } } default: // if unknown, assume it's a field so that // the config can be flat err := parseField() if err != nil { return err } } } return nil } // AddArray is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddArray(key string, marshaler zapcore.ArrayMarshaler) error { return fe.wrapped.AddArray(key, marshaler) } // AddObject is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddObject(key string, marshaler zapcore.ObjectMarshaler) error { return fe.wrapped.AddObject(key, marshaler) } // AddBinary is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddBinary(key string, value []byte) { fe.wrapped.AddBinary(key, value) } // AddByteString is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddByteString(key string, value []byte) { fe.wrapped.AddByteString(key, value) } // AddBool is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddBool(key string, value bool) { fe.wrapped.AddBool(key, value) } // AddComplex128 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddComplex128(key string, value complex128) { fe.wrapped.AddComplex128(key, value) } // AddComplex64 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddComplex64(key string, value complex64) { fe.wrapped.AddComplex64(key, value) } // AddDuration is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddDuration(key string, value time.Duration) { fe.wrapped.AddDuration(key, value) } // AddFloat64 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddFloat64(key string, value float64) { fe.wrapped.AddFloat64(key, value) } // AddFloat32 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddFloat32(key string, value float32) { fe.wrapped.AddFloat32(key, value) } // AddInt is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddInt(key string, value int) { fe.wrapped.AddInt(key, value) } // AddInt64 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddInt64(key string, value int64) { fe.wrapped.AddInt64(key, value) } // AddInt32 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddInt32(key string, value int32) { fe.wrapped.AddInt32(key, value) } // AddInt16 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddInt16(key string, value int16) { fe.wrapped.AddInt16(key, value) } // AddInt8 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddInt8(key string, value int8) { fe.wrapped.AddInt8(key, value) } // AddString is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddString(key, value string) { fe.wrapped.AddString(key, value) } // AddTime is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddTime(key string, value time.Time) { fe.wrapped.AddTime(key, value) } // AddUint is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddUint(key string, value uint) { fe.wrapped.AddUint(key, value) } // AddUint64 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddUint64(key string, value uint64) { fe.wrapped.AddUint64(key, value) } // AddUint32 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddUint32(key string, value uint32) { fe.wrapped.AddUint32(key, value) } // AddUint16 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddUint16(key string, value uint16) { fe.wrapped.AddUint16(key, value) } // AddUint8 is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddUint8(key string, value uint8) { fe.wrapped.AddUint8(key, value) } // AddUintptr is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddUintptr(key string, value uintptr) { fe.wrapped.AddUintptr(key, value) } // AddReflected is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) AddReflected(key string, value any) error { return fe.wrapped.AddReflected(key, value) } // OpenNamespace is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) OpenNamespace(key string) { fe.wrapped.OpenNamespace(key) } // Clone is part of the zapcore.ObjectEncoder interface. func (fe AppendEncoder) Clone() zapcore.Encoder { return AppendEncoder{ Fields: fe.Fields, wrapped: fe.wrapped.Clone(), repl: fe.repl, } } // EncodeEntry partially implements the zapcore.Encoder interface. func (fe AppendEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) { fe.wrapped = fe.wrapped.Clone() for _, field := range fields { field.AddTo(fe) } // append fields from config for key, value := range fe.Fields { // if the value is a string if str, ok := value.(string); ok { isPlaceholder := strings.HasPrefix(str, "{") && strings.HasSuffix(str, "}") && strings.Count(str, "{") == 1 if isPlaceholder { // and it looks like a placeholder, evaluate it replaced, _ := fe.repl.Get(strings.Trim(str, "{}")) zap.Any(key, replaced).AddTo(fe) } else { // just use the string as-is zap.String(key, str).AddTo(fe) } } else { // not a string, so use the value as any zap.Any(key, value).AddTo(fe) } } return fe.wrapped.EncodeEntry(ent, nil) } // Interface guards var ( _ zapcore.Encoder = (*AppendEncoder)(nil) _ caddyfile.Unmarshaler = (*AppendEncoder)(nil) _ caddy.ConfiguresFormatterDefault = (*AppendEncoder)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/filewriter_test_windows.go
modules/logging/filewriter_test_windows.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build windows package logging import ( "os" "path" "testing" ) // Windows relies on ACLs instead of unix permissions model. // Go allows to open files with a particular mode put it is limited to read or write. // See https://cs.opensource.google/go/go/+/refs/tags/go1.22.3:src/syscall/syscall_windows.go;l=708. // This is pretty restrictive and has few interest for log files and thus we just test that log files are // opened with R/W permissions by default on Windows too. func TestFileCreationMode(t *testing.T) { dir, err := os.MkdirTemp("", "caddytest") if err != nil { t.Fatalf("failed to create tempdir: %v", err) } defer os.RemoveAll(dir) fw := &FileWriter{ Filename: path.Join(dir, "test.log"), } logger, err := fw.OpenWriter() if err != nil { t.Fatalf("failed to create file: %v", err) } defer logger.Close() st, err := os.Stat(fw.Filename) if err != nil { t.Fatalf("failed to check file permissions: %v", err) } if st.Mode().Perm()&0o600 != 0o600 { t.Fatalf("file mode is %v, want rw for user", st.Mode().Perm()) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/logging/encoders.go
modules/logging/encoders.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package logging import ( "time" "go.uber.org/zap" "go.uber.org/zap/buffer" "go.uber.org/zap/zapcore" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(ConsoleEncoder{}) caddy.RegisterModule(JSONEncoder{}) } // ConsoleEncoder encodes log entries that are mostly human-readable. type ConsoleEncoder struct { zapcore.Encoder `json:"-"` LogEncoderConfig } // CaddyModule returns the Caddy module information. func (ConsoleEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.console", New: func() caddy.Module { return new(ConsoleEncoder) }, } } // Provision sets up the encoder. func (ce *ConsoleEncoder) Provision(_ caddy.Context) error { if ce.LevelFormat == "" { ce.LevelFormat = "color" } if ce.TimeFormat == "" { ce.TimeFormat = "wall_milli" } ce.Encoder = zapcore.NewConsoleEncoder(ce.ZapcoreEncoderConfig()) return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // console { // <common encoder config subdirectives...> // } // // See the godoc on the LogEncoderConfig type for the syntax of // subdirectives that are common to most/all encoders. func (ce *ConsoleEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume encoder name if d.NextArg() { return d.ArgErr() } err := ce.LogEncoderConfig.UnmarshalCaddyfile(d) if err != nil { return err } return nil } // JSONEncoder encodes entries as JSON. type JSONEncoder struct { zapcore.Encoder `json:"-"` LogEncoderConfig } // CaddyModule returns the Caddy module information. func (JSONEncoder) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.logging.encoders.json", New: func() caddy.Module { return new(JSONEncoder) }, } } // Provision sets up the encoder. func (je *JSONEncoder) Provision(_ caddy.Context) error { je.Encoder = zapcore.NewJSONEncoder(je.ZapcoreEncoderConfig()) return nil } // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax: // // json { // <common encoder config subdirectives...> // } // // See the godoc on the LogEncoderConfig type for the syntax of // subdirectives that are common to most/all encoders. func (je *JSONEncoder) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume encoder name if d.NextArg() { return d.ArgErr() } err := je.LogEncoderConfig.UnmarshalCaddyfile(d) if err != nil { return err } return nil } // LogEncoderConfig holds configuration common to most encoders. type LogEncoderConfig struct { MessageKey *string `json:"message_key,omitempty"` LevelKey *string `json:"level_key,omitempty"` TimeKey *string `json:"time_key,omitempty"` NameKey *string `json:"name_key,omitempty"` CallerKey *string `json:"caller_key,omitempty"` StacktraceKey *string `json:"stacktrace_key,omitempty"` LineEnding *string `json:"line_ending,omitempty"` // Recognized values are: unix_seconds_float, unix_milli_float, unix_nano, iso8601, rfc3339, rfc3339_nano, wall, wall_milli, wall_nano, common_log. // The value may also be custom format per the Go `time` package layout specification, as described [here](https://pkg.go.dev/time#pkg-constants). TimeFormat string `json:"time_format,omitempty"` TimeLocal bool `json:"time_local,omitempty"` // Recognized values are: s/second/seconds, ns/nano/nanos, ms/milli/millis, string. // Empty and unrecognized value default to seconds. DurationFormat string `json:"duration_format,omitempty"` // Recognized values are: lower, upper, color. // Empty and unrecognized value default to lower. LevelFormat string `json:"level_format,omitempty"` } // UnmarshalCaddyfile populates the struct from Caddyfile tokens. Syntax: // // { // message_key <key> // level_key <key> // time_key <key> // name_key <key> // caller_key <key> // stacktrace_key <key> // line_ending <char> // time_format <format> // time_local // duration_format <format> // level_format <format> // } func (lec *LogEncoderConfig) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { for d.NextBlock(0) { subdir := d.Val() switch subdir { case "time_local": lec.TimeLocal = true if d.NextArg() { return d.ArgErr() } continue } var arg string if !d.AllArgs(&arg) { return d.ArgErr() } switch subdir { case "message_key": lec.MessageKey = &arg case "level_key": lec.LevelKey = &arg case "time_key": lec.TimeKey = &arg case "name_key": lec.NameKey = &arg case "caller_key": lec.CallerKey = &arg case "stacktrace_key": lec.StacktraceKey = &arg case "line_ending": lec.LineEnding = &arg case "time_format": lec.TimeFormat = arg case "duration_format": lec.DurationFormat = arg case "level_format": lec.LevelFormat = arg default: return d.Errf("unrecognized subdirective %s", subdir) } } return nil } // ZapcoreEncoderConfig returns the equivalent zapcore.EncoderConfig. // If lec is nil, zap.NewProductionEncoderConfig() is returned. func (lec *LogEncoderConfig) ZapcoreEncoderConfig() zapcore.EncoderConfig { cfg := zap.NewProductionEncoderConfig() if lec == nil { lec = new(LogEncoderConfig) } if lec.MessageKey != nil { cfg.MessageKey = *lec.MessageKey } if lec.LevelKey != nil { cfg.LevelKey = *lec.LevelKey } if lec.TimeKey != nil { cfg.TimeKey = *lec.TimeKey } if lec.NameKey != nil { cfg.NameKey = *lec.NameKey } if lec.CallerKey != nil { cfg.CallerKey = *lec.CallerKey } if lec.StacktraceKey != nil { cfg.StacktraceKey = *lec.StacktraceKey } if lec.LineEnding != nil { cfg.LineEnding = *lec.LineEnding } // time format var timeFormatter zapcore.TimeEncoder switch lec.TimeFormat { case "", "unix_seconds_float": timeFormatter = zapcore.EpochTimeEncoder case "unix_milli_float": timeFormatter = zapcore.EpochMillisTimeEncoder case "unix_nano": timeFormatter = zapcore.EpochNanosTimeEncoder case "iso8601": timeFormatter = zapcore.ISO8601TimeEncoder default: timeFormat := lec.TimeFormat switch lec.TimeFormat { case "rfc3339": timeFormat = time.RFC3339 case "rfc3339_nano": timeFormat = time.RFC3339Nano case "wall": timeFormat = "2006/01/02 15:04:05" case "wall_milli": timeFormat = "2006/01/02 15:04:05.000" case "wall_nano": timeFormat = "2006/01/02 15:04:05.000000000" case "common_log": timeFormat = "02/Jan/2006:15:04:05 -0700" } timeFormatter = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) { var time time.Time if lec.TimeLocal { time = ts.Local() } else { time = ts.UTC() } encoder.AppendString(time.Format(timeFormat)) } } cfg.EncodeTime = timeFormatter // duration format var durFormatter zapcore.DurationEncoder switch lec.DurationFormat { case "s", "second", "seconds": durFormatter = zapcore.SecondsDurationEncoder case "ns", "nano", "nanos": durFormatter = zapcore.NanosDurationEncoder case "ms", "milli", "millis": durFormatter = zapcore.MillisDurationEncoder case "string": durFormatter = zapcore.StringDurationEncoder default: durFormatter = zapcore.SecondsDurationEncoder } cfg.EncodeDuration = durFormatter // level format var levelFormatter zapcore.LevelEncoder switch lec.LevelFormat { case "", "lower": levelFormatter = zapcore.LowercaseLevelEncoder case "upper": levelFormatter = zapcore.CapitalLevelEncoder case "color": levelFormatter = zapcore.CapitalColorLevelEncoder } cfg.EncodeLevel = levelFormatter return cfg } var bufferpool = buffer.NewPool() // Interface guards var ( _ zapcore.Encoder = (*ConsoleEncoder)(nil) _ zapcore.Encoder = (*JSONEncoder)(nil) _ caddyfile.Unmarshaler = (*ConsoleEncoder)(nil) _ caddyfile.Unmarshaler = (*JSONEncoder)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/metrics/adminmetrics.go
modules/metrics/adminmetrics.go
// Copyright 2020 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metrics import ( "errors" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(AdminMetrics{}) } // AdminMetrics is a module that serves a metrics endpoint so that any gathered // metrics can be exposed for scraping. This module is not configurable, and // is permanently mounted to the admin API endpoint at "/metrics". // See the Metrics module for a configurable endpoint that is usable if the // Admin API is disabled. type AdminMetrics struct { registry *prometheus.Registry metricsHandler http.Handler } // CaddyModule returns the Caddy module information. func (AdminMetrics) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "admin.api.metrics", New: func() caddy.Module { return new(AdminMetrics) }, } } // Provision - func (m *AdminMetrics) Provision(ctx caddy.Context) error { m.registry = ctx.GetMetricsRegistry() if m.registry == nil { return errors.New("no metrics registry found") } m.metricsHandler = createMetricsHandler(nil, false, m.registry) return nil } // Routes returns a route for the /metrics endpoint. func (m *AdminMetrics) Routes() []caddy.AdminRoute { return []caddy.AdminRoute{{Pattern: "/metrics", Handler: caddy.AdminHandlerFunc(m.serveHTTP)}} } func (m *AdminMetrics) serveHTTP(w http.ResponseWriter, r *http.Request) error { m.metricsHandler.ServeHTTP(w, r) return nil } // Interface guards var ( _ caddy.Provisioner = (*AdminMetrics)(nil) _ caddy.AdminRouter = (*AdminMetrics)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/metrics/metrics.go
modules/metrics/metrics.go
// Copyright 2020 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metrics import ( "errors" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyhttp" ) func init() { caddy.RegisterModule(Metrics{}) httpcaddyfile.RegisterHandlerDirective("metrics", parseCaddyfile) } // Metrics is a module that serves a /metrics endpoint so that any gathered // metrics can be exposed for scraping. This module is configurable by end-users // unlike AdminMetrics. type Metrics struct { metricsHandler http.Handler // Disable OpenMetrics negotiation, enabled by default. May be necessary if // the produced metrics cannot be parsed by the service scraping metrics. DisableOpenMetrics bool `json:"disable_openmetrics,omitempty"` } // CaddyModule returns the Caddy module information. func (Metrics) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "http.handlers.metrics", New: func() caddy.Module { return new(Metrics) }, } } type zapLogger struct { zl *zap.Logger } func (l *zapLogger) Println(v ...any) { l.zl.Sugar().Error(v...) } // Provision sets up m. func (m *Metrics) Provision(ctx caddy.Context) error { log := ctx.Logger() registry := ctx.GetMetricsRegistry() if registry == nil { return errors.New("no metrics registry found") } m.metricsHandler = createMetricsHandler(&zapLogger{log}, !m.DisableOpenMetrics, registry) return nil } func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) { var m Metrics err := m.UnmarshalCaddyfile(h.Dispenser) return m, err } // UnmarshalCaddyfile sets up the handler from Caddyfile tokens. Syntax: // // metrics [<matcher>] { // disable_openmetrics // } func (m *Metrics) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() // consume directive name args := d.RemainingArgs() if len(args) > 0 { return d.ArgErr() } for d.NextBlock(0) { switch d.Val() { case "disable_openmetrics": m.DisableOpenMetrics = true default: return d.Errf("unrecognized subdirective %q", d.Val()) } } return nil } func (m Metrics) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { m.metricsHandler.ServeHTTP(w, r) return nil } // Interface guards var ( _ caddy.Provisioner = (*Metrics)(nil) _ caddyhttp.MiddlewareHandler = (*Metrics)(nil) _ caddyfile.Unmarshaler = (*Metrics)(nil) ) func createMetricsHandler(logger promhttp.Logger, enableOpenMetrics bool, registry *prometheus.Registry) http.Handler { return promhttp.InstrumentMetricHandler(registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{ // will only log errors if logger is non-nil ErrorLog: logger, // Allow OpenMetrics format to be negotiated - largely compatible, // except quantile/le label values always have a decimal. EnableOpenMetrics: enableOpenMetrics, }), ) }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/metrics/metrics_test.go
modules/metrics/metrics_test.go
package metrics import ( "testing" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestMetricsUnmarshalCaddyfile(t *testing.T) { m := &Metrics{} d := caddyfile.NewTestDispenser(`metrics bogus`) err := m.UnmarshalCaddyfile(d) if err == nil { t.Errorf("expected error") } m = &Metrics{} d = caddyfile.NewTestDispenser(`metrics`) err = m.UnmarshalCaddyfile(d) if err != nil { t.Errorf("unexpected error: %v", err) } if m.DisableOpenMetrics { t.Errorf("DisableOpenMetrics should've been false: %v", m.DisableOpenMetrics) } m = &Metrics{} d = caddyfile.NewTestDispenser(`metrics { disable_openmetrics }`) err = m.UnmarshalCaddyfile(d) if err != nil { t.Errorf("unexpected error: %v", err) } if !m.DisableOpenMetrics { t.Errorf("DisableOpenMetrics should've been true: %v", m.DisableOpenMetrics) } m = &Metrics{} d = caddyfile.NewTestDispenser(`metrics { bogus }`) err = m.UnmarshalCaddyfile(d) if err == nil { t.Errorf("expected error: %v", err) } }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/internal/network/networkproxy.go
modules/internal/network/networkproxy.go
package network import ( "errors" "net/http" "net/url" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func init() { caddy.RegisterModule(ProxyFromURL{}) caddy.RegisterModule(ProxyFromNone{}) } // The "url" proxy source uses the defined URL as the proxy type ProxyFromURL struct { URL string `json:"url"` ctx caddy.Context logger *zap.Logger } // CaddyModule implements Module. func (p ProxyFromURL) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.network_proxy.url", New: func() caddy.Module { return &ProxyFromURL{} }, } } func (p *ProxyFromURL) Provision(ctx caddy.Context) error { p.ctx = ctx p.logger = ctx.Logger() return nil } // Validate implements Validator. func (p ProxyFromURL) Validate() error { if _, err := url.Parse(p.URL); err != nil { return err } return nil } // ProxyFunc implements ProxyFuncProducer. func (p ProxyFromURL) ProxyFunc() func(*http.Request) (*url.URL, error) { if strings.Contains(p.URL, "{") && strings.Contains(p.URL, "}") { // courtesy of @ImpostorKeanu: https://github.com/caddyserver/caddy/pull/6397 return func(r *http.Request) (*url.URL, error) { // retrieve the replacer from context. repl, ok := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { err := errors.New("failed to obtain replacer from request") p.logger.Error(err.Error()) return nil, err } // apply placeholders to the value // note: h.ForwardProxyURL should never be empty at this point s := repl.ReplaceAll(p.URL, "") if s == "" { p.logger.Error("network_proxy URL was empty after applying placeholders", zap.String("initial_value", p.URL), zap.String("final_value", s), zap.String("hint", "check for invalid placeholders")) return nil, errors.New("empty value for network_proxy URL") } // parse the url pUrl, err := url.Parse(s) if err != nil { p.logger.Warn("failed to derive transport proxy from network_proxy URL") pUrl = nil } else if pUrl.Host == "" || strings.Split("", pUrl.Host)[0] == ":" { // url.Parse does not return an error on these values: // // - http://:80 // - pUrl.Host == ":80" // - /some/path // - pUrl.Host == "" // // Super edge cases, but humans are human. err = errors.New("supplied network_proxy URL is missing a host value") pUrl = nil } else { p.logger.Debug("setting transport proxy url", zap.String("url", s)) } return pUrl, err } } return func(r *http.Request) (*url.URL, error) { return url.Parse(p.URL) } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (p *ProxyFromURL) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { d.Next() d.Next() p.URL = d.Val() return nil } // The "none" proxy source module disables the use of network proxy. type ProxyFromNone struct{} func (p ProxyFromNone) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "caddy.network_proxy.none", New: func() caddy.Module { return &ProxyFromNone{} }, } } // UnmarshalCaddyfile implements caddyfile.Unmarshaler. func (p ProxyFromNone) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } // ProxyFunc implements ProxyFuncProducer. func (p ProxyFromNone) ProxyFunc() func(*http.Request) (*url.URL, error) { return nil } var ( _ caddy.Module = ProxyFromURL{} _ caddy.Provisioner = (*ProxyFromURL)(nil) _ caddy.Validator = ProxyFromURL{} _ caddy.ProxyFuncProducer = ProxyFromURL{} _ caddyfile.Unmarshaler = (*ProxyFromURL)(nil) _ caddy.Module = ProxyFromNone{} _ caddy.ProxyFuncProducer = ProxyFromNone{} _ caddyfile.Unmarshaler = ProxyFromNone{} )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyevents/app.go
modules/caddyevents/app.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package caddyevents import ( "context" "encoding/json" "errors" "fmt" "strings" "go.uber.org/zap" "github.com/caddyserver/caddy/v2" ) func init() { caddy.RegisterModule(App{}) } // App implements a global eventing system within Caddy. // Modules can emit and subscribe to events, providing // hooks into deep parts of the code base that aren't // otherwise accessible. Events provide information about // what and when things are happening, and this facility // allows handlers to take action when events occur, // add information to the event's metadata, and even // control program flow in some cases. // // Events are propagated in a DOM-like fashion. An event // emitted from module `a.b.c` (the "origin") will first // invoke handlers listening to `a.b.c`, then `a.b`, // then `a`, then those listening regardless of origin. // If a handler returns the special error Aborted, then // propagation immediately stops and the event is marked // as aborted. Emitters may optionally choose to adjust // program flow based on an abort. // // Modules can subscribe to events by origin and/or name. // A handler is invoked only if it is subscribed to the // event by name and origin. Subscriptions should be // registered during the provisioning phase, before apps // are started. // // Event handlers are fired synchronously as part of the // regular flow of the program. This allows event handlers // to control the flow of the program if the origin permits // it and also allows handlers to convey new information // back into the origin module before it continues. // In essence, event handlers are similar to HTTP // middleware handlers. // // Event bindings/subscribers are unordered; i.e. // event handlers are invoked in an arbitrary order. // Event handlers should not rely on the logic of other // handlers to succeed. // // The entirety of this app module is EXPERIMENTAL and // subject to change. Pay attention to release notes. type App struct { // Subscriptions bind handlers to one or more events // either globally or scoped to specific modules or module // namespaces. Subscriptions []*Subscription `json:"subscriptions,omitempty"` // Map of event name to map of module ID/namespace to handlers subscriptions map[string]map[caddy.ModuleID][]Handler logger *zap.Logger started bool } // Subscription represents binding of one or more handlers to // one or more events. type Subscription struct { // The name(s) of the event(s) to bind to. Default: all events. Events []string `json:"events,omitempty"` // The ID or namespace of the module(s) from which events // originate to listen to for events. Default: all modules. // // Events propagate up, so events emitted by module "a.b.c" // will also trigger the event for "a.b" and "a". Thus, to // receive all events from "a.b.c" and "a.b.d", for example, // one can subscribe to either "a.b" or all of "a" entirely. Modules []caddy.ModuleID `json:"modules,omitempty"` // The event handler modules. These implement the actual // behavior to invoke when an event occurs. At least one // handler is required. HandlersRaw []json.RawMessage `json:"handlers,omitempty" caddy:"namespace=events.handlers inline_key=handler"` // The decoded handlers; Go code that is subscribing to // an event should set this field directly; HandlersRaw // is meant for JSON configuration to fill out this field. Handlers []Handler `json:"-"` } // CaddyModule returns the Caddy module information. func (App) CaddyModule() caddy.ModuleInfo { return caddy.ModuleInfo{ ID: "events", New: func() caddy.Module { return new(App) }, } } // Provision sets up the app. func (app *App) Provision(ctx caddy.Context) error { app.logger = ctx.Logger() app.subscriptions = make(map[string]map[caddy.ModuleID][]Handler) for _, sub := range app.Subscriptions { if sub.HandlersRaw == nil { continue } handlersIface, err := ctx.LoadModule(sub, "HandlersRaw") if err != nil { return fmt.Errorf("loading event subscriber modules: %v", err) } for _, h := range handlersIface.([]any) { sub.Handlers = append(sub.Handlers, h.(Handler)) } if len(sub.Handlers) == 0 { // pointless to bind without any handlers return fmt.Errorf("no handlers defined") } } return nil } // Start runs the app. func (app *App) Start() error { for _, sub := range app.Subscriptions { if err := app.Subscribe(sub); err != nil { return err } } app.started = true return nil } // Stop gracefully shuts down the app. func (app *App) Stop() error { return nil } // Subscribe binds one or more event handlers to one or more events // according to the subscription s. For now, subscriptions can only // be created during the provision phase; new bindings cannot be // created after the events app has started. func (app *App) Subscribe(s *Subscription) error { if app.started { return fmt.Errorf("events already started; new subscriptions closed") } // handle special case of catch-alls (omission of event name or module space implies all) if len(s.Events) == 0 { s.Events = []string{""} } if len(s.Modules) == 0 { s.Modules = []caddy.ModuleID{""} } for _, eventName := range s.Events { if app.subscriptions[eventName] == nil { app.subscriptions[eventName] = make(map[caddy.ModuleID][]Handler) } for _, originModule := range s.Modules { app.subscriptions[eventName][originModule] = append(app.subscriptions[eventName][originModule], s.Handlers...) } } return nil } // On is syntactic sugar for Subscribe() that binds a single handler // to a single event from any module. If the eventName is empty string, // it counts for all events. func (app *App) On(eventName string, handler Handler) error { return app.Subscribe(&Subscription{ Events: []string{eventName}, Handlers: []Handler{handler}, }) } // Emit creates and dispatches an event named eventName to all relevant handlers with // the metadata data. Events are emitted and propagated synchronously. The returned Event // value will have any additional information from the invoked handlers. // // Note that the data map is not copied, for efficiency. After Emit() is called, the // data passed in should not be changed in other goroutines. func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) caddy.Event { logger := app.logger.With(zap.String("name", eventName)) e, err := caddy.NewEvent(ctx, eventName, data) if err != nil { logger.Error("failed to create event", zap.Error(err)) } var originModule caddy.ModuleInfo var originModuleID caddy.ModuleID var originModuleName string if origin := e.Origin(); origin != nil { originModule = origin.CaddyModule() originModuleID = originModule.ID originModuleName = originModule.String() } logger = logger.With( zap.String("id", e.ID().String()), zap.String("origin", originModuleName)) // add event info to replacer, make sure it's in the context repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) if !ok { repl = caddy.NewReplacer() ctx.Context = context.WithValue(ctx.Context, caddy.ReplacerCtxKey, repl) } repl.Map(func(key string) (any, bool) { switch key { case "event": return e, true case "event.id": return e.ID(), true case "event.name": return e.Name(), true case "event.time": return e.Timestamp(), true case "event.time_unix": return e.Timestamp().UnixMilli(), true case "event.module": return originModuleID, true case "event.data": return e.Data, true } if after, ok0 := strings.CutPrefix(key, "event.data."); ok0 { key = after if val, ok := e.Data[key]; ok { return val, true } } return nil, false }) logger = logger.WithLazy(zap.Any("data", e.Data)) logger.Debug("event") // invoke handlers bound to the event by name and also all events; this for loop // iterates twice at most: once for the event name, once for "" (all events) for { moduleID := originModuleID // implement propagation up the module tree (i.e. start with "a.b.c" then "a.b" then "a" then "") for { if app.subscriptions[eventName] == nil { break // shortcut if event not bound at all } for _, handler := range app.subscriptions[eventName][moduleID] { select { case <-ctx.Done(): logger.Error("context canceled; event handling stopped") return e default: } // this log can be a useful sanity check to ensure your handlers are in fact being invoked // (see https://github.com/mholt/caddy-events-exec/issues/6) logger.Debug("invoking subscribed handler", zap.String("subscribed_to", eventName), zap.Any("handler", handler)) if err := handler.Handle(ctx, e); err != nil { aborted := errors.Is(err, caddy.ErrEventAborted) logger.Error("handler error", zap.Error(err), zap.Bool("aborted", aborted)) if aborted { e.Aborted = err return e } } } if moduleID == "" { break } lastDot := strings.LastIndex(string(moduleID), ".") if lastDot < 0 { moduleID = "" // include handlers bound to events regardless of module } else { moduleID = moduleID[:lastDot] } } // include handlers listening to all events if eventName == "" { break } eventName = "" } return e } // Handler is a type that can handle events. type Handler interface { Handle(context.Context, caddy.Event) error } // Interface guards var ( _ caddy.App = (*App)(nil) _ caddy.Provisioner = (*App)(nil) )
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/modules/caddyevents/eventsconfig/caddyfile.go
modules/caddyevents/eventsconfig/caddyfile.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package eventsconfig is for configuring caddyevents.App with the // Caddyfile. This code can't be in the caddyevents package because // the httpcaddyfile package imports caddyhttp, which imports // caddyevents: hence, it creates an import cycle. package eventsconfig import ( "encoding/json" "github.com/caddyserver/caddy/v2/caddyconfig" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" "github.com/caddyserver/caddy/v2/modules/caddyevents" ) func init() { httpcaddyfile.RegisterGlobalOption("events", parseApp) } // parseApp configures the "events" global option from Caddyfile to set up the events app. // Syntax: // // events { // on <event> <handler_module...> // } // // If <event> is *, then it will bind to all events. func parseApp(d *caddyfile.Dispenser, _ any) (any, error) { d.Next() // consume option name app := new(caddyevents.App) for d.NextBlock(0) { switch d.Val() { case "on": if !d.NextArg() { return nil, d.ArgErr() } eventName := d.Val() if eventName == "*" { eventName = "" } if !d.NextArg() { return nil, d.ArgErr() } handlerName := d.Val() modID := "events.handlers." + handlerName unm, err := caddyfile.UnmarshalModule(d, modID) if err != nil { return nil, err } app.Subscriptions = append(app.Subscriptions, &caddyevents.Subscription{ Events: []string{eventName}, HandlersRaw: []json.RawMessage{ caddyconfig.JSONModuleObject(unm, "handler", handlerName, nil), }, }) default: return nil, d.ArgErr() } } return httpcaddyfile.App{ Name: "events", Value: caddyconfig.JSON(app, nil), }, nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/notify/notify_windows.go
notify/notify_windows.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package notify import ( "log" "strings" "golang.org/x/sys/windows/svc" ) // globalStatus store windows service status, it can be // use to notify caddy status. var globalStatus chan<- svc.Status // SetGlobalStatus assigns the channel through which status updates // will be sent to the SCM. This is typically provided by the service // handler when the service starts. func SetGlobalStatus(status chan<- svc.Status) { globalStatus = status } // Ready notifies the SCM that the service is fully running and ready // to accept stop or shutdown control requests. func Ready() error { if globalStatus != nil { globalStatus <- svc.Status{ State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown, } } return nil } // Reloading notifies the SCM that the service is entering a transitional // state. func Reloading() error { if globalStatus != nil { globalStatus <- svc.Status{State: svc.StartPending} } return nil } // Stopping notifies the SCM that the service is in the process of stopping. // This allows Windows to track the shutdown transition properly. func Stopping() error { if globalStatus != nil { globalStatus <- svc.Status{State: svc.StopPending} } return nil } // Status sends an arbitrary service state to the SCM based on a string // identifier of [svc.State]. // The unknown states will be logged. func Status(name string) error { if globalStatus == nil { return nil } var state svc.State var accepts svc.Accepted accepts = 0 switch strings.ToLower(name) { case "stopped": state = svc.Stopped case "start_pending": state = svc.StartPending case "stop_pending": state = svc.StopPending case "running": state = svc.Running accepts = svc.AcceptStop | svc.AcceptShutdown case "continue_pending": state = svc.ContinuePending case "pause_pending": state = svc.PausePending case "paused": state = svc.Paused accepts = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue default: log.Printf("unknown state: %s", name) return nil } globalStatus <- svc.Status{State: state, Accepts: accepts} return nil } // Error notifies the SCM that the service is stopping due to a failure, // including a service-specific exit code. func Error(err error, code int) error { if globalStatus != nil { globalStatus <- svc.Status{ State: svc.StopPending, ServiceSpecificExitCode: uint32(code), } } return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/notify/notify_linux.go
notify/notify_linux.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package notify provides facilities for notifying process managers // of state changes, mainly for when running as a system service. package notify import ( "fmt" "net" "os" "strings" ) // The documentation about this IPC protocol is available here: // https://www.freedesktop.org/software/systemd/man/sd_notify.html func sdNotify(payload string) error { if socketPath == "" { return nil } socketAddr := &net.UnixAddr{ Name: socketPath, Net: "unixgram", } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) if err != nil { return err } defer conn.Close() _, err = conn.Write([]byte(payload)) return err } // Ready notifies systemd that caddy has finished its // initialization routines. func Ready() error { return sdNotify("READY=1") } // Reloading notifies systemd that caddy is reloading its config. func Reloading() error { return sdNotify("RELOADING=1") } // Stopping notifies systemd that caddy is stopping. func Stopping() error { return sdNotify("STOPPING=1") } // Status sends systemd an updated status message. func Status(msg string) error { return sdNotify("STATUS=" + msg) } // Error is like Status, but sends systemd an error message // instead, with an optional errno-style error number. func Error(err error, errno int) error { collapsedErr := strings.ReplaceAll(err.Error(), "\n", " ") msg := fmt.Sprintf("STATUS=%s", collapsedErr) if errno > 0 { msg += fmt.Sprintf("\nERRNO=%d", errno) } return sdNotify(msg) } var socketPath, _ = os.LookupEnv("NOTIFY_SOCKET")
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
caddyserver/caddy
https://github.com/caddyserver/caddy/blob/28103aafba3490eedb626823f9641b766c7c99fd/notify/notify_other.go
notify/notify_other.go
// Copyright 2015 Matthew Holt and The Caddy Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !linux && !windows package notify func Ready() error { return nil } func Reloading() error { return nil } func Stopping() error { return nil } func Status(_ string) error { return nil } func Error(_ error, _ int) error { return nil }
go
Apache-2.0
28103aafba3490eedb626823f9641b766c7c99fd
2026-01-07T08:35:43.461103Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/vhost/vhost.go
pkg/util/vhost/vhost.go
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vhost import ( "context" "fmt" "net" "strings" "time" "github.com/fatedier/golib/errors" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" ) type RouteInfo string const ( RouteInfoKey RouteInfo = "routeInfo" RouteConfigKey RouteInfo = "routeConfig" ) type RequestRouteInfo struct { URL string Host string HTTPUser string RemoteAddr string URLHost string Endpoint string } type ( muxFunc func(net.Conn) (net.Conn, map[string]string, error) authFunc func(conn net.Conn, username, password string, reqInfoMap map[string]string) (bool, error) hostRewriteFunc func(net.Conn, string) (net.Conn, error) successHookFunc func(net.Conn, map[string]string) error failHookFunc func(net.Conn) ) // Muxer is a functional component used for https and tcpmux proxies. // It accepts connections and extracts vhost information from the beginning of the connection data. // It then routes the connection to its appropriate listener. type Muxer struct { listener net.Listener timeout time.Duration vhostFunc muxFunc checkAuth authFunc successHook successHookFunc failHook failHookFunc rewriteHost hostRewriteFunc registryRouter *Routers } func NewMuxer( listener net.Listener, vhostFunc muxFunc, timeout time.Duration, ) (mux *Muxer, err error) { mux = &Muxer{ listener: listener, timeout: timeout, vhostFunc: vhostFunc, registryRouter: NewRouters(), } go mux.run() return mux, nil } func (v *Muxer) SetCheckAuthFunc(f authFunc) *Muxer { v.checkAuth = f return v } func (v *Muxer) SetSuccessHookFunc(f successHookFunc) *Muxer { v.successHook = f return v } func (v *Muxer) SetFailHookFunc(f failHookFunc) *Muxer { v.failHook = f return v } func (v *Muxer) SetRewriteHostFunc(f hostRewriteFunc) *Muxer { v.rewriteHost = f return v } func (v *Muxer) Close() error { return v.listener.Close() } type ChooseEndpointFunc func() (string, error) type CreateConnFunc func(remoteAddr string) (net.Conn, error) type CreateConnByEndpointFunc func(endpoint, remoteAddr string) (net.Conn, error) // RouteConfig is the params used to match HTTP requests type RouteConfig struct { Domain string Location string RewriteHost string Username string Password string Headers map[string]string ResponseHeaders map[string]string RouteByHTTPUser string CreateConnFn CreateConnFunc ChooseEndpointFn ChooseEndpointFunc CreateConnByEndpointFn CreateConnByEndpointFunc } // listen for a new domain name, if rewriteHost is not empty and rewriteHost func is not nil, // then rewrite the host header to rewriteHost func (v *Muxer) Listen(ctx context.Context, cfg *RouteConfig) (l *Listener, err error) { l = &Listener{ name: cfg.Domain, location: cfg.Location, routeByHTTPUser: cfg.RouteByHTTPUser, rewriteHost: cfg.RewriteHost, username: cfg.Username, password: cfg.Password, mux: v, accept: make(chan net.Conn), ctx: ctx, } err = v.registryRouter.Add(cfg.Domain, cfg.Location, cfg.RouteByHTTPUser, l) if err != nil { return } return l, nil } func (v *Muxer) getListener(name, path, httpUser string) (*Listener, bool) { findRouter := func(inName, inPath, inHTTPUser string) (*Listener, bool) { vr, ok := v.registryRouter.Get(inName, inPath, inHTTPUser) if ok { return vr.payload.(*Listener), true } // Try to check if there is one proxy that doesn't specify routerByHTTPUser, it means match all. vr, ok = v.registryRouter.Get(inName, inPath, "") if ok { return vr.payload.(*Listener), true } return nil, false } // first we check the full hostname // if not exist, then check the wildcard_domain such as *.example.com l, ok := findRouter(name, path, httpUser) if ok { return l, true } domainSplit := strings.Split(name, ".") for len(domainSplit) >= 3 { domainSplit[0] = "*" name = strings.Join(domainSplit, ".") l, ok = findRouter(name, path, httpUser) if ok { return l, true } domainSplit = domainSplit[1:] } // Finally, try to check if there is one proxy that domain is "*" means match all domains. l, ok = findRouter("*", path, httpUser) if ok { return l, true } return nil, false } func (v *Muxer) run() { for { conn, err := v.listener.Accept() if err != nil { return } go v.handle(conn) } } func (v *Muxer) handle(c net.Conn) { if err := c.SetDeadline(time.Now().Add(v.timeout)); err != nil { _ = c.Close() return } sConn, reqInfoMap, err := v.vhostFunc(c) if err != nil { log.Debugf("get hostname from http/https request error: %v", err) _ = c.Close() return } name := strings.ToLower(reqInfoMap["Host"]) path := strings.ToLower(reqInfoMap["Path"]) httpUser := reqInfoMap["HTTPUser"] l, ok := v.getListener(name, path, httpUser) if !ok { log.Debugf("http request for host [%s] path [%s] httpUser [%s] not found", name, path, httpUser) v.failHook(sConn) return } xl := xlog.FromContextSafe(l.ctx) if v.successHook != nil { if err := v.successHook(c, reqInfoMap); err != nil { xl.Infof("success func failure on vhost connection: %v", err) _ = c.Close() return } } // if checkAuth func is exist and username/password is set // then verify user access if l.mux.checkAuth != nil && l.username != "" { ok, err := l.mux.checkAuth(c, l.username, l.password, reqInfoMap) if !ok || err != nil { xl.Debugf("auth failed for user: %s", l.username) _ = c.Close() return } } if err = sConn.SetDeadline(time.Time{}); err != nil { _ = c.Close() return } c = sConn xl.Debugf("new request host [%s] path [%s] httpUser [%s]", name, path, httpUser) err = errors.PanicToError(func() { l.accept <- c }) if err != nil { xl.Warnf("listener is already closed, ignore this request") } } type Listener struct { name string location string routeByHTTPUser string rewriteHost string username string password string mux *Muxer // for closing Muxer accept chan net.Conn ctx context.Context } func (l *Listener) Accept() (net.Conn, error) { xl := xlog.FromContextSafe(l.ctx) conn, ok := <-l.accept if !ok { return nil, fmt.Errorf("listener closed") } // if rewriteHost func is exist // rewrite http requests with a modified host header // if l.rewriteHost is empty, nothing to do if l.mux.rewriteHost != nil { sConn, err := l.mux.rewriteHost(conn, l.rewriteHost) if err != nil { xl.Warnf("host header rewrite failed: %v", err) return nil, fmt.Errorf("host header rewrite failed") } xl.Debugf("rewrite host to [%s] success", l.rewriteHost) conn = sConn } return netpkg.NewContextConn(l.ctx, conn), nil } func (l *Listener) Close() error { l.mux.registryRouter.Del(l.name, l.location, l.routeByHTTPUser) close(l.accept) return nil } func (l *Listener) Name() string { return l.name } func (l *Listener) Addr() net.Addr { return (*net.TCPAddr)(nil) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/vhost/https.go
pkg/util/vhost/https.go
// Copyright 2016 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vhost import ( "crypto/tls" "io" "net" "time" libnet "github.com/fatedier/golib/net" ) type HTTPSMuxer struct { *Muxer } func NewHTTPSMuxer(listener net.Listener, timeout time.Duration) (*HTTPSMuxer, error) { mux, err := NewMuxer(listener, GetHTTPSHostname, timeout) mux.SetFailHookFunc(vhostFailed) if err != nil { return nil, err } return &HTTPSMuxer{mux}, err } func GetHTTPSHostname(c net.Conn) (_ net.Conn, _ map[string]string, err error) { reqInfoMap := make(map[string]string, 0) sc, rd := libnet.NewSharedConn(c) clientHello, err := readClientHello(rd) if err != nil { return nil, reqInfoMap, err } reqInfoMap["Host"] = clientHello.ServerName reqInfoMap["Scheme"] = "https" return sc, reqInfoMap, nil } func readClientHello(reader io.Reader) (*tls.ClientHelloInfo, error) { var hello *tls.ClientHelloInfo // Note that Handshake always fails because the readOnlyConn is not a real connection. // As long as the Client Hello is successfully read, the failure should only happen after GetConfigForClient is called, // so we only care about the error if hello was never set. err := tls.Server(readOnlyConn{reader: reader}, &tls.Config{ GetConfigForClient: func(argHello *tls.ClientHelloInfo) (*tls.Config, error) { hello = &tls.ClientHelloInfo{} *hello = *argHello return nil, nil }, }).Handshake() if hello == nil { return nil, err } return hello, nil } func vhostFailed(c net.Conn) { // Alert with alertUnrecognizedName _ = tls.Server(c, &tls.Config{}).Handshake() c.Close() } type readOnlyConn struct { reader io.Reader } func (conn readOnlyConn) Read(p []byte) (int, error) { return conn.reader.Read(p) } func (conn readOnlyConn) Write(_ []byte) (int, error) { return 0, io.ErrClosedPipe } func (conn readOnlyConn) Close() error { return nil } func (conn readOnlyConn) LocalAddr() net.Addr { return nil } func (conn readOnlyConn) RemoteAddr() net.Addr { return nil } func (conn readOnlyConn) SetDeadline(_ time.Time) error { return nil } func (conn readOnlyConn) SetReadDeadline(_ time.Time) error { return nil } func (conn readOnlyConn) SetWriteDeadline(_ time.Time) error { return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/vhost/router.go
pkg/util/vhost/router.go
package vhost import ( "cmp" "errors" "slices" "strings" "sync" ) var ErrRouterConfigConflict = errors.New("router config conflict") type routerByHTTPUser map[string][]*Router type Routers struct { indexByDomain map[string]routerByHTTPUser mutex sync.RWMutex } type Router struct { domain string location string httpUser string // store any object here payload any } func NewRouters() *Routers { return &Routers{ indexByDomain: make(map[string]routerByHTTPUser), } } func (r *Routers) Add(domain, location, httpUser string, payload any) error { domain = strings.ToLower(domain) r.mutex.Lock() defer r.mutex.Unlock() if _, exist := r.exist(domain, location, httpUser); exist { return ErrRouterConfigConflict } routersByHTTPUser, found := r.indexByDomain[domain] if !found { routersByHTTPUser = make(map[string][]*Router) } vrs, found := routersByHTTPUser[httpUser] if !found { vrs = make([]*Router, 0, 1) } vr := &Router{ domain: domain, location: location, httpUser: httpUser, payload: payload, } vrs = append(vrs, vr) slices.SortFunc(vrs, func(a, b *Router) int { return -cmp.Compare(a.location, b.location) }) routersByHTTPUser[httpUser] = vrs r.indexByDomain[domain] = routersByHTTPUser return nil } func (r *Routers) Del(domain, location, httpUser string) { domain = strings.ToLower(domain) r.mutex.Lock() defer r.mutex.Unlock() routersByHTTPUser, found := r.indexByDomain[domain] if !found { return } vrs, found := routersByHTTPUser[httpUser] if !found { return } newVrs := make([]*Router, 0) for _, vr := range vrs { if vr.location != location { newVrs = append(newVrs, vr) } } routersByHTTPUser[httpUser] = newVrs } func (r *Routers) Get(host, path, httpUser string) (vr *Router, exist bool) { host = strings.ToLower(host) r.mutex.RLock() defer r.mutex.RUnlock() routersByHTTPUser, found := r.indexByDomain[host] if !found { return } vrs, found := routersByHTTPUser[httpUser] if !found { return } for _, vr = range vrs { if strings.HasPrefix(path, vr.location) { return vr, true } } return } func (r *Routers) exist(host, path, httpUser string) (route *Router, exist bool) { routersByHTTPUser, found := r.indexByDomain[host] if !found { return } routers, found := routersByHTTPUser[httpUser] if !found { return } for _, route = range routers { if path == route.location { return route, true } } return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/vhost/http.go
pkg/util/vhost/http.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vhost import ( "context" "encoding/base64" "errors" "fmt" stdlog "log" "net" "net/http" "net/http/httputil" "net/url" "strings" "time" libio "github.com/fatedier/golib/io" "github.com/fatedier/golib/pool" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" ) var ErrNoRouteFound = errors.New("no route found") type HTTPReverseProxyOptions struct { ResponseHeaderTimeoutS int64 } type HTTPReverseProxy struct { proxy http.Handler vhostRouter *Routers responseHeaderTimeout time.Duration } func NewHTTPReverseProxy(option HTTPReverseProxyOptions, vhostRouter *Routers) *HTTPReverseProxy { if option.ResponseHeaderTimeoutS <= 0 { option.ResponseHeaderTimeoutS = 60 } rp := &HTTPReverseProxy{ responseHeaderTimeout: time.Duration(option.ResponseHeaderTimeoutS) * time.Second, vhostRouter: vhostRouter, } proxy := &httputil.ReverseProxy{ // Modify incoming requests by route policies. Rewrite: func(r *httputil.ProxyRequest) { r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"] r.SetXForwarded() req := r.Out req.URL.Scheme = "http" reqRouteInfo := req.Context().Value(RouteInfoKey).(*RequestRouteInfo) originalHost, _ := httppkg.CanonicalHost(reqRouteInfo.Host) rc := req.Context().Value(RouteConfigKey).(*RouteConfig) if rc != nil { if rc.RewriteHost != "" { req.Host = rc.RewriteHost } var endpoint string if rc.ChooseEndpointFn != nil { // ignore error here, it will use CreateConnFn instead later endpoint, _ = rc.ChooseEndpointFn() reqRouteInfo.Endpoint = endpoint log.Tracef("choose endpoint name [%s] for http request host [%s] path [%s] httpuser [%s]", endpoint, originalHost, reqRouteInfo.URL, reqRouteInfo.HTTPUser) } // Set {domain}.{location}.{routeByHTTPUser}.{endpoint} as URL host here to let http transport reuse connections. req.URL.Host = rc.Domain + "." + base64.StdEncoding.EncodeToString([]byte(rc.Location)) + "." + base64.StdEncoding.EncodeToString([]byte(rc.RouteByHTTPUser)) + "." + base64.StdEncoding.EncodeToString([]byte(endpoint)) for k, v := range rc.Headers { req.Header.Set(k, v) } } else { req.URL.Host = req.Host } }, ModifyResponse: func(r *http.Response) error { rc := r.Request.Context().Value(RouteConfigKey).(*RouteConfig) if rc != nil { for k, v := range rc.ResponseHeaders { r.Header.Set(k, v) } } return nil }, // Create a connection to one proxy routed by route policy. Transport: &http.Transport{ ResponseHeaderTimeout: rp.responseHeaderTimeout, IdleConnTimeout: 60 * time.Second, MaxIdleConnsPerHost: 5, DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { return rp.CreateConnection(ctx.Value(RouteInfoKey).(*RequestRouteInfo), true) }, Proxy: func(req *http.Request) (*url.URL, error) { // Use proxy mode if there is host in HTTP first request line. // GET http://example.com/ HTTP/1.1 // Host: example.com // // Normal: // GET / HTTP/1.1 // Host: example.com urlHost := req.Context().Value(RouteInfoKey).(*RequestRouteInfo).URLHost if urlHost != "" { return req.URL, nil } return nil, nil }, }, BufferPool: pool.NewBuffer(32 * 1024), ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0), ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) { log.Logf(log.WarnLevel, 1, "do http proxy request [host: %s] error: %v", req.Host, err) if err != nil { if e, ok := err.(net.Error); ok && e.Timeout() { rw.WriteHeader(http.StatusGatewayTimeout) return } } rw.WriteHeader(http.StatusNotFound) _, _ = rw.Write(getNotFoundPageContent()) }, } rp.proxy = h2c.NewHandler(proxy, &http2.Server{}) return rp } // Register register the route config to reverse proxy // reverse proxy will use CreateConnFn from routeCfg to create a connection to the remote service func (rp *HTTPReverseProxy) Register(routeCfg RouteConfig) error { err := rp.vhostRouter.Add(routeCfg.Domain, routeCfg.Location, routeCfg.RouteByHTTPUser, &routeCfg) if err != nil { return err } return nil } // UnRegister unregister route config by domain and location func (rp *HTTPReverseProxy) UnRegister(routeCfg RouteConfig) { rp.vhostRouter.Del(routeCfg.Domain, routeCfg.Location, routeCfg.RouteByHTTPUser) } func (rp *HTTPReverseProxy) GetRouteConfig(domain, location, routeByHTTPUser string) *RouteConfig { vr, ok := rp.getVhost(domain, location, routeByHTTPUser) if ok { log.Debugf("get new http request host [%s] path [%s] httpuser [%s]", domain, location, routeByHTTPUser) return vr.payload.(*RouteConfig) } return nil } // CreateConnection create a new connection by route config func (rp *HTTPReverseProxy) CreateConnection(reqRouteInfo *RequestRouteInfo, byEndpoint bool) (net.Conn, error) { host, _ := httppkg.CanonicalHost(reqRouteInfo.Host) vr, ok := rp.getVhost(host, reqRouteInfo.URL, reqRouteInfo.HTTPUser) if ok { if byEndpoint { fn := vr.payload.(*RouteConfig).CreateConnByEndpointFn if fn != nil { return fn(reqRouteInfo.Endpoint, reqRouteInfo.RemoteAddr) } } fn := vr.payload.(*RouteConfig).CreateConnFn if fn != nil { return fn(reqRouteInfo.RemoteAddr) } } return nil, fmt.Errorf("%v: %s %s %s", ErrNoRouteFound, host, reqRouteInfo.URL, reqRouteInfo.HTTPUser) } func (rp *HTTPReverseProxy) CheckAuth(domain, location, routeByHTTPUser, user, passwd string) bool { vr, ok := rp.getVhost(domain, location, routeByHTTPUser) if ok { checkUser := vr.payload.(*RouteConfig).Username checkPasswd := vr.payload.(*RouteConfig).Password if (checkUser != "" || checkPasswd != "") && (checkUser != user || checkPasswd != passwd) { return false } } return true } // getVhost tries to get vhost router by route policy. func (rp *HTTPReverseProxy) getVhost(domain, location, routeByHTTPUser string) (*Router, bool) { findRouter := func(inDomain, inLocation, inRouteByHTTPUser string) (*Router, bool) { vr, ok := rp.vhostRouter.Get(inDomain, inLocation, inRouteByHTTPUser) if ok { return vr, ok } // Try to check if there is one proxy that doesn't specify routerByHTTPUser, it means match all. vr, ok = rp.vhostRouter.Get(inDomain, inLocation, "") if ok { return vr, ok } return nil, false } // First we check the full hostname // if not exist, then check the wildcard_domain such as *.example.com vr, ok := findRouter(domain, location, routeByHTTPUser) if ok { return vr, ok } // e.g. domain = test.example.com, try to match wildcard domains. // *.example.com // *.com domainSplit := strings.Split(domain, ".") for len(domainSplit) >= 3 { domainSplit[0] = "*" domain = strings.Join(domainSplit, ".") vr, ok = findRouter(domain, location, routeByHTTPUser) if ok { return vr, true } domainSplit = domainSplit[1:] } // Finally, try to check if there is one proxy that domain is "*" means match all domains. vr, ok = findRouter("*", location, routeByHTTPUser) if ok { return vr, true } return nil, false } func (rp *HTTPReverseProxy) connectHandler(rw http.ResponseWriter, req *http.Request) { hj, ok := rw.(http.Hijacker) if !ok { rw.WriteHeader(http.StatusInternalServerError) return } client, _, err := hj.Hijack() if err != nil { rw.WriteHeader(http.StatusInternalServerError) return } remote, err := rp.CreateConnection(req.Context().Value(RouteInfoKey).(*RequestRouteInfo), false) if err != nil { _ = NotFoundResponse().Write(client) client.Close() return } _ = req.Write(remote) go libio.Join(remote, client) } func parseBasicAuth(auth string) (username, password string, ok bool) { const prefix = "Basic " // Case insensitive prefix match. See Issue 22736. if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { return } c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) if err != nil { return } cs := string(c) s := strings.IndexByte(cs, ':') if s < 0 { return } return cs[:s], cs[s+1:], true } func (rp *HTTPReverseProxy) injectRequestInfoToCtx(req *http.Request) *http.Request { user := "" // If url host isn't empty, it's a proxy request. Get http user from Proxy-Authorization header. if req.URL.Host != "" { proxyAuth := req.Header.Get("Proxy-Authorization") if proxyAuth != "" { user, _, _ = parseBasicAuth(proxyAuth) } } if user == "" { user, _, _ = req.BasicAuth() } reqRouteInfo := &RequestRouteInfo{ URL: req.URL.Path, Host: req.Host, HTTPUser: user, RemoteAddr: req.RemoteAddr, URLHost: req.URL.Host, } originalHost, _ := httppkg.CanonicalHost(reqRouteInfo.Host) rc := rp.GetRouteConfig(originalHost, reqRouteInfo.URL, reqRouteInfo.HTTPUser) newctx := req.Context() newctx = context.WithValue(newctx, RouteInfoKey, reqRouteInfo) newctx = context.WithValue(newctx, RouteConfigKey, rc) return req.Clone(newctx) } func (rp *HTTPReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { domain, _ := httppkg.CanonicalHost(req.Host) location := req.URL.Path user, passwd, _ := req.BasicAuth() if !rp.CheckAuth(domain, location, user, user, passwd) { rw.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } newreq := rp.injectRequestInfoToCtx(req) if req.Method == http.MethodConnect { rp.connectHandler(rw, newreq) } else { rp.proxy.ServeHTTP(rw, newreq) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/vhost/resource.go
pkg/util/vhost/resource.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vhost import ( "bytes" "io" "net/http" "os" "github.com/fatedier/frp/pkg/util/log" "github.com/fatedier/frp/pkg/util/version" ) var NotFoundPagePath = "" const ( NotFound = `<!DOCTYPE html> <html> <head> <title>Not Found</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body> <h1>The page you requested was not found.</h1> <p>Sorry, the page you are looking for is currently unavailable.<br/> Please try again later.</p> <p>The server is powered by <a href="https://github.com/fatedier/frp">frp</a>.</p> <p><em>Faithfully yours, frp.</em></p> </body> </html> ` ) func getNotFoundPageContent() []byte { var ( buf []byte err error ) if NotFoundPagePath != "" { buf, err = os.ReadFile(NotFoundPagePath) if err != nil { log.Warnf("read custom 404 page error: %v", err) buf = []byte(NotFound) } } else { buf = []byte(NotFound) } return buf } func NotFoundResponse() *http.Response { header := make(http.Header) header.Set("server", "frp/"+version.Full()) header.Set("Content-Type", "text/html") content := getNotFoundPageContent() res := &http.Response{ Status: "Not Found", StatusCode: 404, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: header, Body: io.NopCloser(bytes.NewReader(content)), ContentLength: int64(len(content)), } return res }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/vhost/https_test.go
pkg/util/vhost/https_test.go
package vhost import ( "crypto/tls" "net" "testing" "time" "github.com/stretchr/testify/require" ) func TestGetHTTPSHostname(t *testing.T) { require := require.New(t) l, err := net.Listen("tcp", "127.0.0.1:") require.NoError(err) defer l.Close() var conn net.Conn go func() { conn, _ = l.Accept() require.NotNil(conn) }() go func() { time.Sleep(100 * time.Millisecond) tls.Dial("tcp", l.Addr().String(), &tls.Config{ InsecureSkipVerify: true, ServerName: "example.com", }) }() time.Sleep(200 * time.Millisecond) _, infos, err := GetHTTPSHostname(conn) require.NoError(err) require.Equal("example.com", infos["Host"]) require.Equal("https", infos["Scheme"]) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/system/system_android.go
pkg/util/system/system_android.go
// Copyright 2024 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package system import ( "context" "net" "os/exec" "strings" "time" ) func EnableCompatibilityMode() { fixTimezone() fixDNSResolver() } // fixTimezone is used to try our best to fix timezone issue on some Android devices. func fixTimezone() { out, err := exec.Command("/system/bin/getprop", "persist.sys.timezone").Output() if err != nil { return } loc, err := time.LoadLocation(strings.TrimSpace(string(out))) if err != nil { return } time.Local = loc } // fixDNSResolver will first attempt to resolve google.com to check if the current DNS is available. // If it is not available, it will default to using 8.8.8.8 as the DNS server. // This is a workaround for the issue that golang can't get the default DNS servers on Android. func fixDNSResolver() { // First, we attempt to resolve a domain. If resolution is successful, no modifications are necessary. // In real-world scenarios, users may have already configured /etc/resolv.conf, or compiled directly // in the Android environment instead of using cross-platform compilation, so this issue does not arise. if net.DefaultResolver != nil { timeoutCtx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, err := net.DefaultResolver.LookupHost(timeoutCtx, "google.com") if err == nil { return } } // If the resolution fails, use 8.8.8.8 as the DNS server. // Note: If there are other methods to obtain the default DNS servers, the default DNS servers should be used preferentially. net.DefaultResolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, network, addr string) (net.Conn, error) { if addr == "127.0.0.1:53" || addr == "[::1]:53" { addr = "8.8.8.8:53" } var d net.Dialer return d.DialContext(ctx, network, addr) }, } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/system/system.go
pkg/util/system/system.go
// Copyright 2024 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !android package system // EnableCompatibilityMode enables compatibility mode for different system. // For example, on Android, the inability to obtain the correct time zone will result in incorrect log time output. func EnableCompatibilityMode() { }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/util/types.go
pkg/util/util/types.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package util func EmptyOr[T comparable](v T, fallback T) T { var zero T if zero == v { return fallback } return v }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/util/util.go
pkg/util/util/util.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package util import ( "crypto/md5" "crypto/rand" "crypto/subtle" "encoding/hex" "fmt" mathrand "math/rand/v2" "net" "strconv" "strings" "time" ) // RandID return a rand string used in frp. func RandID() (id string, err error) { return RandIDWithLen(16) } // RandIDWithLen return a rand string with idLen length. func RandIDWithLen(idLen int) (id string, err error) { if idLen <= 0 { return "", nil } b := make([]byte, idLen/2+1) _, err = rand.Read(b) if err != nil { return } id = fmt.Sprintf("%x", b) return id[:idLen], nil } func GetAuthKey(token string, timestamp int64) (key string) { md5Ctx := md5.New() md5Ctx.Write([]byte(token)) md5Ctx.Write([]byte(strconv.FormatInt(timestamp, 10))) data := md5Ctx.Sum(nil) return hex.EncodeToString(data) } func CanonicalAddr(host string, port int) (addr string) { if port == 80 || port == 443 { addr = host } else { addr = net.JoinHostPort(host, strconv.Itoa(port)) } return } func ParseRangeNumbers(rangeStr string) (numbers []int64, err error) { rangeStr = strings.TrimSpace(rangeStr) numbers = make([]int64, 0) // e.g. 1000-2000,2001,2002,3000-4000 numRanges := strings.Split(rangeStr, ",") for _, numRangeStr := range numRanges { // 1000-2000 or 2001 numArray := strings.Split(numRangeStr, "-") // length: only 1 or 2 is correct rangeType := len(numArray) switch rangeType { case 1: // single number singleNum, errRet := strconv.ParseInt(strings.TrimSpace(numArray[0]), 10, 64) if errRet != nil { err = fmt.Errorf("range number is invalid, %v", errRet) return } numbers = append(numbers, singleNum) case 2: // range numbers minValue, errRet := strconv.ParseInt(strings.TrimSpace(numArray[0]), 10, 64) if errRet != nil { err = fmt.Errorf("range number is invalid, %v", errRet) return } maxValue, errRet := strconv.ParseInt(strings.TrimSpace(numArray[1]), 10, 64) if errRet != nil { err = fmt.Errorf("range number is invalid, %v", errRet) return } if maxValue < minValue { err = fmt.Errorf("range number is invalid") return } for i := minValue; i <= maxValue; i++ { numbers = append(numbers, i) } default: err = fmt.Errorf("range number is invalid") return } } return } func GenerateResponseErrorString(summary string, err error, detailed bool) string { if detailed { return err.Error() } return summary } func RandomSleep(duration time.Duration, minRatio, maxRatio float64) time.Duration { minValue := int64(minRatio * 1000.0) maxValue := int64(maxRatio * 1000.0) var n int64 if maxValue <= minValue { n = minValue } else { n = mathrand.Int64N(maxValue-minValue) + minValue } d := duration * time.Duration(n) / time.Duration(1000) time.Sleep(d) return d } func ConstantTimeEqString(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/util/util_test.go
pkg/util/util/util_test.go
package util import ( "testing" "github.com/stretchr/testify/require" ) func TestRandId(t *testing.T) { require := require.New(t) id, err := RandID() require.NoError(err) t.Log(id) require.Equal(16, len(id)) } func TestGetAuthKey(t *testing.T) { require := require.New(t) key := GetAuthKey("1234", 1488720000) require.Equal("6df41a43725f0c770fd56379e12acf8c", key) } func TestParseRangeNumbers(t *testing.T) { require := require.New(t) numbers, err := ParseRangeNumbers("2-5") require.NoError(err) require.Equal([]int64{2, 3, 4, 5}, numbers) numbers, err = ParseRangeNumbers("1") require.NoError(err) require.Equal([]int64{1}, numbers) numbers, err = ParseRangeNumbers("3-5,8") require.NoError(err) require.Equal([]int64{3, 4, 5, 8}, numbers) numbers, err = ParseRangeNumbers(" 3-5,8, 10-12 ") require.NoError(err) require.Equal([]int64{3, 4, 5, 8, 10, 11, 12}, numbers) _, err = ParseRangeNumbers("3-a") require.Error(err) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/xlog/log_writer.go
pkg/util/xlog/log_writer.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package xlog import "strings" // LogWriter forwards writes to frp's logger at configurable level. // It is safe for concurrent use as long as the underlying Logger is thread-safe. type LogWriter struct { xl *Logger logFunc func(string) } func (w LogWriter) Write(p []byte) (n int, err error) { msg := strings.TrimSpace(string(p)) w.logFunc(msg) return len(p), nil } func NewTraceWriter(xl *Logger) LogWriter { return LogWriter{ xl: xl, logFunc: func(msg string) { xl.Tracef("%s", msg) }, } } func NewDebugWriter(xl *Logger) LogWriter { return LogWriter{ xl: xl, logFunc: func(msg string) { xl.Debugf("%s", msg) }, } } func NewInfoWriter(xl *Logger) LogWriter { return LogWriter{ xl: xl, logFunc: func(msg string) { xl.Infof("%s", msg) }, } } func NewWarnWriter(xl *Logger) LogWriter { return LogWriter{ xl: xl, logFunc: func(msg string) { xl.Warnf("%s", msg) }, } } func NewErrorWriter(xl *Logger) LogWriter { return LogWriter{ xl: xl, logFunc: func(msg string) { xl.Errorf("%s", msg) }, } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/xlog/ctx.go
pkg/util/xlog/ctx.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package xlog import ( "context" ) type key int const ( xlogKey key = 0 ) func NewContext(ctx context.Context, xl *Logger) context.Context { return context.WithValue(ctx, xlogKey, xl) } func FromContext(ctx context.Context) (xl *Logger, ok bool) { xl, ok = ctx.Value(xlogKey).(*Logger) return } func FromContextSafe(ctx context.Context) *Logger { xl, ok := ctx.Value(xlogKey).(*Logger) if !ok { xl = New() } return xl }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/xlog/xlog.go
pkg/util/xlog/xlog.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package xlog import ( "cmp" "slices" "github.com/fatedier/frp/pkg/util/log" ) type LogPrefix struct { // Name is the name of the prefix, it won't be displayed in log but used to identify the prefix. Name string // Value is the value of the prefix, it will be displayed in log. Value string // The prefix with higher priority will be displayed first, default is 10. Priority int } // Logger is not thread safety for operations on prefix type Logger struct { prefixes []LogPrefix prefixString string } func New() *Logger { return &Logger{ prefixes: make([]LogPrefix, 0), } } func (l *Logger) ResetPrefixes() (old []LogPrefix) { old = l.prefixes l.prefixes = make([]LogPrefix, 0) l.prefixString = "" return } func (l *Logger) AppendPrefix(prefix string) *Logger { return l.AddPrefix(LogPrefix{ Name: prefix, Value: prefix, Priority: 10, }) } func (l *Logger) AddPrefix(prefix LogPrefix) *Logger { found := false if prefix.Priority <= 0 { prefix.Priority = 10 } for _, p := range l.prefixes { if p.Name == prefix.Name { found = true p.Value = prefix.Value p.Priority = prefix.Priority } } if !found { l.prefixes = append(l.prefixes, prefix) } l.renderPrefixString() return l } func (l *Logger) renderPrefixString() { slices.SortStableFunc(l.prefixes, func(a, b LogPrefix) int { return cmp.Compare(a.Priority, b.Priority) }) l.prefixString = "" for _, v := range l.prefixes { l.prefixString += "[" + v.Value + "] " } } func (l *Logger) Spawn() *Logger { nl := New() nl.prefixes = append(nl.prefixes, l.prefixes...) nl.renderPrefixString() return nl } func (l *Logger) Errorf(format string, v ...any) { log.Logger.Errorf(l.prefixString+format, v...) } func (l *Logger) Warnf(format string, v ...any) { log.Logger.Warnf(l.prefixString+format, v...) } func (l *Logger) Infof(format string, v ...any) { log.Logger.Infof(l.prefixString+format, v...) } func (l *Logger) Debugf(format string, v ...any) { log.Logger.Debugf(l.prefixString+format, v...) } func (l *Logger) Tracef(format string, v ...any) { log.Logger.Tracef(l.prefixString+format, v...) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/limit/writer.go
pkg/util/limit/writer.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package limit import ( "context" "io" "golang.org/x/time/rate" ) type Writer struct { w io.Writer limiter *rate.Limiter } func NewWriter(w io.Writer, limiter *rate.Limiter) *Writer { return &Writer{ w: w, limiter: limiter, } } func (w *Writer) Write(p []byte) (n int, err error) { var nn int b := w.limiter.Burst() for { end := len(p) if end == 0 { break } if b < len(p) { end = b } err = w.limiter.WaitN(context.Background(), end) if err != nil { return } nn, err = w.w.Write(p[:end]) n += nn if err != nil { return } p = p[end:] } return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/limit/reader.go
pkg/util/limit/reader.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package limit import ( "context" "io" "golang.org/x/time/rate" ) type Reader struct { r io.Reader limiter *rate.Limiter } func NewReader(r io.Reader, limiter *rate.Limiter) *Reader { return &Reader{ r: r, limiter: limiter, } } func (r *Reader) Read(p []byte) (n int, err error) { b := r.limiter.Burst() if b < len(p) { p = p[:b] } n, err = r.r.Read(p) if err != nil { return } err = r.limiter.WaitN(context.Background(), n) if err != nil { return } return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/version/version.go
pkg/util/version/version.go
// Copyright 2016 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package version var version = "0.66.0" func Full() string { return version }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/tcpmux/httpconnect.go
pkg/util/tcpmux/httpconnect.go
// Copyright 2020 guylewin, guy@lewin.co.il // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcpmux import ( "bufio" "fmt" "io" "net" "net/http" "time" libnet "github.com/fatedier/golib/net" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/vhost" ) type HTTPConnectTCPMuxer struct { *vhost.Muxer // If passthrough is set to true, the CONNECT request will be forwarded to the backend service. // Otherwise, it will return an OK response to the client and forward the remaining content to the backend service. passthrough bool } func NewHTTPConnectTCPMuxer(listener net.Listener, passthrough bool, timeout time.Duration) (*HTTPConnectTCPMuxer, error) { ret := &HTTPConnectTCPMuxer{passthrough: passthrough} mux, err := vhost.NewMuxer(listener, ret.getHostFromHTTPConnect, timeout) mux.SetCheckAuthFunc(ret.auth). SetSuccessHookFunc(ret.sendConnectResponse). SetFailHookFunc(vhostFailed) ret.Muxer = mux return ret, err } func (muxer *HTTPConnectTCPMuxer) readHTTPConnectRequest(rd io.Reader) (host, httpUser, httpPwd string, err error) { bufioReader := bufio.NewReader(rd) req, err := http.ReadRequest(bufioReader) if err != nil { return } if req.Method != "CONNECT" { err = fmt.Errorf("connections to tcp vhost must be of method CONNECT") return } host, _ = httppkg.CanonicalHost(req.Host) proxyAuth := req.Header.Get("Proxy-Authorization") if proxyAuth != "" { httpUser, httpPwd, _ = httppkg.ParseBasicAuth(proxyAuth) } return } func (muxer *HTTPConnectTCPMuxer) sendConnectResponse(c net.Conn, _ map[string]string) error { if muxer.passthrough { return nil } res := httppkg.OkResponse() if res.Body != nil { defer res.Body.Close() } return res.Write(c) } func (muxer *HTTPConnectTCPMuxer) auth(c net.Conn, username, password string, reqInfo map[string]string) (bool, error) { reqUsername := reqInfo["HTTPUser"] reqPassword := reqInfo["HTTPPwd"] if username == reqUsername && password == reqPassword { return true, nil } resp := httppkg.ProxyUnauthorizedResponse() if resp.Body != nil { defer resp.Body.Close() } _ = resp.Write(c) return false, nil } func vhostFailed(c net.Conn) { res := vhost.NotFoundResponse() if res.Body != nil { defer res.Body.Close() } _ = res.Write(c) _ = c.Close() } func (muxer *HTTPConnectTCPMuxer) getHostFromHTTPConnect(c net.Conn) (net.Conn, map[string]string, error) { reqInfoMap := make(map[string]string, 0) sc, rd := libnet.NewSharedConn(c) host, httpUser, httpPwd, err := muxer.readHTTPConnectRequest(rd) if err != nil { return nil, reqInfoMap, err } reqInfoMap["Host"] = host reqInfoMap["Scheme"] = "tcp" reqInfoMap["HTTPUser"] = httpUser reqInfoMap["HTTPPwd"] = httpPwd outConn := c if muxer.passthrough { outConn = sc } return outConn, reqInfoMap, nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/listener.go
pkg/util/net/listener.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "fmt" "net" "sync" "github.com/fatedier/golib/errors" ) // InternalListener is a listener that can be used to accept connections from // other goroutines. type InternalListener struct { acceptCh chan net.Conn closed bool mu sync.Mutex } func NewInternalListener() *InternalListener { return &InternalListener{ acceptCh: make(chan net.Conn, 128), } } func (l *InternalListener) Accept() (net.Conn, error) { conn, ok := <-l.acceptCh if !ok { return nil, fmt.Errorf("listener closed") } return conn, nil } func (l *InternalListener) PutConn(conn net.Conn) error { err := errors.PanicToError(func() { select { case l.acceptCh <- conn: default: conn.Close() } }) if err != nil { return fmt.Errorf("put conn error: listener is closed") } return nil } func (l *InternalListener) Close() error { l.mu.Lock() defer l.mu.Unlock() if !l.closed { close(l.acceptCh) l.closed = true } return nil } func (l *InternalListener) Addr() net.Addr { return &InternalAddr{} } type InternalAddr struct{} func (ia *InternalAddr) Network() string { return "internal" } func (ia *InternalAddr) String() string { return "internal" }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/proxyprotocol.go
pkg/util/net/proxyprotocol.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "bytes" "fmt" "net" pp "github.com/pires/go-proxyproto" ) func BuildProxyProtocolHeaderStruct(srcAddr, dstAddr net.Addr, version string) *pp.Header { var versionByte byte if version == "v1" { versionByte = 1 } else { versionByte = 2 // default to v2 } return pp.HeaderProxyFromAddrs(versionByte, srcAddr, dstAddr) } func BuildProxyProtocolHeader(srcAddr, dstAddr net.Addr, version string) ([]byte, error) { h := BuildProxyProtocolHeaderStruct(srcAddr, dstAddr, version) // Convert header to bytes using a buffer var buf bytes.Buffer _, err := h.WriteTo(&buf) if err != nil { return nil, fmt.Errorf("failed to write proxy protocol header: %v", err) } return buf.Bytes(), nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/websocket.go
pkg/util/net/websocket.go
package net import ( "errors" "net" "net/http" "time" "golang.org/x/net/websocket" ) var ErrWebsocketListenerClosed = errors.New("websocket listener closed") const ( FrpWebsocketPath = "/~!frp" ) type WebsocketListener struct { ln net.Listener acceptCh chan net.Conn server *http.Server } // NewWebsocketListener to handle websocket connections // ln: tcp listener for websocket connections func NewWebsocketListener(ln net.Listener) (wl *WebsocketListener) { wl = &WebsocketListener{ acceptCh: make(chan net.Conn), } muxer := http.NewServeMux() muxer.Handle(FrpWebsocketPath, websocket.Handler(func(c *websocket.Conn) { notifyCh := make(chan struct{}) conn := WrapCloseNotifyConn(c, func(_ error) { close(notifyCh) }) wl.acceptCh <- conn <-notifyCh })) wl.server = &http.Server{ Addr: ln.Addr().String(), Handler: muxer, ReadHeaderTimeout: 60 * time.Second, } go func() { _ = wl.server.Serve(ln) }() return } func (p *WebsocketListener) Accept() (net.Conn, error) { c, ok := <-p.acceptCh if !ok { return nil, ErrWebsocketListenerClosed } return c, nil } func (p *WebsocketListener) Close() error { return p.server.Close() } func (p *WebsocketListener) Addr() net.Addr { return p.ln.Addr() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/dns.go
pkg/util/net/dns.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "context" "net" ) func SetDefaultDNSAddress(dnsAddress string) { if _, _, err := net.SplitHostPort(dnsAddress); err != nil { dnsAddress = net.JoinHostPort(dnsAddress, "53") } // Change default dns server net.DefaultResolver = &net.Resolver{ PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) { return net.Dial(network, dnsAddress) }, } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/conn.go
pkg/util/net/conn.go
// Copyright 2016 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "context" "errors" "io" "net" "sync/atomic" "time" "github.com/fatedier/golib/crypto" quic "github.com/quic-go/quic-go" "github.com/fatedier/frp/pkg/util/xlog" ) type ContextGetter interface { Context() context.Context } type ContextSetter interface { WithContext(ctx context.Context) } func NewLogFromConn(conn net.Conn) *xlog.Logger { if c, ok := conn.(ContextGetter); ok { return xlog.FromContextSafe(c.Context()) } return xlog.New() } func NewContextFromConn(conn net.Conn) context.Context { if c, ok := conn.(ContextGetter); ok { return c.Context() } return context.Background() } // ContextConn is the connection with context type ContextConn struct { net.Conn ctx context.Context } func NewContextConn(ctx context.Context, c net.Conn) *ContextConn { return &ContextConn{ Conn: c, ctx: ctx, } } func (c *ContextConn) WithContext(ctx context.Context) { c.ctx = ctx } func (c *ContextConn) Context() context.Context { return c.ctx } type WrapReadWriteCloserConn struct { io.ReadWriteCloser underConn net.Conn remoteAddr net.Addr } func WrapReadWriteCloserToConn(rwc io.ReadWriteCloser, underConn net.Conn) *WrapReadWriteCloserConn { return &WrapReadWriteCloserConn{ ReadWriteCloser: rwc, underConn: underConn, } } func (conn *WrapReadWriteCloserConn) LocalAddr() net.Addr { if conn.underConn != nil { return conn.underConn.LocalAddr() } return (*net.TCPAddr)(nil) } func (conn *WrapReadWriteCloserConn) SetRemoteAddr(addr net.Addr) { conn.remoteAddr = addr } func (conn *WrapReadWriteCloserConn) RemoteAddr() net.Addr { if conn.remoteAddr != nil { return conn.remoteAddr } if conn.underConn != nil { return conn.underConn.RemoteAddr() } return (*net.TCPAddr)(nil) } func (conn *WrapReadWriteCloserConn) SetDeadline(t time.Time) error { if conn.underConn != nil { return conn.underConn.SetDeadline(t) } return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} } func (conn *WrapReadWriteCloserConn) SetReadDeadline(t time.Time) error { if conn.underConn != nil { return conn.underConn.SetReadDeadline(t) } return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} } func (conn *WrapReadWriteCloserConn) SetWriteDeadline(t time.Time) error { if conn.underConn != nil { return conn.underConn.SetWriteDeadline(t) } return &net.OpError{Op: "set", Net: "wrap", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} } type CloseNotifyConn struct { net.Conn // 1 means closed closeFlag int32 closeFn func(error) } // closeFn will be only called once with the error (nil if Close() was called, non-nil if CloseWithError() was called) func WrapCloseNotifyConn(c net.Conn, closeFn func(error)) *CloseNotifyConn { return &CloseNotifyConn{ Conn: c, closeFn: closeFn, } } func (cc *CloseNotifyConn) Close() (err error) { pflag := atomic.SwapInt32(&cc.closeFlag, 1) if pflag == 0 { err = cc.Conn.Close() if cc.closeFn != nil { cc.closeFn(nil) } } return } // CloseWithError closes the connection and passes the error to the close callback. func (cc *CloseNotifyConn) CloseWithError(err error) error { pflag := atomic.SwapInt32(&cc.closeFlag, 1) if pflag == 0 { closeErr := cc.Conn.Close() if cc.closeFn != nil { cc.closeFn(err) } return closeErr } return nil } type StatsConn struct { net.Conn closed int64 // 1 means closed totalRead int64 totalWrite int64 statsFunc func(totalRead, totalWrite int64) } func WrapStatsConn(conn net.Conn, statsFunc func(total, totalWrite int64)) *StatsConn { return &StatsConn{ Conn: conn, statsFunc: statsFunc, } } func (statsConn *StatsConn) Read(p []byte) (n int, err error) { n, err = statsConn.Conn.Read(p) statsConn.totalRead += int64(n) return } func (statsConn *StatsConn) Write(p []byte) (n int, err error) { n, err = statsConn.Conn.Write(p) statsConn.totalWrite += int64(n) return } func (statsConn *StatsConn) Close() (err error) { old := atomic.SwapInt64(&statsConn.closed, 1) if old != 1 { err = statsConn.Conn.Close() if statsConn.statsFunc != nil { statsConn.statsFunc(statsConn.totalRead, statsConn.totalWrite) } } return } type wrapQuicStream struct { *quic.Stream c *quic.Conn } func QuicStreamToNetConn(s *quic.Stream, c *quic.Conn) net.Conn { return &wrapQuicStream{ Stream: s, c: c, } } func (conn *wrapQuicStream) LocalAddr() net.Addr { if conn.c != nil { return conn.c.LocalAddr() } return (*net.TCPAddr)(nil) } func (conn *wrapQuicStream) RemoteAddr() net.Addr { if conn.c != nil { return conn.c.RemoteAddr() } return (*net.TCPAddr)(nil) } func (conn *wrapQuicStream) Close() error { conn.CancelRead(0) return conn.Stream.Close() } func NewCryptoReadWriter(rw io.ReadWriter, key []byte) (io.ReadWriter, error) { encReader := crypto.NewReader(rw, key) encWriter, err := crypto.NewWriter(rw, key) if err != nil { return nil, err } return struct { io.Reader io.Writer }{ Reader: encReader, Writer: encWriter, }, nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/udp.go
pkg/util/net/udp.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "fmt" "io" "net" "strconv" "sync" "time" "github.com/fatedier/golib/pool" ) type UDPPacket struct { Buf []byte LocalAddr net.Addr RemoteAddr net.Addr } type FakeUDPConn struct { l *UDPListener localAddr net.Addr remoteAddr net.Addr packets chan []byte closeFlag bool lastActive time.Time mu sync.RWMutex } func NewFakeUDPConn(l *UDPListener, laddr, raddr net.Addr) *FakeUDPConn { fc := &FakeUDPConn{ l: l, localAddr: laddr, remoteAddr: raddr, packets: make(chan []byte, 20), } go func() { for { time.Sleep(5 * time.Second) fc.mu.RLock() if time.Since(fc.lastActive) > 10*time.Second { fc.mu.RUnlock() fc.Close() break } fc.mu.RUnlock() } }() return fc } func (c *FakeUDPConn) putPacket(content []byte) { defer func() { _ = recover() }() select { case c.packets <- content: default: } } func (c *FakeUDPConn) Read(b []byte) (n int, err error) { content, ok := <-c.packets if !ok { return 0, io.EOF } c.mu.Lock() c.lastActive = time.Now() c.mu.Unlock() if len(b) < len(content) { n = len(b) } else { n = len(content) } copy(b, content) return n, nil } func (c *FakeUDPConn) Write(b []byte) (n int, err error) { c.mu.RLock() if c.closeFlag { c.mu.RUnlock() return 0, io.ErrClosedPipe } c.mu.RUnlock() packet := &UDPPacket{ Buf: b, LocalAddr: c.localAddr, RemoteAddr: c.remoteAddr, } _ = c.l.writeUDPPacket(packet) c.mu.Lock() c.lastActive = time.Now() c.mu.Unlock() return len(b), nil } func (c *FakeUDPConn) Close() error { c.mu.Lock() defer c.mu.Unlock() if !c.closeFlag { c.closeFlag = true close(c.packets) } return nil } func (c *FakeUDPConn) IsClosed() bool { c.mu.RLock() defer c.mu.RUnlock() return c.closeFlag } func (c *FakeUDPConn) LocalAddr() net.Addr { return c.localAddr } func (c *FakeUDPConn) RemoteAddr() net.Addr { return c.remoteAddr } func (c *FakeUDPConn) SetDeadline(_ time.Time) error { return nil } func (c *FakeUDPConn) SetReadDeadline(_ time.Time) error { return nil } func (c *FakeUDPConn) SetWriteDeadline(_ time.Time) error { return nil } type UDPListener struct { addr net.Addr acceptCh chan net.Conn writeCh chan *UDPPacket readConn net.Conn closeFlag bool fakeConns map[string]*FakeUDPConn } func ListenUDP(bindAddr string, bindPort int) (l *UDPListener, err error) { udpAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(bindAddr, strconv.Itoa(bindPort))) if err != nil { return l, err } readConn, err := net.ListenUDP("udp", udpAddr) l = &UDPListener{ addr: udpAddr, acceptCh: make(chan net.Conn), writeCh: make(chan *UDPPacket, 1000), fakeConns: make(map[string]*FakeUDPConn), } // for reading go func() { for { buf := pool.GetBuf(1450) n, remoteAddr, err := readConn.ReadFromUDP(buf) if err != nil { close(l.acceptCh) close(l.writeCh) return } fakeConn, exist := l.fakeConns[remoteAddr.String()] if !exist || fakeConn.IsClosed() { fakeConn = NewFakeUDPConn(l, l.Addr(), remoteAddr) l.fakeConns[remoteAddr.String()] = fakeConn } fakeConn.putPacket(buf[:n]) l.acceptCh <- fakeConn } }() // for writing go func() { for { packet, ok := <-l.writeCh if !ok { return } if addr, ok := packet.RemoteAddr.(*net.UDPAddr); ok { _, _ = readConn.WriteToUDP(packet.Buf, addr) } } }() return } func (l *UDPListener) writeUDPPacket(packet *UDPPacket) (err error) { defer func() { if errRet := recover(); errRet != nil { err = fmt.Errorf("udp write closed listener") } }() l.writeCh <- packet return } func (l *UDPListener) WriteMsg(buf []byte, remoteAddr *net.UDPAddr) (err error) { // only set remote addr here packet := &UDPPacket{ Buf: buf, RemoteAddr: remoteAddr, } err = l.writeUDPPacket(packet) return } func (l *UDPListener) Accept() (net.Conn, error) { conn, ok := <-l.acceptCh if !ok { return conn, fmt.Errorf("channel for udp listener closed") } return conn, nil } func (l *UDPListener) Close() error { if !l.closeFlag { l.closeFlag = true if l.readConn != nil { l.readConn.Close() } } return nil } func (l *UDPListener) Addr() net.Addr { return l.addr } // ConnectedUDPConn is a wrapper for net.UDPConn which converts WriteTo syscalls // to Write syscalls that are 4 times faster on some OS'es. This should only be // used for connections that were produced by a net.Dial* call. type ConnectedUDPConn struct{ *net.UDPConn } // WriteTo redirects all writes to the Write syscall, which is 4 times faster. func (c *ConnectedUDPConn) WriteTo(b []byte, _ net.Addr) (int, error) { return c.Write(b) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/http.go
pkg/util/net/http.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "compress/gzip" "io" "net/http" "strings" "time" "github.com/fatedier/frp/pkg/util/util" ) type HTTPAuthMiddleware struct { user string passwd string authFailDelay time.Duration } func NewHTTPAuthMiddleware(user, passwd string) *HTTPAuthMiddleware { return &HTTPAuthMiddleware{ user: user, passwd: passwd, } } func (authMid *HTTPAuthMiddleware) SetAuthFailDelay(delay time.Duration) *HTTPAuthMiddleware { authMid.authFailDelay = delay return authMid } func (authMid *HTTPAuthMiddleware) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reqUser, reqPasswd, hasAuth := r.BasicAuth() if (authMid.user == "" && authMid.passwd == "") || (hasAuth && util.ConstantTimeEqString(reqUser, authMid.user) && util.ConstantTimeEqString(reqPasswd, authMid.passwd)) { next.ServeHTTP(w, r) } else { if authMid.authFailDelay > 0 { time.Sleep(authMid.authFailDelay) } w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) } }) } type HTTPGzipWrapper struct { h http.Handler } func (gw *HTTPGzipWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { gw.h.ServeHTTP(w, r) return } w.Header().Set("Content-Encoding", "gzip") gz := gzip.NewWriter(w) defer gz.Close() gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w} gw.h.ServeHTTP(gzr, r) } func MakeHTTPGzipHandler(h http.Handler) http.Handler { return &HTTPGzipWrapper{ h: h, } } type gzipResponseWriter struct { io.Writer http.ResponseWriter } func (w gzipResponseWriter) Write(b []byte) (int, error) { return w.Writer.Write(b) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/kcp.go
pkg/util/net/kcp.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "fmt" "net" kcp "github.com/xtaci/kcp-go/v5" ) type KCPListener struct { listener net.Listener acceptCh chan net.Conn closeFlag bool } func ListenKcp(address string) (l *KCPListener, err error) { listener, err := kcp.ListenWithOptions(address, nil, 10, 3) if err != nil { return l, err } _ = listener.SetReadBuffer(4194304) _ = listener.SetWriteBuffer(4194304) l = &KCPListener{ listener: listener, acceptCh: make(chan net.Conn), closeFlag: false, } go func() { for { conn, err := listener.AcceptKCP() if err != nil { if l.closeFlag { close(l.acceptCh) return } continue } conn.SetStreamMode(true) conn.SetWriteDelay(true) conn.SetNoDelay(1, 20, 2, 1) conn.SetMtu(1350) conn.SetWindowSize(1024, 1024) conn.SetACKNoDelay(false) l.acceptCh <- conn } }() return l, err } func (l *KCPListener) Accept() (net.Conn, error) { conn, ok := <-l.acceptCh if !ok { return conn, fmt.Errorf("channel for kcp listener closed") } return conn, nil } func (l *KCPListener) Close() error { if !l.closeFlag { l.closeFlag = true l.listener.Close() } return nil } func (l *KCPListener) Addr() net.Addr { return l.listener.Addr() } func NewKCPConnFromUDP(conn *net.UDPConn, connected bool, raddr string) (net.Conn, error) { udpAddr, err := net.ResolveUDPAddr("udp", raddr) if err != nil { return nil, err } var pConn net.PacketConn = conn if connected { pConn = &ConnectedUDPConn{conn} } kcpConn, err := kcp.NewConn3(1, udpAddr, nil, 10, 3, pConn) if err != nil { return nil, err } kcpConn.SetStreamMode(true) kcpConn.SetWriteDelay(true) kcpConn.SetNoDelay(1, 20, 2, 1) kcpConn.SetMtu(1350) kcpConn.SetWindowSize(1024, 1024) kcpConn.SetACKNoDelay(false) return kcpConn, nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/proxyprotocol_test.go
pkg/util/net/proxyprotocol_test.go
package net import ( "net" "testing" pp "github.com/pires/go-proxyproto" "github.com/stretchr/testify/require" ) func TestBuildProxyProtocolHeader(t *testing.T) { require := require.New(t) tests := []struct { name string srcAddr net.Addr dstAddr net.Addr version string expectError bool }{ { name: "UDP IPv4 v2", srcAddr: &net.UDPAddr{IP: net.ParseIP("192.168.1.100"), Port: 12345}, dstAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: 3306}, version: "v2", expectError: false, }, { name: "TCP IPv4 v1", srcAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 12345}, dstAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 80}, version: "v1", expectError: false, }, { name: "UDP IPv6 v2", srcAddr: &net.UDPAddr{IP: net.ParseIP("2001:db8::1"), Port: 12345}, dstAddr: &net.UDPAddr{IP: net.ParseIP("::1"), Port: 3306}, version: "v2", expectError: false, }, { name: "TCP IPv6 v1", srcAddr: &net.TCPAddr{IP: net.ParseIP("::1"), Port: 12345}, dstAddr: &net.TCPAddr{IP: net.ParseIP("2001:db8::1"), Port: 80}, version: "v1", expectError: false, }, { name: "nil source address", srcAddr: nil, dstAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: 3306}, version: "v2", expectError: false, }, { name: "nil destination address", srcAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 12345}, dstAddr: nil, version: "v2", expectError: false, }, { name: "unsupported address type", srcAddr: &net.UnixAddr{Name: "/tmp/test.sock", Net: "unix"}, dstAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: 3306}, version: "v2", expectError: false, }, } for _, tt := range tests { header, err := BuildProxyProtocolHeader(tt.srcAddr, tt.dstAddr, tt.version) if tt.expectError { require.Error(err, "test case: %s", tt.name) continue } require.NoError(err, "test case: %s", tt.name) require.NotEmpty(header, "test case: %s", tt.name) } } func TestBuildProxyProtocolHeaderStruct(t *testing.T) { require := require.New(t) tests := []struct { name string srcAddr net.Addr dstAddr net.Addr version string expectedProtocol pp.AddressFamilyAndProtocol expectedVersion byte expectedCommand pp.ProtocolVersionAndCommand expectedSourceAddr net.Addr expectedDestAddr net.Addr }{ { name: "TCP IPv4 v2", srcAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 12345}, dstAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 80}, version: "v2", expectedProtocol: pp.TCPv4, expectedVersion: 2, expectedCommand: pp.PROXY, expectedSourceAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 12345}, expectedDestAddr: &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 80}, }, { name: "UDP IPv6 v1", srcAddr: &net.UDPAddr{IP: net.ParseIP("2001:db8::1"), Port: 12345}, dstAddr: &net.UDPAddr{IP: net.ParseIP("::1"), Port: 3306}, version: "v1", expectedProtocol: pp.UDPv6, expectedVersion: 1, expectedCommand: pp.PROXY, expectedSourceAddr: &net.UDPAddr{IP: net.ParseIP("2001:db8::1"), Port: 12345}, expectedDestAddr: &net.UDPAddr{IP: net.ParseIP("::1"), Port: 3306}, }, { name: "TCP IPv6 default version", srcAddr: &net.TCPAddr{IP: net.ParseIP("::1"), Port: 12345}, dstAddr: &net.TCPAddr{IP: net.ParseIP("2001:db8::1"), Port: 80}, version: "", expectedProtocol: pp.TCPv6, expectedVersion: 2, // default to v2 expectedCommand: pp.PROXY, expectedSourceAddr: &net.TCPAddr{IP: net.ParseIP("::1"), Port: 12345}, expectedDestAddr: &net.TCPAddr{IP: net.ParseIP("2001:db8::1"), Port: 80}, }, { name: "nil source address", srcAddr: nil, dstAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: 3306}, version: "v2", expectedProtocol: pp.UNSPEC, expectedVersion: 2, expectedCommand: pp.LOCAL, expectedSourceAddr: nil, // go-proxyproto sets both to nil when srcAddr is nil expectedDestAddr: nil, }, { name: "nil destination address", srcAddr: &net.TCPAddr{IP: net.ParseIP("192.168.1.100"), Port: 12345}, dstAddr: nil, version: "v2", expectedProtocol: pp.UNSPEC, expectedVersion: 2, expectedCommand: pp.LOCAL, expectedSourceAddr: nil, // go-proxyproto sets both to nil when dstAddr is nil expectedDestAddr: nil, }, { name: "unsupported address type", srcAddr: &net.UnixAddr{Name: "/tmp/test.sock", Net: "unix"}, dstAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1"), Port: 3306}, version: "v2", expectedProtocol: pp.UNSPEC, expectedVersion: 2, expectedCommand: pp.LOCAL, expectedSourceAddr: nil, // go-proxyproto sets both to nil for unsupported types expectedDestAddr: nil, }, } for _, tt := range tests { header := BuildProxyProtocolHeaderStruct(tt.srcAddr, tt.dstAddr, tt.version) require.NotNil(header, "test case: %s", tt.name) require.Equal(tt.expectedCommand, header.Command, "test case: %s", tt.name) require.Equal(tt.expectedSourceAddr, header.SourceAddr, "test case: %s", tt.name) require.Equal(tt.expectedDestAddr, header.DestinationAddr, "test case: %s", tt.name) require.Equal(tt.expectedProtocol, header.TransportProtocol, "test case: %s", tt.name) require.Equal(tt.expectedVersion, header.Version, "test case: %s", tt.name) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/dial.go
pkg/util/net/dial.go
package net import ( "context" "net" "net/url" libnet "github.com/fatedier/golib/net" "golang.org/x/net/websocket" ) func DialHookCustomTLSHeadByte(enableTLS bool, disableCustomTLSHeadByte bool) libnet.AfterHookFunc { return func(ctx context.Context, c net.Conn, addr string) (context.Context, net.Conn, error) { if enableTLS && !disableCustomTLSHeadByte { _, err := c.Write([]byte{byte(FRPTLSHeadByte)}) if err != nil { return nil, nil, err } } return ctx, c, nil } } func DialHookWebsocket(protocol string, host string) libnet.AfterHookFunc { return func(ctx context.Context, c net.Conn, addr string) (context.Context, net.Conn, error) { if protocol != "wss" { protocol = "ws" } if host == "" { host = addr } addr = protocol + "://" + host + FrpWebsocketPath uri, err := url.Parse(addr) if err != nil { return nil, nil, err } origin := "http://" + uri.Host cfg, err := websocket.NewConfig(addr, origin) if err != nil { return nil, nil, err } conn, err := websocket.NewClient(cfg, c) if err != nil { return nil, nil, err } return ctx, conn, nil } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/net/tls.go
pkg/util/net/tls.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package net import ( "crypto/tls" "fmt" "net" "time" libnet "github.com/fatedier/golib/net" ) var FRPTLSHeadByte = 0x17 func CheckAndEnableTLSServerConnWithTimeout( c net.Conn, tlsConfig *tls.Config, tlsOnly bool, timeout time.Duration, ) (out net.Conn, isTLS bool, custom bool, err error) { sc, r := libnet.NewSharedConnSize(c, 2) buf := make([]byte, 1) var n int _ = c.SetReadDeadline(time.Now().Add(timeout)) n, err = r.Read(buf) _ = c.SetReadDeadline(time.Time{}) if err != nil { return } switch { case n == 1 && int(buf[0]) == FRPTLSHeadByte: out = tls.Server(c, tlsConfig) isTLS = true custom = true case n == 1 && int(buf[0]) == 0x16: out = tls.Server(sc, tlsConfig) isTLS = true default: if tlsOnly { err = fmt.Errorf("non-TLS connection received on a TlsOnly server") return } out = sc } return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/metric/metrics.go
pkg/util/metric/metrics.go
// Copyright 2020 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metric // GaugeMetric represents a single numerical value that can arbitrarily go up // and down. type GaugeMetric interface { Inc() Dec() Set(float64) } // CounterMetric represents a single numerical value that only ever // goes up. type CounterMetric interface { Inc() } // HistogramMetric counts individual observations. type HistogramMetric interface { Observe(float64) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/metric/date_counter.go
pkg/util/metric/date_counter.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metric import ( "sync" "time" ) type DateCounter interface { TodayCount() int64 GetLastDaysCount(lastdays int64) []int64 Inc(int64) Dec(int64) Snapshot() DateCounter Clear() } func NewDateCounter(reserveDays int64) DateCounter { if reserveDays <= 0 { reserveDays = 1 } return newStandardDateCounter(reserveDays) } type StandardDateCounter struct { reserveDays int64 counts []int64 lastUpdateDate time.Time mu sync.Mutex } func newStandardDateCounter(reserveDays int64) *StandardDateCounter { now := time.Now() now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) s := &StandardDateCounter{ reserveDays: reserveDays, counts: make([]int64, reserveDays), lastUpdateDate: now, } return s } func (c *StandardDateCounter) TodayCount() int64 { c.mu.Lock() defer c.mu.Unlock() c.rotate(time.Now()) return c.counts[0] } func (c *StandardDateCounter) GetLastDaysCount(lastdays int64) []int64 { if lastdays > c.reserveDays { lastdays = c.reserveDays } counts := make([]int64, lastdays) c.mu.Lock() defer c.mu.Unlock() c.rotate(time.Now()) for i := 0; i < int(lastdays); i++ { counts[i] = c.counts[i] } return counts } func (c *StandardDateCounter) Inc(count int64) { c.mu.Lock() defer c.mu.Unlock() c.rotate(time.Now()) c.counts[0] += count } func (c *StandardDateCounter) Dec(count int64) { c.mu.Lock() defer c.mu.Unlock() c.rotate(time.Now()) c.counts[0] -= count } func (c *StandardDateCounter) Snapshot() DateCounter { c.mu.Lock() defer c.mu.Unlock() tmp := newStandardDateCounter(c.reserveDays) for i := 0; i < int(c.reserveDays); i++ { tmp.counts[i] = c.counts[i] } return tmp } func (c *StandardDateCounter) Clear() { c.mu.Lock() defer c.mu.Unlock() for i := 0; i < int(c.reserveDays); i++ { c.counts[i] = 0 } } // rotate // Must hold the lock before calling this function. func (c *StandardDateCounter) rotate(now time.Time) { now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) days := int(now.Sub(c.lastUpdateDate).Hours() / 24) defer func() { c.lastUpdateDate = now }() if days <= 0 { return } else if days >= int(c.reserveDays) { c.counts = make([]int64, c.reserveDays) return } newCounts := make([]int64, c.reserveDays) for i := days; i < int(c.reserveDays); i++ { newCounts[i] = c.counts[i-days] } c.counts = newCounts }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/metric/counter_test.go
pkg/util/metric/counter_test.go
package metric import ( "testing" "github.com/stretchr/testify/require" ) func TestCounter(t *testing.T) { require := require.New(t) c := NewCounter() c.Inc(10) require.EqualValues(10, c.Count()) c.Dec(5) require.EqualValues(5, c.Count()) cTmp := c.Snapshot() require.EqualValues(5, cTmp.Count()) c.Clear() require.EqualValues(0, c.Count()) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/metric/counter.go
pkg/util/metric/counter.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metric import ( "sync/atomic" ) type Counter interface { Count() int32 Inc(int32) Dec(int32) Snapshot() Counter Clear() } func NewCounter() Counter { return &StandardCounter{ count: 0, } } type StandardCounter struct { count int32 } func (c *StandardCounter) Count() int32 { return atomic.LoadInt32(&c.count) } func (c *StandardCounter) Inc(count int32) { atomic.AddInt32(&c.count, count) } func (c *StandardCounter) Dec(count int32) { atomic.AddInt32(&c.count, -count) } func (c *StandardCounter) Snapshot() Counter { tmp := &StandardCounter{ count: atomic.LoadInt32(&c.count), } return tmp } func (c *StandardCounter) Clear() { atomic.StoreInt32(&c.count, 0) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/metric/date_counter_test.go
pkg/util/metric/date_counter_test.go
package metric import ( "testing" "github.com/stretchr/testify/require" ) func TestDateCounter(t *testing.T) { require := require.New(t) dc := NewDateCounter(3) dc.Inc(10) require.EqualValues(10, dc.TodayCount()) dc.Dec(5) require.EqualValues(5, dc.TodayCount()) counts := dc.GetLastDaysCount(3) require.EqualValues(3, len(counts)) require.EqualValues(5, counts[0]) require.EqualValues(0, counts[1]) require.EqualValues(0, counts[2]) dcTmp := dc.Snapshot() require.EqualValues(5, dcTmp.TodayCount()) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/log/log.go
pkg/util/log/log.go
// Copyright 2016 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package log import ( "bytes" "os" "github.com/fatedier/golib/log" ) var ( TraceLevel = log.TraceLevel DebugLevel = log.DebugLevel InfoLevel = log.InfoLevel WarnLevel = log.WarnLevel ErrorLevel = log.ErrorLevel ) var Logger *log.Logger func init() { Logger = log.New( log.WithCaller(true), log.AddCallerSkip(1), log.WithLevel(log.InfoLevel), ) } func InitLogger(logPath string, levelStr string, maxDays int, disableLogColor bool) { options := []log.Option{} if logPath == "console" { if !disableLogColor { options = append(options, log.WithOutput(log.NewConsoleWriter(log.ConsoleConfig{ Colorful: true, }, os.Stdout)), ) } } else { writer := log.NewRotateFileWriter(log.RotateFileConfig{ FileName: logPath, Mode: log.RotateFileModeDaily, MaxDays: maxDays, }) writer.Init() options = append(options, log.WithOutput(writer)) } level, err := log.ParseLevel(levelStr) if err != nil { level = log.InfoLevel } options = append(options, log.WithLevel(level)) Logger = Logger.WithOptions(options...) } func Errorf(format string, v ...any) { Logger.Errorf(format, v...) } func Warnf(format string, v ...any) { Logger.Warnf(format, v...) } func Infof(format string, v ...any) { Logger.Infof(format, v...) } func Debugf(format string, v ...any) { Logger.Debugf(format, v...) } func Tracef(format string, v ...any) { Logger.Tracef(format, v...) } func Logf(level log.Level, offset int, format string, v ...any) { Logger.Logf(level, offset, format, v...) } type WriteLogger struct { level log.Level offset int } func NewWriteLogger(level log.Level, offset int) *WriteLogger { return &WriteLogger{ level: level, offset: offset, } } func (w *WriteLogger) Write(p []byte) (n int, err error) { Logger.Log(w.level, w.offset, string(bytes.TrimRight(p, "\n"))) return len(p), nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/wait/backoff.go
pkg/util/wait/backoff.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package wait import ( "math/rand/v2" "time" "github.com/fatedier/frp/pkg/util/util" ) type BackoffFunc func(previousDuration time.Duration, previousConditionError bool) time.Duration func (f BackoffFunc) Backoff(previousDuration time.Duration, previousConditionError bool) time.Duration { return f(previousDuration, previousConditionError) } type BackoffManager interface { Backoff(previousDuration time.Duration, previousConditionError bool) time.Duration } type FastBackoffOptions struct { Duration time.Duration Factor float64 Jitter float64 MaxDuration time.Duration InitDurationIfFail time.Duration // If FastRetryCount > 0, then within the FastRetryWindow time window, // the retry will be performed with a delay of FastRetryDelay for the first FastRetryCount calls. FastRetryCount int FastRetryDelay time.Duration FastRetryJitter float64 FastRetryWindow time.Duration } type fastBackoffImpl struct { options FastBackoffOptions lastCalledTime time.Time consecutiveErrCount int fastRetryCutoffTime time.Time countsInFastRetryWindow int } func NewFastBackoffManager(options FastBackoffOptions) BackoffManager { return &fastBackoffImpl{ options: options, countsInFastRetryWindow: 1, } } func (f *fastBackoffImpl) Backoff(previousDuration time.Duration, previousConditionError bool) time.Duration { if f.lastCalledTime.IsZero() { f.lastCalledTime = time.Now() return f.options.Duration } now := time.Now() f.lastCalledTime = now if previousConditionError { f.consecutiveErrCount++ } else { f.consecutiveErrCount = 0 } if f.options.FastRetryCount > 0 && previousConditionError { f.countsInFastRetryWindow++ if f.countsInFastRetryWindow <= f.options.FastRetryCount { return Jitter(f.options.FastRetryDelay, f.options.FastRetryJitter) } if now.After(f.fastRetryCutoffTime) { // reset f.fastRetryCutoffTime = now.Add(f.options.FastRetryWindow) f.countsInFastRetryWindow = 0 } } if previousConditionError { var duration time.Duration if f.consecutiveErrCount == 1 { duration = util.EmptyOr(f.options.InitDurationIfFail, previousDuration) } else { duration = previousDuration } duration = util.EmptyOr(duration, time.Second) if f.options.Factor != 0 { duration = time.Duration(float64(duration) * f.options.Factor) } if f.options.Jitter > 0 { duration = Jitter(duration, f.options.Jitter) } if f.options.MaxDuration > 0 && duration > f.options.MaxDuration { duration = f.options.MaxDuration } return duration } return f.options.Duration } func BackoffUntil(f func() (bool, error), backoff BackoffManager, sliding bool, stopCh <-chan struct{}) { var delay time.Duration previousError := false ticker := time.NewTicker(backoff.Backoff(delay, previousError)) defer ticker.Stop() for { select { case <-stopCh: return default: } if !sliding { delay = backoff.Backoff(delay, previousError) } if done, err := f(); done { return } else if err != nil { previousError = true } else { previousError = false } if sliding { delay = backoff.Backoff(delay, previousError) } ticker.Reset(delay) select { case <-stopCh: return case <-ticker.C: } } } // Jitter returns a time.Duration between duration and duration + maxFactor * // duration. // // This allows clients to avoid converging on periodic behavior. If maxFactor // is 0.0, a suggested default value will be chosen. func Jitter(duration time.Duration, maxFactor float64) time.Duration { if maxFactor <= 0.0 { maxFactor = 1.0 } wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration)) return wait } func Until(f func(), period time.Duration, stopCh <-chan struct{}) { ff := func() (bool, error) { f() return false, nil } BackoffUntil(ff, BackoffFunc(func(time.Duration, bool) time.Duration { return period }), true, stopCh) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/http/server.go
pkg/util/http/server.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package http import ( "crypto/tls" "net" "net/http" "net/http/pprof" "strconv" "time" "github.com/gorilla/mux" "github.com/fatedier/frp/assets" v1 "github.com/fatedier/frp/pkg/config/v1" netpkg "github.com/fatedier/frp/pkg/util/net" ) var ( defaultReadTimeout = 60 * time.Second defaultWriteTimeout = 60 * time.Second ) type Server struct { addr string ln net.Listener tlsCfg *tls.Config router *mux.Router hs *http.Server authMiddleware mux.MiddlewareFunc } func NewServer(cfg v1.WebServerConfig) (*Server, error) { assets.Load(cfg.AssetsDir) addr := net.JoinHostPort(cfg.Addr, strconv.Itoa(cfg.Port)) if addr == ":" { addr = ":http" } ln, err := net.Listen("tcp", addr) if err != nil { return nil, err } router := mux.NewRouter() hs := &http.Server{ Addr: addr, Handler: router, ReadTimeout: defaultReadTimeout, WriteTimeout: defaultWriteTimeout, } s := &Server{ addr: addr, ln: ln, hs: hs, router: router, } if cfg.PprofEnable { s.registerPprofHandlers() } if cfg.TLS != nil { cert, err := tls.LoadX509KeyPair(cfg.TLS.CertFile, cfg.TLS.KeyFile) if err != nil { return nil, err } s.tlsCfg = &tls.Config{ Certificates: []tls.Certificate{cert}, } } s.authMiddleware = netpkg.NewHTTPAuthMiddleware(cfg.User, cfg.Password).SetAuthFailDelay(200 * time.Millisecond).Middleware return s, nil } func (s *Server) Address() string { return s.addr } func (s *Server) Run() error { ln := s.ln if s.tlsCfg != nil { ln = tls.NewListener(ln, s.tlsCfg) } return s.hs.Serve(ln) } func (s *Server) Close() error { return s.hs.Close() } type RouterRegisterHelper struct { Router *mux.Router AssetsFS http.FileSystem AuthMiddleware mux.MiddlewareFunc } func (s *Server) RouteRegister(register func(helper *RouterRegisterHelper)) { register(&RouterRegisterHelper{ Router: s.router, AssetsFS: assets.FileSystem, AuthMiddleware: s.authMiddleware, }) } func (s *Server) registerPprofHandlers() { s.router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) s.router.HandleFunc("/debug/pprof/profile", pprof.Profile) s.router.HandleFunc("/debug/pprof/symbol", pprof.Symbol) s.router.HandleFunc("/debug/pprof/trace", pprof.Trace) s.router.PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/util/http/http.go
pkg/util/http/http.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package http import ( "encoding/base64" "net" "net/http" "strings" ) func OkResponse() *http.Response { header := make(http.Header) res := &http.Response{ Status: "OK", StatusCode: 200, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: header, } return res } func ProxyUnauthorizedResponse() *http.Response { header := make(http.Header) header.Set("Proxy-Authenticate", `Basic realm="Restricted"`) res := &http.Response{ Status: "Proxy Authentication Required", StatusCode: 407, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: header, } return res } // canonicalHost strips port from host if present and returns the canonicalized // host name. func CanonicalHost(host string) (string, error) { var err error host = strings.ToLower(host) if hasPort(host) { host, _, err = net.SplitHostPort(host) if err != nil { return "", err } } // Strip trailing dot from fully qualified domain names. host = strings.TrimSuffix(host, ".") return host, nil } // hasPort reports whether host contains a port number. host may be a host // name, an IPv4 or an IPv6 address. func hasPort(host string) bool { colons := strings.Count(host, ":") if colons == 0 { return false } if colons == 1 { return true } return host[0] == '[' && strings.Contains(host, "]:") } func ParseBasicAuth(auth string) (username, password string, ok bool) { const prefix = "Basic " // Case insensitive prefix match. See Issue 22736. if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { return } c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) if err != nil { return } cs := string(c) s := strings.IndexByte(cs, ':') if s < 0 { return } return cs[:s], cs[s+1:], true } func BasicAuth(username, passwd string) string { auth := username + ":" + passwd return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/auth/token.go
pkg/auth/token.go
// Copyright 2020 guylewin, guy@lewin.co.il // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package auth import ( "fmt" "slices" "time" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/util/util" ) type TokenAuthSetterVerifier struct { additionalAuthScopes []v1.AuthScope token string } func NewTokenAuth(additionalAuthScopes []v1.AuthScope, token string) *TokenAuthSetterVerifier { return &TokenAuthSetterVerifier{ additionalAuthScopes: additionalAuthScopes, token: token, } } func (auth *TokenAuthSetterVerifier) SetLogin(loginMsg *msg.Login) error { loginMsg.PrivilegeKey = util.GetAuthKey(auth.token, loginMsg.Timestamp) return nil } func (auth *TokenAuthSetterVerifier) SetPing(pingMsg *msg.Ping) error { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { return nil } pingMsg.Timestamp = time.Now().Unix() pingMsg.PrivilegeKey = util.GetAuthKey(auth.token, pingMsg.Timestamp) return nil } func (auth *TokenAuthSetterVerifier) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) error { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { return nil } newWorkConnMsg.Timestamp = time.Now().Unix() newWorkConnMsg.PrivilegeKey = util.GetAuthKey(auth.token, newWorkConnMsg.Timestamp) return nil } func (auth *TokenAuthSetterVerifier) VerifyLogin(m *msg.Login) error { if !util.ConstantTimeEqString(util.GetAuthKey(auth.token, m.Timestamp), m.PrivilegeKey) { return fmt.Errorf("token in login doesn't match token from configuration") } return nil } func (auth *TokenAuthSetterVerifier) VerifyPing(m *msg.Ping) error { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { return nil } if !util.ConstantTimeEqString(util.GetAuthKey(auth.token, m.Timestamp), m.PrivilegeKey) { return fmt.Errorf("token in heartbeat doesn't match token from configuration") } return nil } func (auth *TokenAuthSetterVerifier) VerifyNewWorkConn(m *msg.NewWorkConn) error { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { return nil } if !util.ConstantTimeEqString(util.GetAuthKey(auth.token, m.Timestamp), m.PrivilegeKey) { return fmt.Errorf("token in NewWorkConn doesn't match token from configuration") } return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/auth/oidc.go
pkg/auth/oidc.go
// Copyright 2020 guylewin, guy@lewin.co.il // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package auth import ( "context" "crypto/tls" "crypto/x509" "fmt" "net/http" "net/url" "os" "slices" "github.com/coreos/go-oidc/v3/oidc" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" ) // createOIDCHTTPClient creates an HTTP client with custom TLS and proxy configuration for OIDC token requests func createOIDCHTTPClient(trustedCAFile string, insecureSkipVerify bool, proxyURL string) (*http.Client, error) { // Clone the default transport to get all reasonable defaults transport := http.DefaultTransport.(*http.Transport).Clone() // Configure TLS settings if trustedCAFile != "" || insecureSkipVerify { tlsConfig := &tls.Config{ InsecureSkipVerify: insecureSkipVerify, } if trustedCAFile != "" && !insecureSkipVerify { caCert, err := os.ReadFile(trustedCAFile) if err != nil { return nil, fmt.Errorf("failed to read OIDC CA certificate file %q: %w", trustedCAFile, err) } caCertPool := x509.NewCertPool() if !caCertPool.AppendCertsFromPEM(caCert) { return nil, fmt.Errorf("failed to parse OIDC CA certificate from file %q", trustedCAFile) } tlsConfig.RootCAs = caCertPool } transport.TLSClientConfig = tlsConfig } // Configure proxy settings if proxyURL != "" { parsedURL, err := url.Parse(proxyURL) if err != nil { return nil, fmt.Errorf("failed to parse OIDC proxy URL %q: %w", proxyURL, err) } transport.Proxy = http.ProxyURL(parsedURL) } else { // Explicitly disable proxy to override DefaultTransport's ProxyFromEnvironment transport.Proxy = nil } return &http.Client{Transport: transport}, nil } type OidcAuthProvider struct { additionalAuthScopes []v1.AuthScope tokenGenerator *clientcredentials.Config httpClient *http.Client } func NewOidcAuthSetter(additionalAuthScopes []v1.AuthScope, cfg v1.AuthOIDCClientConfig) (*OidcAuthProvider, error) { eps := make(map[string][]string) for k, v := range cfg.AdditionalEndpointParams { eps[k] = []string{v} } if cfg.Audience != "" { eps["audience"] = []string{cfg.Audience} } tokenGenerator := &clientcredentials.Config{ ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, Scopes: []string{cfg.Scope}, TokenURL: cfg.TokenEndpointURL, EndpointParams: eps, } // Create custom HTTP client if needed var httpClient *http.Client if cfg.TrustedCaFile != "" || cfg.InsecureSkipVerify || cfg.ProxyURL != "" { var err error httpClient, err = createOIDCHTTPClient(cfg.TrustedCaFile, cfg.InsecureSkipVerify, cfg.ProxyURL) if err != nil { return nil, fmt.Errorf("failed to create OIDC HTTP client: %w", err) } } return &OidcAuthProvider{ additionalAuthScopes: additionalAuthScopes, tokenGenerator: tokenGenerator, httpClient: httpClient, }, nil } func (auth *OidcAuthProvider) generateAccessToken() (accessToken string, err error) { ctx := context.Background() if auth.httpClient != nil { ctx = context.WithValue(ctx, oauth2.HTTPClient, auth.httpClient) } tokenObj, err := auth.tokenGenerator.Token(ctx) if err != nil { return "", fmt.Errorf("couldn't generate OIDC token for login: %v", err) } return tokenObj.AccessToken, nil } func (auth *OidcAuthProvider) SetLogin(loginMsg *msg.Login) (err error) { loginMsg.PrivilegeKey, err = auth.generateAccessToken() return err } func (auth *OidcAuthProvider) SetPing(pingMsg *msg.Ping) (err error) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { return nil } pingMsg.PrivilegeKey, err = auth.generateAccessToken() return err } func (auth *OidcAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { return nil } newWorkConnMsg.PrivilegeKey, err = auth.generateAccessToken() return err } type OidcTokenSourceAuthProvider struct { additionalAuthScopes []v1.AuthScope valueSource *v1.ValueSource } func NewOidcTokenSourceAuthSetter(additionalAuthScopes []v1.AuthScope, valueSource *v1.ValueSource) *OidcTokenSourceAuthProvider { return &OidcTokenSourceAuthProvider{ additionalAuthScopes: additionalAuthScopes, valueSource: valueSource, } } func (auth *OidcTokenSourceAuthProvider) generateAccessToken() (accessToken string, err error) { ctx := context.Background() accessToken, err = auth.valueSource.Resolve(ctx) if err != nil { return "", fmt.Errorf("couldn't acquire OIDC token for login: %v", err) } return } func (auth *OidcTokenSourceAuthProvider) SetLogin(loginMsg *msg.Login) (err error) { loginMsg.PrivilegeKey, err = auth.generateAccessToken() return err } func (auth *OidcTokenSourceAuthProvider) SetPing(pingMsg *msg.Ping) (err error) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { return nil } pingMsg.PrivilegeKey, err = auth.generateAccessToken() return err } func (auth *OidcTokenSourceAuthProvider) SetNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { return nil } newWorkConnMsg.PrivilegeKey, err = auth.generateAccessToken() return err } type TokenVerifier interface { Verify(context.Context, string) (*oidc.IDToken, error) } type OidcAuthConsumer struct { additionalAuthScopes []v1.AuthScope verifier TokenVerifier subjectsFromLogin []string } func NewTokenVerifier(cfg v1.AuthOIDCServerConfig) TokenVerifier { provider, err := oidc.NewProvider(context.Background(), cfg.Issuer) if err != nil { panic(err) } verifierConf := oidc.Config{ ClientID: cfg.Audience, SkipClientIDCheck: cfg.Audience == "", SkipExpiryCheck: cfg.SkipExpiryCheck, SkipIssuerCheck: cfg.SkipIssuerCheck, } return provider.Verifier(&verifierConf) } func NewOidcAuthVerifier(additionalAuthScopes []v1.AuthScope, verifier TokenVerifier) *OidcAuthConsumer { return &OidcAuthConsumer{ additionalAuthScopes: additionalAuthScopes, verifier: verifier, subjectsFromLogin: []string{}, } } func (auth *OidcAuthConsumer) VerifyLogin(loginMsg *msg.Login) (err error) { token, err := auth.verifier.Verify(context.Background(), loginMsg.PrivilegeKey) if err != nil { return fmt.Errorf("invalid OIDC token in login: %v", err) } if !slices.Contains(auth.subjectsFromLogin, token.Subject) { auth.subjectsFromLogin = append(auth.subjectsFromLogin, token.Subject) } return nil } func (auth *OidcAuthConsumer) verifyPostLoginToken(privilegeKey string) (err error) { token, err := auth.verifier.Verify(context.Background(), privilegeKey) if err != nil { return fmt.Errorf("invalid OIDC token in ping: %v", err) } if !slices.Contains(auth.subjectsFromLogin, token.Subject) { return fmt.Errorf("received different OIDC subject in login and ping. "+ "original subjects: %s, "+ "new subject: %s", auth.subjectsFromLogin, token.Subject) } return nil } func (auth *OidcAuthConsumer) VerifyPing(pingMsg *msg.Ping) (err error) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeHeartBeats) { return nil } return auth.verifyPostLoginToken(pingMsg.PrivilegeKey) } func (auth *OidcAuthConsumer) VerifyNewWorkConn(newWorkConnMsg *msg.NewWorkConn) (err error) { if !slices.Contains(auth.additionalAuthScopes, v1.AuthScopeNewWorkConns) { return nil } return auth.verifyPostLoginToken(newWorkConnMsg.PrivilegeKey) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/auth/pass.go
pkg/auth/pass.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package auth import ( "github.com/fatedier/frp/pkg/msg" ) var AlwaysPassVerifier = &alwaysPass{} var _ Verifier = &alwaysPass{} type alwaysPass struct{} func (*alwaysPass) VerifyLogin(*msg.Login) error { return nil } func (*alwaysPass) VerifyPing(*msg.Ping) error { return nil } func (*alwaysPass) VerifyNewWorkConn(*msg.NewWorkConn) error { return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/auth/auth.go
pkg/auth/auth.go
// Copyright 2020 guylewin, guy@lewin.co.il // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package auth import ( "context" "fmt" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" ) type Setter interface { SetLogin(*msg.Login) error SetPing(*msg.Ping) error SetNewWorkConn(*msg.NewWorkConn) error } type ClientAuth struct { Setter Setter key []byte } func (a *ClientAuth) EncryptionKey() []byte { return a.key } // BuildClientAuth resolves any dynamic auth values and returns a prepared auth runtime. // Caller must run validation before calling this function. func BuildClientAuth(cfg *v1.AuthClientConfig) (*ClientAuth, error) { if cfg == nil { return nil, fmt.Errorf("auth config is nil") } resolved := *cfg if resolved.Method == v1.AuthMethodToken && resolved.TokenSource != nil { token, err := resolved.TokenSource.Resolve(context.Background()) if err != nil { return nil, fmt.Errorf("failed to resolve auth.tokenSource: %w", err) } resolved.Token = token } setter, err := NewAuthSetter(resolved) if err != nil { return nil, err } return &ClientAuth{ Setter: setter, key: []byte(resolved.Token), }, nil } func NewAuthSetter(cfg v1.AuthClientConfig) (authProvider Setter, err error) { switch cfg.Method { case v1.AuthMethodToken: authProvider = NewTokenAuth(cfg.AdditionalScopes, cfg.Token) case v1.AuthMethodOIDC: if cfg.OIDC.TokenSource != nil { authProvider = NewOidcTokenSourceAuthSetter(cfg.AdditionalScopes, cfg.OIDC.TokenSource) } else { authProvider, err = NewOidcAuthSetter(cfg.AdditionalScopes, cfg.OIDC) if err != nil { return nil, err } } default: return nil, fmt.Errorf("unsupported auth method: %s", cfg.Method) } return authProvider, nil } type Verifier interface { VerifyLogin(*msg.Login) error VerifyPing(*msg.Ping) error VerifyNewWorkConn(*msg.NewWorkConn) error } type ServerAuth struct { Verifier Verifier key []byte } func (a *ServerAuth) EncryptionKey() []byte { return a.key } // BuildServerAuth resolves any dynamic auth values and returns a prepared auth runtime. // Caller must run validation before calling this function. func BuildServerAuth(cfg *v1.AuthServerConfig) (*ServerAuth, error) { if cfg == nil { return nil, fmt.Errorf("auth config is nil") } resolved := *cfg if resolved.Method == v1.AuthMethodToken && resolved.TokenSource != nil { token, err := resolved.TokenSource.Resolve(context.Background()) if err != nil { return nil, fmt.Errorf("failed to resolve auth.tokenSource: %w", err) } resolved.Token = token } return &ServerAuth{ Verifier: NewAuthVerifier(resolved), key: []byte(resolved.Token), }, nil } func NewAuthVerifier(cfg v1.AuthServerConfig) (authVerifier Verifier) { switch cfg.Method { case v1.AuthMethodToken: authVerifier = NewTokenAuth(cfg.AdditionalScopes, cfg.Token) case v1.AuthMethodOIDC: tokenVerifier := NewTokenVerifier(cfg.OIDC) authVerifier = NewOidcAuthVerifier(cfg.AdditionalScopes, tokenVerifier) } return authVerifier }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/auth/oidc_test.go
pkg/auth/oidc_test.go
package auth_test import ( "context" "testing" "time" "github.com/coreos/go-oidc/v3/oidc" "github.com/stretchr/testify/require" "github.com/fatedier/frp/pkg/auth" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" ) type mockTokenVerifier struct{} func (m *mockTokenVerifier) Verify(ctx context.Context, subject string) (*oidc.IDToken, error) { return &oidc.IDToken{ Subject: subject, }, nil } func TestPingWithEmptySubjectFromLoginFails(t *testing.T) { r := require.New(t) consumer := auth.NewOidcAuthVerifier([]v1.AuthScope{v1.AuthScopeHeartBeats}, &mockTokenVerifier{}) err := consumer.VerifyPing(&msg.Ping{ PrivilegeKey: "ping-without-login", Timestamp: time.Now().UnixMilli(), }) r.Error(err) r.Contains(err.Error(), "received different OIDC subject in login and ping") } func TestPingAfterLoginWithNewSubjectSucceeds(t *testing.T) { r := require.New(t) consumer := auth.NewOidcAuthVerifier([]v1.AuthScope{v1.AuthScopeHeartBeats}, &mockTokenVerifier{}) err := consumer.VerifyLogin(&msg.Login{ PrivilegeKey: "ping-after-login", }) r.NoError(err) err = consumer.VerifyPing(&msg.Ping{ PrivilegeKey: "ping-after-login", Timestamp: time.Now().UnixMilli(), }) r.NoError(err) } func TestPingAfterLoginWithDifferentSubjectFails(t *testing.T) { r := require.New(t) consumer := auth.NewOidcAuthVerifier([]v1.AuthScope{v1.AuthScopeHeartBeats}, &mockTokenVerifier{}) err := consumer.VerifyLogin(&msg.Login{ PrivilegeKey: "login-with-first-subject", }) r.NoError(err) err = consumer.VerifyPing(&msg.Ping{ PrivilegeKey: "ping-with-different-subject", Timestamp: time.Now().UnixMilli(), }) r.Error(err) r.Contains(err.Error(), "received different OIDC subject in login and ping") }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/auth/legacy/legacy.go
pkg/auth/legacy/legacy.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package legacy type BaseConfig struct { // AuthenticationMethod specifies what authentication method to use to // authenticate frpc with frps. If "token" is specified - token will be // read into login message. If "oidc" is specified - OIDC (Open ID Connect) // token will be issued using OIDC settings. By default, this value is "token". AuthenticationMethod string `ini:"authentication_method" json:"authentication_method"` // AuthenticateHeartBeats specifies whether to include authentication token in // heartbeats sent to frps. By default, this value is false. AuthenticateHeartBeats bool `ini:"authenticate_heartbeats" json:"authenticate_heartbeats"` // AuthenticateNewWorkConns specifies whether to include authentication token in // new work connections sent to frps. By default, this value is false. AuthenticateNewWorkConns bool `ini:"authenticate_new_work_conns" json:"authenticate_new_work_conns"` } func getDefaultBaseConf() BaseConfig { return BaseConfig{ AuthenticationMethod: "token", AuthenticateHeartBeats: false, AuthenticateNewWorkConns: false, } } type ClientConfig struct { BaseConfig `ini:",extends"` OidcClientConfig `ini:",extends"` TokenConfig `ini:",extends"` } func GetDefaultClientConf() ClientConfig { return ClientConfig{ BaseConfig: getDefaultBaseConf(), OidcClientConfig: getDefaultOidcClientConf(), TokenConfig: getDefaultTokenConf(), } } type ServerConfig struct { BaseConfig `ini:",extends"` OidcServerConfig `ini:",extends"` TokenConfig `ini:",extends"` } func GetDefaultServerConf() ServerConfig { return ServerConfig{ BaseConfig: getDefaultBaseConf(), OidcServerConfig: getDefaultOidcServerConf(), TokenConfig: getDefaultTokenConf(), } } type OidcClientConfig struct { // OidcClientID specifies the client ID to use to get a token in OIDC // authentication if AuthenticationMethod == "oidc". By default, this value // is "". OidcClientID string `ini:"oidc_client_id" json:"oidc_client_id"` // OidcClientSecret specifies the client secret to use to get a token in OIDC // authentication if AuthenticationMethod == "oidc". By default, this value // is "". OidcClientSecret string `ini:"oidc_client_secret" json:"oidc_client_secret"` // OidcAudience specifies the audience of the token in OIDC authentication // if AuthenticationMethod == "oidc". By default, this value is "". OidcAudience string `ini:"oidc_audience" json:"oidc_audience"` // OidcScope specifies the scope of the token in OIDC authentication // if AuthenticationMethod == "oidc". By default, this value is "". OidcScope string `ini:"oidc_scope" json:"oidc_scope"` // OidcTokenEndpointURL specifies the URL which implements OIDC Token Endpoint. // It will be used to get an OIDC token if AuthenticationMethod == "oidc". // By default, this value is "". OidcTokenEndpointURL string `ini:"oidc_token_endpoint_url" json:"oidc_token_endpoint_url"` // OidcAdditionalEndpointParams specifies additional parameters to be sent // this field will be transfer to map[string][]string in OIDC token generator // The field will be set by prefix "oidc_additional_" OidcAdditionalEndpointParams map[string]string `ini:"-" json:"oidc_additional_endpoint_params"` } func getDefaultOidcClientConf() OidcClientConfig { return OidcClientConfig{ OidcClientID: "", OidcClientSecret: "", OidcAudience: "", OidcScope: "", OidcTokenEndpointURL: "", OidcAdditionalEndpointParams: make(map[string]string), } } type OidcServerConfig struct { // OidcIssuer specifies the issuer to verify OIDC tokens with. This issuer // will be used to load public keys to verify signature and will be compared // with the issuer claim in the OIDC token. It will be used if // AuthenticationMethod == "oidc". By default, this value is "". OidcIssuer string `ini:"oidc_issuer" json:"oidc_issuer"` // OidcAudience specifies the audience OIDC tokens should contain when validated. // If this value is empty, audience ("client ID") verification will be skipped. // It will be used when AuthenticationMethod == "oidc". By default, this // value is "". OidcAudience string `ini:"oidc_audience" json:"oidc_audience"` // OidcSkipExpiryCheck specifies whether to skip checking if the OIDC token is // expired. It will be used when AuthenticationMethod == "oidc". By default, this // value is false. OidcSkipExpiryCheck bool `ini:"oidc_skip_expiry_check" json:"oidc_skip_expiry_check"` // OidcSkipIssuerCheck specifies whether to skip checking if the OIDC token's // issuer claim matches the issuer specified in OidcIssuer. It will be used when // AuthenticationMethod == "oidc". By default, this value is false. OidcSkipIssuerCheck bool `ini:"oidc_skip_issuer_check" json:"oidc_skip_issuer_check"` } func getDefaultOidcServerConf() OidcServerConfig { return OidcServerConfig{ OidcIssuer: "", OidcAudience: "", OidcSkipExpiryCheck: false, OidcSkipIssuerCheck: false, } } type TokenConfig struct { // Token specifies the authorization token used to create keys to be sent // to the server. The server must have a matching token for authorization // to succeed. By default, this value is "". Token string `ini:"token" json:"token"` } func getDefaultTokenConf() TokenConfig { return TokenConfig{ Token: "", } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/visitor/virtual_net.go
pkg/plugin/visitor/virtual_net.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package visitor import ( "context" "errors" "fmt" "net" "sync" "time" v1 "github.com/fatedier/frp/pkg/config/v1" netutil "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" ) func init() { Register(v1.VisitorPluginVirtualNet, NewVirtualNetPlugin) } type VirtualNetPlugin struct { pluginCtx PluginContext routes []net.IPNet mu sync.Mutex controllerConn net.Conn closeSignal chan struct{} consecutiveErrors int // Tracks consecutive connection errors for exponential backoff ctx context.Context cancel context.CancelFunc } func NewVirtualNetPlugin(pluginCtx PluginContext, options v1.VisitorPluginOptions) (Plugin, error) { opts := options.(*v1.VirtualNetVisitorPluginOptions) p := &VirtualNetPlugin{ pluginCtx: pluginCtx, routes: make([]net.IPNet, 0), } p.ctx, p.cancel = context.WithCancel(pluginCtx.Ctx) if opts.DestinationIP == "" { return nil, errors.New("destinationIP is required") } // Parse DestinationIP and create a host route. ip := net.ParseIP(opts.DestinationIP) if ip == nil { return nil, fmt.Errorf("invalid destination IP address [%s]", opts.DestinationIP) } var mask net.IPMask if ip.To4() != nil { mask = net.CIDRMask(32, 32) // /32 for IPv4 } else { mask = net.CIDRMask(128, 128) // /128 for IPv6 } p.routes = append(p.routes, net.IPNet{IP: ip, Mask: mask}) return p, nil } func (p *VirtualNetPlugin) Name() string { return v1.VisitorPluginVirtualNet } func (p *VirtualNetPlugin) Start() { xl := xlog.FromContextSafe(p.pluginCtx.Ctx) if p.pluginCtx.VnetController == nil { return } routeStr := "unknown" if len(p.routes) > 0 { routeStr = p.routes[0].String() } xl.Infof("starting VirtualNetPlugin for visitor [%s], attempting to register routes for %s", p.pluginCtx.Name, routeStr) go p.run() } func (p *VirtualNetPlugin) run() { xl := xlog.FromContextSafe(p.ctx) for { currentCloseSignal := make(chan struct{}) p.mu.Lock() p.closeSignal = currentCloseSignal p.mu.Unlock() select { case <-p.ctx.Done(): xl.Infof("VirtualNetPlugin run loop for visitor [%s] stopping (context cancelled before pipe creation).", p.pluginCtx.Name) p.cleanupControllerConn(xl) return default: } controllerConn, pluginConn := net.Pipe() p.mu.Lock() p.controllerConn = controllerConn p.mu.Unlock() // Wrap with CloseNotifyConn which supports both close notification and error recording var closeErr error pluginNotifyConn := netutil.WrapCloseNotifyConn(pluginConn, func(err error) { closeErr = err close(currentCloseSignal) // Signal the run loop on close. }) xl.Infof("attempting to register client route for visitor [%s]", p.pluginCtx.Name) p.pluginCtx.VnetController.RegisterClientRoute(p.ctx, p.pluginCtx.Name, p.routes, controllerConn) xl.Infof("successfully registered client route for visitor [%s]. Starting connection handler with CloseNotifyConn.", p.pluginCtx.Name) // Pass the CloseNotifyConn to the visitor for handling. // The visitor can call CloseWithError to record the failure reason. p.pluginCtx.SendConnToVisitor(pluginNotifyConn) // Wait for context cancellation or connection close. select { case <-p.ctx.Done(): xl.Infof("VirtualNetPlugin run loop stopping for visitor [%s] (context cancelled while waiting).", p.pluginCtx.Name) p.cleanupControllerConn(xl) return case <-currentCloseSignal: // Determine reconnect delay based on error with exponential backoff var reconnectDelay time.Duration if closeErr != nil { p.consecutiveErrors++ xl.Warnf("connection closed with error for visitor [%s] (consecutive errors: %d): %v", p.pluginCtx.Name, p.consecutiveErrors, closeErr) // Exponential backoff: 60s, 120s, 240s, 300s (capped) baseDelay := 60 * time.Second reconnectDelay = baseDelay * time.Duration(1<<uint(p.consecutiveErrors-1)) if reconnectDelay > 300*time.Second { reconnectDelay = 300 * time.Second } } else { // Reset consecutive errors on successful connection if p.consecutiveErrors > 0 { xl.Infof("connection closed normally for visitor [%s], resetting error counter (was %d)", p.pluginCtx.Name, p.consecutiveErrors) p.consecutiveErrors = 0 } else { xl.Infof("connection closed normally for visitor [%s]", p.pluginCtx.Name) } reconnectDelay = 10 * time.Second } // The visitor closed the plugin side. Close the controller side. p.cleanupControllerConn(xl) xl.Infof("waiting %v before attempting reconnection for visitor [%s]...", reconnectDelay, p.pluginCtx.Name) select { case <-time.After(reconnectDelay): case <-p.ctx.Done(): xl.Infof("VirtualNetPlugin reconnection delay interrupted for visitor [%s]", p.pluginCtx.Name) return } } xl.Infof("re-establishing virtual connection for visitor [%s]...", p.pluginCtx.Name) } } // cleanupControllerConn closes the current controllerConn (if it exists) under lock. func (p *VirtualNetPlugin) cleanupControllerConn(xl *xlog.Logger) { p.mu.Lock() defer p.mu.Unlock() if p.controllerConn != nil { xl.Debugf("cleaning up controllerConn for visitor [%s]", p.pluginCtx.Name) p.controllerConn.Close() p.controllerConn = nil } p.closeSignal = nil } // Close initiates the plugin shutdown. func (p *VirtualNetPlugin) Close() error { xl := xlog.FromContextSafe(p.pluginCtx.Ctx) xl.Infof("closing VirtualNetPlugin for visitor [%s]", p.pluginCtx.Name) // Signal the run loop goroutine to stop. p.cancel() // Unregister the route from the controller. if p.pluginCtx.VnetController != nil { p.pluginCtx.VnetController.UnregisterClientRoute(p.pluginCtx.Name) xl.Infof("unregistered client route for visitor [%s]", p.pluginCtx.Name) } // Explicitly close the controller side of the pipe. // This ensures the pipe is broken even if the run loop is stuck or the visitor hasn't closed its end. p.cleanupControllerConn(xl) xl.Infof("finished cleaning up connections during close for visitor [%s]", p.pluginCtx.Name) return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/visitor/plugin.go
pkg/plugin/visitor/plugin.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package visitor import ( "context" "fmt" "net" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/vnet" ) // PluginContext provides the necessary context and callbacks for visitor plugins. type PluginContext struct { // Name is the unique identifier for this visitor, used for logging and routing. Name string // Ctx manages the plugin's lifecycle and carries the logger for structured logging. Ctx context.Context // VnetController manages TUN device routing. May be nil if virtual networking is disabled. VnetController *vnet.Controller // SendConnToVisitor sends a connection to the visitor's internal processing queue. // Does not return error; failures are handled by closing the connection. SendConnToVisitor func(net.Conn) } // Creators is used for create plugins to handle connections. var creators = make(map[string]CreatorFn) type CreatorFn func(pluginCtx PluginContext, options v1.VisitorPluginOptions) (Plugin, error) func Register(name string, fn CreatorFn) { if _, exist := creators[name]; exist { panic(fmt.Sprintf("plugin [%s] is already registered", name)) } creators[name] = fn } func Create(pluginName string, pluginCtx PluginContext, options v1.VisitorPluginOptions) (p Plugin, err error) { if fn, ok := creators[pluginName]; ok { p, err = fn(pluginCtx, options) } else { err = fmt.Errorf("plugin [%s] is not registered", pluginName) } return } type Plugin interface { Name() string Start() Close() error }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/server/tracer.go
pkg/plugin/server/tracer.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" ) type key int const ( reqidKey key = 0 ) func NewReqidContext(ctx context.Context, reqid string) context.Context { return context.WithValue(ctx, reqidKey, reqid) } func GetReqidFromContext(ctx context.Context) string { ret, _ := ctx.Value(reqidKey).(string) return ret }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/server/types.go
pkg/plugin/server/types.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "github.com/fatedier/frp/pkg/msg" ) type Request struct { Version string `json:"version"` Op string `json:"op"` Content any `json:"content"` } type Response struct { Reject bool `json:"reject"` RejectReason string `json:"reject_reason"` Unchange bool `json:"unchange"` Content any `json:"content"` } type LoginContent struct { msg.Login ClientAddress string `json:"client_address,omitempty"` } type UserInfo struct { User string `json:"user"` Metas map[string]string `json:"metas"` RunID string `json:"run_id"` } type NewProxyContent struct { User UserInfo `json:"user"` msg.NewProxy } type CloseProxyContent struct { User UserInfo `json:"user"` msg.CloseProxy } type PingContent struct { User UserInfo `json:"user"` msg.Ping } type NewWorkConnContent struct { User UserInfo `json:"user"` msg.NewWorkConn } type NewUserConnContent struct { User UserInfo `json:"user"` ProxyName string `json:"proxy_name"` ProxyType string `json:"proxy_type"` RemoteAddr string `json:"remote_addr"` }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/server/http.go
pkg/plugin/server/http.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "bytes" "context" "crypto/tls" "encoding/json" "fmt" "io" "net/http" "net/url" "reflect" "strings" v1 "github.com/fatedier/frp/pkg/config/v1" ) type httpPlugin struct { options v1.HTTPPluginOptions url string client *http.Client } func NewHTTPPluginOptions(options v1.HTTPPluginOptions) Plugin { url := fmt.Sprintf("%s%s", options.Addr, options.Path) var client *http.Client if strings.HasPrefix(url, "https://") { tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: !options.TLSVerify}, } client = &http.Client{Transport: tr} } else { client = &http.Client{} } if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") { url = "http://" + url } return &httpPlugin{ options: options, url: url, client: client, } } func (p *httpPlugin) Name() string { return p.options.Name } func (p *httpPlugin) IsSupport(op string) bool { for _, v := range p.options.Ops { if v == op { return true } } return false } func (p *httpPlugin) Handle(ctx context.Context, op string, content any) (*Response, any, error) { r := &Request{ Version: APIVersion, Op: op, Content: content, } var res Response res.Content = reflect.New(reflect.TypeOf(content)).Interface() if err := p.do(ctx, r, &res); err != nil { return nil, nil, err } return &res, res.Content, nil } func (p *httpPlugin) do(ctx context.Context, r *Request, res *Response) error { buf, err := json.Marshal(r) if err != nil { return err } v := url.Values{} v.Set("version", r.Version) v.Set("op", r.Op) req, err := http.NewRequest("POST", p.url+"?"+v.Encode(), bytes.NewReader(buf)) if err != nil { return err } req = req.WithContext(ctx) req.Header.Set("X-Frp-Reqid", GetReqidFromContext(ctx)) req.Header.Set("Content-Type", "application/json") resp, err := p.client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("do http request error code: %d", resp.StatusCode) } buf, err = io.ReadAll(resp.Body) if err != nil { return err } return json.Unmarshal(buf, res) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/server/plugin.go
pkg/plugin/server/plugin.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" ) const ( APIVersion = "0.1.0" OpLogin = "Login" OpNewProxy = "NewProxy" OpCloseProxy = "CloseProxy" OpPing = "Ping" OpNewWorkConn = "NewWorkConn" OpNewUserConn = "NewUserConn" ) type Plugin interface { Name() string IsSupport(op string) bool Handle(ctx context.Context, op string, content any) (res *Response, retContent any, err error) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/server/manager.go
pkg/plugin/server/manager.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "errors" "fmt" "strings" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/xlog" ) type Manager struct { loginPlugins []Plugin newProxyPlugins []Plugin closeProxyPlugins []Plugin pingPlugins []Plugin newWorkConnPlugins []Plugin newUserConnPlugins []Plugin } func NewManager() *Manager { return &Manager{ loginPlugins: make([]Plugin, 0), newProxyPlugins: make([]Plugin, 0), closeProxyPlugins: make([]Plugin, 0), pingPlugins: make([]Plugin, 0), newWorkConnPlugins: make([]Plugin, 0), newUserConnPlugins: make([]Plugin, 0), } } func (m *Manager) Register(p Plugin) { if p.IsSupport(OpLogin) { m.loginPlugins = append(m.loginPlugins, p) } if p.IsSupport(OpNewProxy) { m.newProxyPlugins = append(m.newProxyPlugins, p) } if p.IsSupport(OpCloseProxy) { m.closeProxyPlugins = append(m.closeProxyPlugins, p) } if p.IsSupport(OpPing) { m.pingPlugins = append(m.pingPlugins, p) } if p.IsSupport(OpNewWorkConn) { m.newWorkConnPlugins = append(m.newWorkConnPlugins, p) } if p.IsSupport(OpNewUserConn) { m.newUserConnPlugins = append(m.newUserConnPlugins, p) } } func (m *Manager) Login(content *LoginContent) (*LoginContent, error) { if len(m.loginPlugins) == 0 { return content, nil } var ( res = &Response{ Reject: false, Unchange: true, } retContent any err error ) reqid, _ := util.RandID() xl := xlog.New().AppendPrefix("reqid: " + reqid) ctx := xlog.NewContext(context.Background(), xl) ctx = NewReqidContext(ctx, reqid) for _, p := range m.loginPlugins { res, retContent, err = p.Handle(ctx, OpLogin, *content) if err != nil { xl.Warnf("send Login request to plugin [%s] error: %v", p.Name(), err) return nil, errors.New("send Login request to plugin error") } if res.Reject { return nil, fmt.Errorf("%s", res.RejectReason) } if !res.Unchange { content = retContent.(*LoginContent) } } return content, nil } func (m *Manager) NewProxy(content *NewProxyContent) (*NewProxyContent, error) { if len(m.newProxyPlugins) == 0 { return content, nil } var ( res = &Response{ Reject: false, Unchange: true, } retContent any err error ) reqid, _ := util.RandID() xl := xlog.New().AppendPrefix("reqid: " + reqid) ctx := xlog.NewContext(context.Background(), xl) ctx = NewReqidContext(ctx, reqid) for _, p := range m.newProxyPlugins { res, retContent, err = p.Handle(ctx, OpNewProxy, *content) if err != nil { xl.Warnf("send NewProxy request to plugin [%s] error: %v", p.Name(), err) return nil, errors.New("send NewProxy request to plugin error") } if res.Reject { return nil, fmt.Errorf("%s", res.RejectReason) } if !res.Unchange { content = retContent.(*NewProxyContent) } } return content, nil } func (m *Manager) CloseProxy(content *CloseProxyContent) error { if len(m.closeProxyPlugins) == 0 { return nil } errs := make([]string, 0) reqid, _ := util.RandID() xl := xlog.New().AppendPrefix("reqid: " + reqid) ctx := xlog.NewContext(context.Background(), xl) ctx = NewReqidContext(ctx, reqid) for _, p := range m.closeProxyPlugins { _, _, err := p.Handle(ctx, OpCloseProxy, *content) if err != nil { xl.Warnf("send CloseProxy request to plugin [%s] error: %v", p.Name(), err) errs = append(errs, fmt.Sprintf("[%s]: %v", p.Name(), err)) } } if len(errs) > 0 { return fmt.Errorf("send CloseProxy request to plugin errors: %s", strings.Join(errs, "; ")) } return nil } func (m *Manager) Ping(content *PingContent) (*PingContent, error) { if len(m.pingPlugins) == 0 { return content, nil } var ( res = &Response{ Reject: false, Unchange: true, } retContent any err error ) reqid, _ := util.RandID() xl := xlog.New().AppendPrefix("reqid: " + reqid) ctx := xlog.NewContext(context.Background(), xl) ctx = NewReqidContext(ctx, reqid) for _, p := range m.pingPlugins { res, retContent, err = p.Handle(ctx, OpPing, *content) if err != nil { xl.Warnf("send Ping request to plugin [%s] error: %v", p.Name(), err) return nil, errors.New("send Ping request to plugin error") } if res.Reject { return nil, fmt.Errorf("%s", res.RejectReason) } if !res.Unchange { content = retContent.(*PingContent) } } return content, nil } func (m *Manager) NewWorkConn(content *NewWorkConnContent) (*NewWorkConnContent, error) { if len(m.newWorkConnPlugins) == 0 { return content, nil } var ( res = &Response{ Reject: false, Unchange: true, } retContent any err error ) reqid, _ := util.RandID() xl := xlog.New().AppendPrefix("reqid: " + reqid) ctx := xlog.NewContext(context.Background(), xl) ctx = NewReqidContext(ctx, reqid) for _, p := range m.newWorkConnPlugins { res, retContent, err = p.Handle(ctx, OpNewWorkConn, *content) if err != nil { xl.Warnf("send NewWorkConn request to plugin [%s] error: %v", p.Name(), err) return nil, errors.New("send NewWorkConn request to plugin error") } if res.Reject { return nil, fmt.Errorf("%s", res.RejectReason) } if !res.Unchange { content = retContent.(*NewWorkConnContent) } } return content, nil } func (m *Manager) NewUserConn(content *NewUserConnContent) (*NewUserConnContent, error) { if len(m.newUserConnPlugins) == 0 { return content, nil } var ( res = &Response{ Reject: false, Unchange: true, } retContent any err error ) reqid, _ := util.RandID() xl := xlog.New().AppendPrefix("reqid: " + reqid) ctx := xlog.NewContext(context.Background(), xl) ctx = NewReqidContext(ctx, reqid) for _, p := range m.newUserConnPlugins { res, retContent, err = p.Handle(ctx, OpNewUserConn, *content) if err != nil { xl.Infof("send NewUserConn request to plugin [%s] error: %v", p.Name(), err) return nil, errors.New("send NewUserConn request to plugin error") } if res.Reject { return nil, fmt.Errorf("%s", res.RejectReason) } if !res.Unchange { content = retContent.(*NewUserConnContent) } } return content, nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/tls2raw.go
pkg/plugin/client/tls2raw.go
// Copyright 2024 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "crypto/tls" "net" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/transport" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/xlog" ) func init() { Register(v1.PluginTLS2Raw, NewTLS2RawPlugin) } type TLS2RawPlugin struct { opts *v1.TLS2RawPluginOptions tlsConfig *tls.Config } func NewTLS2RawPlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.TLS2RawPluginOptions) p := &TLS2RawPlugin{ opts: opts, } tlsConfig, err := transport.NewServerTLSConfig(p.opts.CrtPath, p.opts.KeyPath, "") if err != nil { return nil, err } p.tlsConfig = tlsConfig return p, nil } func (p *TLS2RawPlugin) Handle(ctx context.Context, connInfo *ConnectionInfo) { xl := xlog.FromContextSafe(ctx) wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) tlsConn := tls.Server(wrapConn, p.tlsConfig) if err := tlsConn.Handshake(); err != nil { xl.Warnf("tls handshake error: %v", err) return } rawConn, err := net.Dial("tcp", p.opts.LocalAddr) if err != nil { xl.Warnf("dial to local addr error: %v", err) return } libio.Join(tlsConn, rawConn) } func (p *TLS2RawPlugin) Name() string { return v1.PluginTLS2Raw } func (p *TLS2RawPlugin) Close() error { return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/https2http.go
pkg/plugin/client/https2http.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "crypto/tls" "fmt" stdlog "log" "net/http" "net/http/httputil" "time" "github.com/fatedier/golib/pool" "github.com/samber/lo" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/transport" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { Register(v1.PluginHTTPS2HTTP, NewHTTPS2HTTPPlugin) } type HTTPS2HTTPPlugin struct { opts *v1.HTTPS2HTTPPluginOptions l *Listener s *http.Server } func NewHTTPS2HTTPPlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.HTTPS2HTTPPluginOptions) listener := NewProxyListener() p := &HTTPS2HTTPPlugin{ opts: opts, l: listener, } rp := &httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"] r.SetXForwarded() req := r.Out req.URL.Scheme = "http" req.URL.Host = p.opts.LocalAddr if p.opts.HostHeaderRewrite != "" { req.Host = p.opts.HostHeaderRewrite } for k, v := range p.opts.RequestHeaders.Set { req.Header.Set(k, v) } }, BufferPool: pool.NewBuffer(32 * 1024), ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0), } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.TLS != nil { tlsServerName, _ := httppkg.CanonicalHost(r.TLS.ServerName) host, _ := httppkg.CanonicalHost(r.Host) if tlsServerName != "" && tlsServerName != host { w.WriteHeader(http.StatusMisdirectedRequest) return } } rp.ServeHTTP(w, r) }) tlsConfig, err := transport.NewServerTLSConfig(p.opts.CrtPath, p.opts.KeyPath, "") if err != nil { return nil, fmt.Errorf("gen TLS config error: %v", err) } p.s = &http.Server{ Handler: handler, ReadHeaderTimeout: 60 * time.Second, TLSConfig: tlsConfig, } if !lo.FromPtr(opts.EnableHTTP2) { p.s.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler)) } go func() { _ = p.s.ServeTLS(listener, "", "") }() return p, nil } func (p *HTTPS2HTTPPlugin) Handle(_ context.Context, connInfo *ConnectionInfo) { wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) if connInfo.SrcAddr != nil { wrapConn.SetRemoteAddr(connInfo.SrcAddr) } _ = p.l.PutConn(wrapConn) } func (p *HTTPS2HTTPPlugin) Name() string { return v1.PluginHTTPS2HTTP } func (p *HTTPS2HTTPPlugin) Close() error { return p.s.Close() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/unix_domain_socket.go
pkg/plugin/client/unix_domain_socket.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "net" libio "github.com/fatedier/golib/io" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/xlog" ) func init() { Register(v1.PluginUnixDomainSocket, NewUnixDomainSocketPlugin) } type UnixDomainSocketPlugin struct { UnixAddr *net.UnixAddr } func NewUnixDomainSocketPlugin(_ PluginContext, options v1.ClientPluginOptions) (p Plugin, err error) { opts := options.(*v1.UnixDomainSocketPluginOptions) unixAddr, errRet := net.ResolveUnixAddr("unix", opts.UnixPath) if errRet != nil { err = errRet return } p = &UnixDomainSocketPlugin{ UnixAddr: unixAddr, } return } func (uds *UnixDomainSocketPlugin) Handle(ctx context.Context, connInfo *ConnectionInfo) { xl := xlog.FromContextSafe(ctx) localConn, err := net.DialUnix("unix", nil, uds.UnixAddr) if err != nil { xl.Warnf("dial to uds %s error: %v", uds.UnixAddr, err) return } if connInfo.ProxyProtocolHeader != nil { if _, err := connInfo.ProxyProtocolHeader.WriteTo(localConn); err != nil { return } } libio.Join(localConn, connInfo.Conn) } func (uds *UnixDomainSocketPlugin) Name() string { return v1.PluginUnixDomainSocket } func (uds *UnixDomainSocketPlugin) Close() error { return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/static_file.go
pkg/plugin/client/static_file.go
// Copyright 2018 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "net/http" "time" "github.com/gorilla/mux" v1 "github.com/fatedier/frp/pkg/config/v1" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { Register(v1.PluginStaticFile, NewStaticFilePlugin) } type StaticFilePlugin struct { opts *v1.StaticFilePluginOptions l *Listener s *http.Server } func NewStaticFilePlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.StaticFilePluginOptions) listener := NewProxyListener() sp := &StaticFilePlugin{ opts: opts, l: listener, } var prefix string if opts.StripPrefix != "" { prefix = "/" + opts.StripPrefix + "/" } else { prefix = "/" } router := mux.NewRouter() router.Use(netpkg.NewHTTPAuthMiddleware(opts.HTTPUser, opts.HTTPPassword).SetAuthFailDelay(200 * time.Millisecond).Middleware) router.PathPrefix(prefix).Handler(netpkg.MakeHTTPGzipHandler(http.StripPrefix(prefix, http.FileServer(http.Dir(opts.LocalPath))))).Methods("GET") sp.s = &http.Server{ Handler: router, ReadHeaderTimeout: 60 * time.Second, } go func() { _ = sp.s.Serve(listener) }() return sp, nil } func (sp *StaticFilePlugin) Handle(_ context.Context, connInfo *ConnectionInfo) { wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) _ = sp.l.PutConn(wrapConn) } func (sp *StaticFilePlugin) Name() string { return v1.PluginStaticFile } func (sp *StaticFilePlugin) Close() error { sp.s.Close() sp.l.Close() return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/http_proxy.go
pkg/plugin/client/http_proxy.go
// Copyright 2017 frp team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "bufio" "context" "encoding/base64" "io" "net" "net/http" "strings" "time" libio "github.com/fatedier/golib/io" libnet "github.com/fatedier/golib/net" v1 "github.com/fatedier/frp/pkg/config/v1" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" ) func init() { Register(v1.PluginHTTPProxy, NewHTTPProxyPlugin) } type HTTPProxy struct { opts *v1.HTTPProxyPluginOptions l *Listener s *http.Server } func NewHTTPProxyPlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.HTTPProxyPluginOptions) listener := NewProxyListener() hp := &HTTPProxy{ l: listener, opts: opts, } hp.s = &http.Server{ Handler: hp, ReadHeaderTimeout: 60 * time.Second, } go func() { _ = hp.s.Serve(listener) }() return hp, nil } func (hp *HTTPProxy) Name() string { return v1.PluginHTTPProxy } func (hp *HTTPProxy) Handle(_ context.Context, connInfo *ConnectionInfo) { wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) sc, rd := libnet.NewSharedConn(wrapConn) firstBytes := make([]byte, 7) _, err := rd.Read(firstBytes) if err != nil { wrapConn.Close() return } if strings.ToUpper(string(firstBytes)) == "CONNECT" { bufRd := bufio.NewReader(sc) request, err := http.ReadRequest(bufRd) if err != nil { wrapConn.Close() return } hp.handleConnectReq(request, libio.WrapReadWriteCloser(bufRd, wrapConn, wrapConn.Close)) return } _ = hp.l.PutConn(sc) } func (hp *HTTPProxy) Close() error { hp.s.Close() hp.l.Close() return nil } func (hp *HTTPProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if ok := hp.Auth(req); !ok { rw.Header().Set("Proxy-Authenticate", "Basic") rw.WriteHeader(http.StatusProxyAuthRequired) return } if req.Method == http.MethodConnect { // deprecated // Connect request is handled in Handle function. hp.ConnectHandler(rw, req) } else { hp.HTTPHandler(rw, req) } } func (hp *HTTPProxy) HTTPHandler(rw http.ResponseWriter, req *http.Request) { removeProxyHeaders(req) resp, err := http.DefaultTransport.RoundTrip(req) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } defer resp.Body.Close() copyHeaders(rw.Header(), resp.Header) rw.WriteHeader(resp.StatusCode) _, err = io.Copy(rw, resp.Body) if err != nil && err != io.EOF { return } } // deprecated // Hijack needs to SetReadDeadline on the Conn of the request, but if we use stream compression here, // we may always get i/o timeout error. func (hp *HTTPProxy) ConnectHandler(rw http.ResponseWriter, req *http.Request) { hj, ok := rw.(http.Hijacker) if !ok { rw.WriteHeader(http.StatusInternalServerError) return } client, _, err := hj.Hijack() if err != nil { rw.WriteHeader(http.StatusInternalServerError) return } remote, err := net.Dial("tcp", req.URL.Host) if err != nil { http.Error(rw, "Failed", http.StatusBadRequest) client.Close() return } _, _ = client.Write([]byte("HTTP/1.1 200 OK\r\n\r\n")) go libio.Join(remote, client) } func (hp *HTTPProxy) Auth(req *http.Request) bool { if hp.opts.HTTPUser == "" && hp.opts.HTTPPassword == "" { return true } s := strings.SplitN(req.Header.Get("Proxy-Authorization"), " ", 2) if len(s) != 2 { return false } b, err := base64.StdEncoding.DecodeString(s[1]) if err != nil { return false } pair := strings.SplitN(string(b), ":", 2) if len(pair) != 2 { return false } if !util.ConstantTimeEqString(pair[0], hp.opts.HTTPUser) || !util.ConstantTimeEqString(pair[1], hp.opts.HTTPPassword) { time.Sleep(200 * time.Millisecond) return false } return true } func (hp *HTTPProxy) handleConnectReq(req *http.Request, rwc io.ReadWriteCloser) { defer rwc.Close() if ok := hp.Auth(req); !ok { res := getBadResponse() _ = res.Write(rwc) if res.Body != nil { res.Body.Close() } return } remote, err := net.Dial("tcp", req.URL.Host) if err != nil { res := &http.Response{ StatusCode: 400, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, } _ = res.Write(rwc) return } _, _ = rwc.Write([]byte("HTTP/1.1 200 OK\r\n\r\n")) libio.Join(remote, rwc) } func copyHeaders(dst, src http.Header) { for key, values := range src { for _, value := range values { dst.Add(key, value) } } } func removeProxyHeaders(req *http.Request) { req.RequestURI = "" req.Header.Del("Proxy-Connection") req.Header.Del("Connection") req.Header.Del("Proxy-Authenticate") req.Header.Del("Proxy-Authorization") req.Header.Del("TE") req.Header.Del("Trailers") req.Header.Del("Transfer-Encoding") req.Header.Del("Upgrade") } func getBadResponse() *http.Response { header := make(map[string][]string) header["Proxy-Authenticate"] = []string{"Basic"} header["Connection"] = []string{"close"} res := &http.Response{ Status: "407 Not authorized", StatusCode: 407, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: header, } return res }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/http2https.go
pkg/plugin/client/http2https.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "crypto/tls" stdlog "log" "net/http" "net/http/httputil" "github.com/fatedier/golib/pool" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { Register(v1.PluginHTTP2HTTPS, NewHTTP2HTTPSPlugin) } type HTTP2HTTPSPlugin struct { opts *v1.HTTP2HTTPSPluginOptions l *Listener s *http.Server } func NewHTTP2HTTPSPlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.HTTP2HTTPSPluginOptions) listener := NewProxyListener() p := &HTTP2HTTPSPlugin{ opts: opts, l: listener, } tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } rp := &httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"] r.Out.Header["X-Forwarded-Host"] = r.In.Header["X-Forwarded-Host"] r.Out.Header["X-Forwarded-Proto"] = r.In.Header["X-Forwarded-Proto"] req := r.Out req.URL.Scheme = "https" req.URL.Host = p.opts.LocalAddr if p.opts.HostHeaderRewrite != "" { req.Host = p.opts.HostHeaderRewrite } for k, v := range p.opts.RequestHeaders.Set { req.Header.Set(k, v) } }, Transport: tr, BufferPool: pool.NewBuffer(32 * 1024), ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0), } p.s = &http.Server{ Handler: rp, ReadHeaderTimeout: 0, } go func() { _ = p.s.Serve(listener) }() return p, nil } func (p *HTTP2HTTPSPlugin) Handle(_ context.Context, connInfo *ConnectionInfo) { wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) _ = p.l.PutConn(wrapConn) } func (p *HTTP2HTTPSPlugin) Name() string { return v1.PluginHTTP2HTTPS } func (p *HTTP2HTTPSPlugin) Close() error { return p.s.Close() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/virtual_net.go
pkg/plugin/client/virtual_net.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "io" "sync" v1 "github.com/fatedier/frp/pkg/config/v1" ) func init() { Register(v1.PluginVirtualNet, NewVirtualNetPlugin) } type VirtualNetPlugin struct { pluginCtx PluginContext opts *v1.VirtualNetPluginOptions mu sync.Mutex conns map[io.ReadWriteCloser]struct{} } func NewVirtualNetPlugin(pluginCtx PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.VirtualNetPluginOptions) p := &VirtualNetPlugin{ pluginCtx: pluginCtx, opts: opts, } return p, nil } func (p *VirtualNetPlugin) Handle(ctx context.Context, connInfo *ConnectionInfo) { // Verify if virtual network controller is available if p.pluginCtx.VnetController == nil { return } // Add the connection before starting the read loop to avoid race condition // where RemoveConn might be called before the connection is added. p.mu.Lock() if p.conns == nil { p.conns = make(map[io.ReadWriteCloser]struct{}) } p.conns[connInfo.Conn] = struct{}{} p.mu.Unlock() // Register the connection with the controller and pass the cleanup function p.pluginCtx.VnetController.StartServerConnReadLoop(ctx, connInfo.Conn, func() { p.RemoveConn(connInfo.Conn) }) } func (p *VirtualNetPlugin) RemoveConn(conn io.ReadWriteCloser) { p.mu.Lock() defer p.mu.Unlock() // Check if the map exists, as Close might have set it to nil concurrently if p.conns != nil { delete(p.conns, conn) } } func (p *VirtualNetPlugin) Name() string { return v1.PluginVirtualNet } func (p *VirtualNetPlugin) Close() error { p.mu.Lock() defer p.mu.Unlock() // Close any remaining connections for conn := range p.conns { _ = conn.Close() } p.conns = nil return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/http2http.go
pkg/plugin/client/http2http.go
// Copyright 2024 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" stdlog "log" "net/http" "net/http/httputil" "github.com/fatedier/golib/pool" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { Register(v1.PluginHTTP2HTTP, NewHTTP2HTTPPlugin) } type HTTP2HTTPPlugin struct { opts *v1.HTTP2HTTPPluginOptions l *Listener s *http.Server } func NewHTTP2HTTPPlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.HTTP2HTTPPluginOptions) listener := NewProxyListener() p := &HTTP2HTTPPlugin{ opts: opts, l: listener, } rp := &httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { req := r.Out req.URL.Scheme = "http" req.URL.Host = p.opts.LocalAddr if p.opts.HostHeaderRewrite != "" { req.Host = p.opts.HostHeaderRewrite } for k, v := range p.opts.RequestHeaders.Set { req.Header.Set(k, v) } }, BufferPool: pool.NewBuffer(32 * 1024), ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0), } p.s = &http.Server{ Handler: rp, ReadHeaderTimeout: 0, } go func() { _ = p.s.Serve(listener) }() return p, nil } func (p *HTTP2HTTPPlugin) Handle(_ context.Context, connInfo *ConnectionInfo) { wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) _ = p.l.PutConn(wrapConn) } func (p *HTTP2HTTPPlugin) Name() string { return v1.PluginHTTP2HTTP } func (p *HTTP2HTTPPlugin) Close() error { return p.s.Close() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/plugin.go
pkg/plugin/client/plugin.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package client import ( "context" "fmt" "io" "net" "sync" "github.com/fatedier/golib/errors" pp "github.com/pires/go-proxyproto" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/vnet" ) type PluginContext struct { Name string VnetController *vnet.Controller } // Creators is used for create plugins to handle connections. var creators = make(map[string]CreatorFn) type CreatorFn func(pluginCtx PluginContext, options v1.ClientPluginOptions) (Plugin, error) func Register(name string, fn CreatorFn) { if _, exist := creators[name]; exist { panic(fmt.Sprintf("plugin [%s] is already registered", name)) } creators[name] = fn } func Create(pluginName string, pluginCtx PluginContext, options v1.ClientPluginOptions) (p Plugin, err error) { if fn, ok := creators[pluginName]; ok { p, err = fn(pluginCtx, options) } else { err = fmt.Errorf("plugin [%s] is not registered", pluginName) } return } type ConnectionInfo struct { Conn io.ReadWriteCloser UnderlyingConn net.Conn ProxyProtocolHeader *pp.Header SrcAddr net.Addr DstAddr net.Addr } type Plugin interface { Name() string Handle(ctx context.Context, connInfo *ConnectionInfo) Close() error } type Listener struct { conns chan net.Conn closed bool mu sync.Mutex } func NewProxyListener() *Listener { return &Listener{ conns: make(chan net.Conn, 64), } } func (l *Listener) Accept() (net.Conn, error) { conn, ok := <-l.conns if !ok { return nil, fmt.Errorf("listener closed") } return conn, nil } func (l *Listener) PutConn(conn net.Conn) error { err := errors.PanicToError(func() { l.conns <- conn }) return err } func (l *Listener) Close() error { l.mu.Lock() defer l.mu.Unlock() if !l.closed { close(l.conns) l.closed = true } return nil } func (l *Listener) Addr() net.Addr { return (*net.TCPAddr)(nil) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/socks5.go
pkg/plugin/client/socks5.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "io" "log" gosocks5 "github.com/armon/go-socks5" v1 "github.com/fatedier/frp/pkg/config/v1" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { Register(v1.PluginSocks5, NewSocks5Plugin) } type Socks5Plugin struct { Server *gosocks5.Server } func NewSocks5Plugin(_ PluginContext, options v1.ClientPluginOptions) (p Plugin, err error) { opts := options.(*v1.Socks5PluginOptions) cfg := &gosocks5.Config{ Logger: log.New(io.Discard, "", log.LstdFlags), } if opts.Username != "" || opts.Password != "" { cfg.Credentials = gosocks5.StaticCredentials(map[string]string{opts.Username: opts.Password}) } sp := &Socks5Plugin{} sp.Server, err = gosocks5.New(cfg) p = sp return } func (sp *Socks5Plugin) Handle(_ context.Context, connInfo *ConnectionInfo) { defer connInfo.Conn.Close() wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) _ = sp.Server.ServeConn(wrapConn) } func (sp *Socks5Plugin) Name() string { return v1.PluginSocks5 } func (sp *Socks5Plugin) Close() error { return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/plugin/client/https2https.go
pkg/plugin/client/https2https.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !frps package client import ( "context" "crypto/tls" "fmt" stdlog "log" "net/http" "net/http/httputil" "time" "github.com/fatedier/golib/pool" "github.com/samber/lo" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/transport" httppkg "github.com/fatedier/frp/pkg/util/http" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" ) func init() { Register(v1.PluginHTTPS2HTTPS, NewHTTPS2HTTPSPlugin) } type HTTPS2HTTPSPlugin struct { opts *v1.HTTPS2HTTPSPluginOptions l *Listener s *http.Server } func NewHTTPS2HTTPSPlugin(_ PluginContext, options v1.ClientPluginOptions) (Plugin, error) { opts := options.(*v1.HTTPS2HTTPSPluginOptions) listener := NewProxyListener() p := &HTTPS2HTTPSPlugin{ opts: opts, l: listener, } tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } rp := &httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.Out.Header["X-Forwarded-For"] = r.In.Header["X-Forwarded-For"] r.SetXForwarded() req := r.Out req.URL.Scheme = "https" req.URL.Host = p.opts.LocalAddr if p.opts.HostHeaderRewrite != "" { req.Host = p.opts.HostHeaderRewrite } for k, v := range p.opts.RequestHeaders.Set { req.Header.Set(k, v) } }, Transport: tr, BufferPool: pool.NewBuffer(32 * 1024), ErrorLog: stdlog.New(log.NewWriteLogger(log.WarnLevel, 2), "", 0), } handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.TLS != nil { tlsServerName, _ := httppkg.CanonicalHost(r.TLS.ServerName) host, _ := httppkg.CanonicalHost(r.Host) if tlsServerName != "" && tlsServerName != host { w.WriteHeader(http.StatusMisdirectedRequest) return } } rp.ServeHTTP(w, r) }) tlsConfig, err := transport.NewServerTLSConfig(p.opts.CrtPath, p.opts.KeyPath, "") if err != nil { return nil, fmt.Errorf("gen TLS config error: %v", err) } p.s = &http.Server{ Handler: handler, ReadHeaderTimeout: 60 * time.Second, TLSConfig: tlsConfig, } if !lo.FromPtr(opts.EnableHTTP2) { p.s.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler)) } go func() { _ = p.s.ServeTLS(listener, "", "") }() return p, nil } func (p *HTTPS2HTTPSPlugin) Handle(_ context.Context, connInfo *ConnectionInfo) { wrapConn := netpkg.WrapReadWriteCloserToConn(connInfo.Conn, connInfo.UnderlyingConn) if connInfo.SrcAddr != nil { wrapConn.SetRemoteAddr(connInfo.SrcAddr) } _ = p.l.PutConn(wrapConn) } func (p *HTTPS2HTTPSPlugin) Name() string { return v1.PluginHTTPS2HTTPS } func (p *HTTPS2HTTPSPlugin) Close() error { return p.s.Close() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/vnet/tun_unsupported.go
pkg/vnet/tun_unsupported.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !darwin && !linux package vnet import ( "context" "fmt" "runtime" "golang.zx2c4.com/wireguard/tun" ) func openTun(_ context.Context, _ string) (tun.Device, error) { return nil, fmt.Errorf("virtual net is not supported on this platform (%s/%s)", runtime.GOOS, runtime.GOARCH) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/vnet/controller.go
pkg/vnet/controller.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vnet import ( "context" "encoding/base64" "fmt" "io" "net" "sync" "github.com/fatedier/golib/pool" "github.com/songgao/water/waterutil" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/util/log" "github.com/fatedier/frp/pkg/util/xlog" ) const ( maxPacketSize = 1420 ) type Controller struct { addr string tun io.ReadWriteCloser clientRouter *clientRouter // Route based on destination IP (client mode) serverRouter *serverRouter // Route based on source IP (server mode) } func NewController(cfg v1.VirtualNetConfig) *Controller { return &Controller{ addr: cfg.Address, clientRouter: newClientRouter(), serverRouter: newServerRouter(), } } func (c *Controller) Init() error { tunDevice, err := OpenTun(context.Background(), c.addr) if err != nil { return err } c.tun = tunDevice return nil } func (c *Controller) Run() error { conn := c.tun for { buf := pool.GetBuf(maxPacketSize) n, err := conn.Read(buf) if err != nil { pool.PutBuf(buf) log.Warnf("vnet read from tun error: %v", err) return err } c.handlePacket(buf[:n]) pool.PutBuf(buf) } } // handlePacket processes a single packet. The caller is responsible for managing the buffer. func (c *Controller) handlePacket(buf []byte) { log.Tracef("vnet read from tun [%d]: %s", len(buf), base64.StdEncoding.EncodeToString(buf)) var src, dst net.IP switch { case waterutil.IsIPv4(buf): header, err := ipv4.ParseHeader(buf) if err != nil { log.Warnf("parse ipv4 header error: %v", err) return } src = header.Src dst = header.Dst log.Tracef("%s >> %s %d/%-4d %-4x %d", header.Src, header.Dst, header.Len, header.TotalLen, header.ID, header.Flags) case waterutil.IsIPv6(buf): header, err := ipv6.ParseHeader(buf) if err != nil { log.Warnf("parse ipv6 header error: %v", err) return } src = header.Src dst = header.Dst log.Tracef("%s >> %s %d %d", header.Src, header.Dst, header.PayloadLen, header.TrafficClass) default: log.Tracef("unknown packet, discarded(%d)", len(buf)) return } targetConn, err := c.clientRouter.findConn(dst) if err == nil { if err := WriteMessage(targetConn, buf); err != nil { log.Warnf("write to client target conn error: %v", err) } return } targetConn, err = c.serverRouter.findConnBySrc(dst) if err == nil { if err := WriteMessage(targetConn, buf); err != nil { log.Warnf("write to server target conn error: %v", err) } return } log.Tracef("no route found for packet from %s to %s", src, dst) } func (c *Controller) Stop() error { return c.tun.Close() } // Client connection read loop func (c *Controller) readLoopClient(ctx context.Context, conn io.ReadWriteCloser) { xl := xlog.FromContextSafe(ctx) defer func() { // Remove the route when read loop ends (connection closed) c.clientRouter.removeConnRoute(conn) conn.Close() }() for { data, err := ReadMessage(conn) if err != nil { xl.Warnf("client read error: %v", err) return } if len(data) == 0 { continue } switch { case waterutil.IsIPv4(data): header, err := ipv4.ParseHeader(data) if err != nil { xl.Warnf("parse ipv4 header error: %v", err) continue } xl.Tracef("%s >> %s %d/%-4d %-4x %d", header.Src, header.Dst, header.Len, header.TotalLen, header.ID, header.Flags) case waterutil.IsIPv6(data): header, err := ipv6.ParseHeader(data) if err != nil { xl.Warnf("parse ipv6 header error: %v", err) continue } xl.Tracef("%s >> %s %d %d", header.Src, header.Dst, header.PayloadLen, header.TrafficClass) default: xl.Tracef("unknown packet, discarded(%d)", len(data)) continue } xl.Tracef("vnet write to tun (client) [%d]: %s", len(data), base64.StdEncoding.EncodeToString(data)) _, err = c.tun.Write(data) if err != nil { xl.Warnf("client write tun error: %v", err) } } } // Server connection read loop func (c *Controller) readLoopServer(ctx context.Context, conn io.ReadWriteCloser, onClose func()) { xl := xlog.FromContextSafe(ctx) defer func() { // Clean up all IP mappings associated with this connection when it closes c.serverRouter.cleanupConnIPs(conn) // Call the provided callback upon closure if onClose != nil { onClose() } conn.Close() }() for { data, err := ReadMessage(conn) if err != nil { xl.Warnf("server read error: %v", err) return } if len(data) == 0 { continue } // Register source IP to connection mapping if waterutil.IsIPv4(data) || waterutil.IsIPv6(data) { var src net.IP if waterutil.IsIPv4(data) { header, err := ipv4.ParseHeader(data) if err == nil { src = header.Src c.serverRouter.registerSrcIP(src, conn) } } else { header, err := ipv6.ParseHeader(data) if err == nil { src = header.Src c.serverRouter.registerSrcIP(src, conn) } } } xl.Tracef("vnet write to tun (server) [%d]: %s", len(data), base64.StdEncoding.EncodeToString(data)) _, err = c.tun.Write(data) if err != nil { xl.Warnf("server write tun error: %v", err) } } } // RegisterClientRoute registers a client route (based on destination IP CIDR) // and starts the read loop func (c *Controller) RegisterClientRoute(ctx context.Context, name string, routes []net.IPNet, conn io.ReadWriteCloser) { c.clientRouter.addRoute(name, routes, conn) go c.readLoopClient(ctx, conn) } // UnregisterClientRoute Remove client route from routing table func (c *Controller) UnregisterClientRoute(name string) { c.clientRouter.delRoute(name) } // StartServerConnReadLoop starts the read loop for a server connection // (dynamically associates with source IPs) func (c *Controller) StartServerConnReadLoop(ctx context.Context, conn io.ReadWriteCloser, onClose func()) { go c.readLoopServer(ctx, conn, onClose) } // ParseRoutes Convert route strings to IPNet objects func ParseRoutes(routeStrings []string) ([]net.IPNet, error) { routes := make([]net.IPNet, 0, len(routeStrings)) for _, r := range routeStrings { _, ipNet, err := net.ParseCIDR(r) if err != nil { return nil, fmt.Errorf("parse route %s error: %v", r, err) } routes = append(routes, *ipNet) } return routes, nil } // Client router (based on destination IP routing) type clientRouter struct { routes map[string]*routeElement mu sync.RWMutex } func newClientRouter() *clientRouter { return &clientRouter{ routes: make(map[string]*routeElement), } } func (r *clientRouter) addRoute(name string, routes []net.IPNet, conn io.ReadWriteCloser) { r.mu.Lock() defer r.mu.Unlock() r.routes[name] = &routeElement{ name: name, routes: routes, conn: conn, } } func (r *clientRouter) findConn(dst net.IP) (io.Writer, error) { r.mu.RLock() defer r.mu.RUnlock() for _, re := range r.routes { for _, route := range re.routes { if route.Contains(dst) { return re.conn, nil } } } return nil, fmt.Errorf("no route found for destination %s", dst) } func (r *clientRouter) delRoute(name string) { r.mu.Lock() defer r.mu.Unlock() delete(r.routes, name) } func (r *clientRouter) removeConnRoute(conn io.Writer) { r.mu.Lock() defer r.mu.Unlock() for name, re := range r.routes { if re.conn == conn { delete(r.routes, name) return } } } // Server router (based solely on source IP routing) type serverRouter struct { srcIPConns map[string]io.Writer // Source IP string to connection mapping mu sync.RWMutex } func newServerRouter() *serverRouter { return &serverRouter{ srcIPConns: make(map[string]io.Writer), } } func (r *serverRouter) findConnBySrc(src net.IP) (io.Writer, error) { r.mu.RLock() defer r.mu.RUnlock() conn, exists := r.srcIPConns[src.String()] if !exists { return nil, fmt.Errorf("no route found for source %s", src) } return conn, nil } func (r *serverRouter) registerSrcIP(src net.IP, conn io.Writer) { key := src.String() r.mu.RLock() existingConn, ok := r.srcIPConns[key] r.mu.RUnlock() // If the entry exists and the connection is the same, no need to do anything. if ok && existingConn == conn { return } // Acquire write lock to update the map. r.mu.Lock() defer r.mu.Unlock() // Double-check after acquiring the write lock to handle potential race conditions. existingConn, ok = r.srcIPConns[key] if ok && existingConn == conn { return } r.srcIPConns[key] = conn } // cleanupConnIPs removes all IP mappings associated with the specified connection func (r *serverRouter) cleanupConnIPs(conn io.Writer) { r.mu.Lock() defer r.mu.Unlock() // Find and delete all IP mappings pointing to this connection for ip, mappedConn := range r.srcIPConns { if mappedConn == conn { delete(r.srcIPConns, ip) } } } type routeElement struct { name string routes []net.IPNet conn io.ReadWriteCloser }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/vnet/tun_linux.go
pkg/vnet/tun_linux.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vnet import ( "context" "crypto/sha256" "encoding/hex" "fmt" "net" "strconv" "strings" "github.com/vishvananda/netlink" "golang.zx2c4.com/wireguard/tun" ) const ( baseTunName = "utun" defaultMTU = 1420 ) func openTun(_ context.Context, addr string) (tun.Device, error) { name, err := findNextTunName(baseTunName) if err != nil { name = getFallbackTunName(baseTunName, addr) } tunDevice, err := tun.CreateTUN(name, defaultMTU) if err != nil { return nil, fmt.Errorf("failed to create TUN device '%s': %w", name, err) } actualName, err := tunDevice.Name() if err != nil { return nil, err } ifn, err := net.InterfaceByName(actualName) if err != nil { return nil, err } link, err := netlink.LinkByName(actualName) if err != nil { return nil, err } ip, cidr, err := net.ParseCIDR(addr) if err != nil { return nil, err } if err := netlink.AddrAdd(link, &netlink.Addr{ IPNet: &net.IPNet{ IP: ip, Mask: cidr.Mask, }, }); err != nil { return nil, err } if err := netlink.LinkSetUp(link); err != nil { return nil, err } if err = addRoutes(ifn, cidr); err != nil { return nil, err } return tunDevice, nil } func findNextTunName(basename string) (string, error) { interfaces, err := net.Interfaces() if err != nil { return "", fmt.Errorf("failed to get network interfaces: %w", err) } maxSuffix := -1 for _, iface := range interfaces { name := iface.Name if strings.HasPrefix(name, basename) { suffix := name[len(basename):] if suffix == "" { continue } numSuffix, err := strconv.Atoi(suffix) if err == nil && numSuffix > maxSuffix { maxSuffix = numSuffix } } } nextSuffix := maxSuffix + 1 name := fmt.Sprintf("%s%d", basename, nextSuffix) return name, nil } func addRoutes(ifn *net.Interface, cidr *net.IPNet) error { r := netlink.Route{ Dst: cidr, LinkIndex: ifn.Index, } if err := netlink.RouteReplace(&r); err != nil { return fmt.Errorf("add route to %v error: %v", r.Dst, err) } return nil } // getFallbackTunName generates a deterministic fallback TUN device name // based on the base name and the provided address string using a hash. func getFallbackTunName(baseName, addr string) string { hasher := sha256.New() hasher.Write([]byte(addr)) hashBytes := hasher.Sum(nil) // Use first 4 bytes -> 8 hex chars for brevity, respecting IFNAMSIZ limit. shortHash := hex.EncodeToString(hashBytes[:4]) return fmt.Sprintf("%s%s", baseName, shortHash) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/vnet/message.go
pkg/vnet/message.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vnet import ( "encoding/binary" "fmt" "io" ) // Maximum message size const ( maxMessageSize = 1024 * 1024 // 1MB ) // Format: [length(4 bytes)][data(length bytes)] // ReadMessage reads a framed message from the reader func ReadMessage(r io.Reader) ([]byte, error) { // Read length (4 bytes) var length uint32 err := binary.Read(r, binary.LittleEndian, &length) if err != nil { return nil, fmt.Errorf("read message length error: %w", err) } // Check length to prevent DoS if length == 0 { return nil, fmt.Errorf("message length is 0") } if length > maxMessageSize { return nil, fmt.Errorf("message too large: %d > %d", length, maxMessageSize) } // Read message data data := make([]byte, length) _, err = io.ReadFull(r, data) if err != nil { return nil, fmt.Errorf("read message data error: %w", err) } return data, nil } // WriteMessage writes a framed message to the writer func WriteMessage(w io.Writer, data []byte) error { // Get data length length := uint32(len(data)) if length == 0 { return fmt.Errorf("message data length is 0") } if length > maxMessageSize { return fmt.Errorf("message too large: %d > %d", length, maxMessageSize) } // Write length err := binary.Write(w, binary.LittleEndian, length) if err != nil { return fmt.Errorf("write message length error: %w", err) } // Write message data _, err = w.Write(data) if err != nil { return fmt.Errorf("write message data error: %w", err) } return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/vnet/tun.go
pkg/vnet/tun.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vnet import ( "context" "io" "github.com/fatedier/golib/pool" "golang.zx2c4.com/wireguard/tun" ) const ( offset = 16 defaultPacketSize = 1420 ) type TunDevice interface { io.ReadWriteCloser } func OpenTun(ctx context.Context, addr string) (TunDevice, error) { td, err := openTun(ctx, addr) if err != nil { return nil, err } mtu, err := td.MTU() if err != nil { mtu = defaultPacketSize } bufferSize := max(mtu, defaultPacketSize) batchSize := td.BatchSize() device := &tunDeviceWrapper{ dev: td, bufferSize: bufferSize, readBuffers: make([][]byte, batchSize), sizeBuffer: make([]int, batchSize), } for i := range device.readBuffers { device.readBuffers[i] = make([]byte, offset+bufferSize) } return device, nil } type tunDeviceWrapper struct { dev tun.Device bufferSize int readBuffers [][]byte packetBuffers [][]byte sizeBuffer []int } func (d *tunDeviceWrapper) Read(p []byte) (int, error) { if len(d.packetBuffers) > 0 { n := copy(p, d.packetBuffers[0]) d.packetBuffers = d.packetBuffers[1:] return n, nil } n, err := d.dev.Read(d.readBuffers, d.sizeBuffer, offset) if err != nil { return 0, err } if n == 0 { return 0, io.EOF } for i := range n { if d.sizeBuffer[i] <= 0 { continue } d.packetBuffers = append(d.packetBuffers, d.readBuffers[i][offset:offset+d.sizeBuffer[i]]) } dataSize := copy(p, d.packetBuffers[0]) d.packetBuffers = d.packetBuffers[1:] return dataSize, nil } func (d *tunDeviceWrapper) Write(p []byte) (int, error) { buf := pool.GetBuf(offset + d.bufferSize) defer pool.PutBuf(buf) n := copy(buf[offset:], p) _, err := d.dev.Write([][]byte{buf[:offset+n]}, offset) return n, err } func (d *tunDeviceWrapper) Close() error { return d.dev.Close() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/vnet/tun_darwin.go
pkg/vnet/tun_darwin.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vnet import ( "context" "fmt" "net" "os/exec" "golang.zx2c4.com/wireguard/tun" ) const ( defaultTunName = "utun" defaultMTU = 1420 ) func openTun(_ context.Context, addr string) (tun.Device, error) { dev, err := tun.CreateTUN(defaultTunName, defaultMTU) if err != nil { return nil, err } name, err := dev.Name() if err != nil { return nil, err } ip, ipNet, err := net.ParseCIDR(addr) if err != nil { return nil, err } // Calculate a peer IP for the point-to-point tunnel peerIP := generatePeerIP(ip) // Configure the interface with proper point-to-point addressing if err = exec.Command("ifconfig", name, "inet", ip.String(), peerIP.String(), "mtu", fmt.Sprint(defaultMTU), "up").Run(); err != nil { return nil, err } // Add default route for the tunnel subnet routes := []net.IPNet{*ipNet} if err = addRoutes(name, routes); err != nil { return nil, err } return dev, nil } // generatePeerIP creates a peer IP for the point-to-point tunnel // by incrementing the last octet of the IP func generatePeerIP(ip net.IP) net.IP { // Make a copy to avoid modifying the original peerIP := make(net.IP, len(ip)) copy(peerIP, ip) // Increment the last octet peerIP[len(peerIP)-1]++ return peerIP } // addRoutes configures system routes for the TUN interface func addRoutes(ifName string, routes []net.IPNet) error { for _, route := range routes { routeStr := route.String() if err := exec.Command("route", "add", "-net", routeStr, "-interface", ifName).Run(); err != nil { return err } } return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/proto/udp/udp_test.go
pkg/proto/udp/udp_test.go
package udp import ( "testing" "github.com/stretchr/testify/require" ) func TestUdpPacket(t *testing.T) { require := require.New(t) buf := []byte("hello world") udpMsg := NewUDPPacket(buf, nil, nil) newBuf, err := GetContent(udpMsg) require.NoError(err) require.EqualValues(buf, newBuf) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/proto/udp/udp.go
pkg/proto/udp/udp.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package udp import ( "encoding/base64" "net" "sync" "time" "github.com/fatedier/golib/errors" "github.com/fatedier/golib/pool" "github.com/fatedier/frp/pkg/msg" netpkg "github.com/fatedier/frp/pkg/util/net" ) func NewUDPPacket(buf []byte, laddr, raddr *net.UDPAddr) *msg.UDPPacket { return &msg.UDPPacket{ Content: base64.StdEncoding.EncodeToString(buf), LocalAddr: laddr, RemoteAddr: raddr, } } func GetContent(m *msg.UDPPacket) (buf []byte, err error) { buf, err = base64.StdEncoding.DecodeString(m.Content) return } func ForwardUserConn(udpConn *net.UDPConn, readCh <-chan *msg.UDPPacket, sendCh chan<- *msg.UDPPacket, bufSize int) { // read go func() { for udpMsg := range readCh { buf, err := GetContent(udpMsg) if err != nil { continue } _, _ = udpConn.WriteToUDP(buf, udpMsg.RemoteAddr) } }() // write buf := pool.GetBuf(bufSize) defer pool.PutBuf(buf) for { n, remoteAddr, err := udpConn.ReadFromUDP(buf) if err != nil { return } // buf[:n] will be encoded to string, so the bytes can be reused udpMsg := NewUDPPacket(buf[:n], nil, remoteAddr) select { case sendCh <- udpMsg: default: } } } func Forwarder(dstAddr *net.UDPAddr, readCh <-chan *msg.UDPPacket, sendCh chan<- msg.Message, bufSize int, proxyProtocolVersion string) { var mu sync.RWMutex udpConnMap := make(map[string]*net.UDPConn) // read from dstAddr and write to sendCh writerFn := func(raddr *net.UDPAddr, udpConn *net.UDPConn) { addr := raddr.String() defer func() { mu.Lock() delete(udpConnMap, addr) mu.Unlock() udpConn.Close() }() buf := pool.GetBuf(bufSize) for { _ = udpConn.SetReadDeadline(time.Now().Add(30 * time.Second)) n, _, err := udpConn.ReadFromUDP(buf) if err != nil { return } udpMsg := NewUDPPacket(buf[:n], nil, raddr) if err = errors.PanicToError(func() { select { case sendCh <- udpMsg: default: } }); err != nil { return } } } // read from readCh go func() { for udpMsg := range readCh { buf, err := GetContent(udpMsg) if err != nil { continue } mu.Lock() udpConn, ok := udpConnMap[udpMsg.RemoteAddr.String()] if !ok { udpConn, err = net.DialUDP("udp", nil, dstAddr) if err != nil { mu.Unlock() continue } udpConnMap[udpMsg.RemoteAddr.String()] = udpConn } mu.Unlock() // Add proxy protocol header if configured if proxyProtocolVersion != "" && udpMsg.RemoteAddr != nil { ppBuf, err := netpkg.BuildProxyProtocolHeader(udpMsg.RemoteAddr, dstAddr, proxyProtocolVersion) if err == nil { // Prepend proxy protocol header to the UDP payload finalBuf := make([]byte, len(ppBuf)+len(buf)) copy(finalBuf, ppBuf) copy(finalBuf[len(ppBuf):], buf) buf = finalBuf } } _, err = udpConn.Write(buf) if err != nil { udpConn.Close() } if !ok { go writerFn(udpMsg.RemoteAddr, udpConn) } } }() }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/errors/errors.go
pkg/errors/errors.go
// Copyright 2016 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package errors import ( "errors" ) var ( ErrMsgType = errors.New("message type error") ErrCtlClosed = errors.New("control is closed") )
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/metrics/metrics.go
pkg/metrics/metrics.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package metrics import ( "github.com/fatedier/frp/pkg/metrics/aggregate" ) var ( EnableMem = aggregate.EnableMem EnablePrometheus = aggregate.EnablePrometheus )
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/metrics/aggregate/server.go
pkg/metrics/aggregate/server.go
// Copyright 2020 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package aggregate import ( "github.com/fatedier/frp/pkg/metrics/mem" "github.com/fatedier/frp/pkg/metrics/prometheus" "github.com/fatedier/frp/server/metrics" ) // EnableMem start to mark metrics to memory monitor system. func EnableMem() { sm.Add(mem.ServerMetrics) } // EnablePrometheus start to mark metrics to prometheus. func EnablePrometheus() { sm.Add(prometheus.ServerMetrics) } var sm = &serverMetrics{} func init() { metrics.Register(sm) } type serverMetrics struct { ms []metrics.ServerMetrics } func (m *serverMetrics) Add(sm metrics.ServerMetrics) { m.ms = append(m.ms, sm) } func (m *serverMetrics) NewClient() { for _, v := range m.ms { v.NewClient() } } func (m *serverMetrics) CloseClient() { for _, v := range m.ms { v.CloseClient() } } func (m *serverMetrics) NewProxy(name string, proxyType string) { for _, v := range m.ms { v.NewProxy(name, proxyType) } } func (m *serverMetrics) CloseProxy(name string, proxyType string) { for _, v := range m.ms { v.CloseProxy(name, proxyType) } } func (m *serverMetrics) OpenConnection(name string, proxyType string) { for _, v := range m.ms { v.OpenConnection(name, proxyType) } } func (m *serverMetrics) CloseConnection(name string, proxyType string) { for _, v := range m.ms { v.CloseConnection(name, proxyType) } } func (m *serverMetrics) AddTrafficIn(name string, proxyType string, trafficBytes int64) { for _, v := range m.ms { v.AddTrafficIn(name, proxyType, trafficBytes) } } func (m *serverMetrics) AddTrafficOut(name string, proxyType string, trafficBytes int64) { for _, v := range m.ms { v.AddTrafficOut(name, proxyType, trafficBytes) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/metrics/prometheus/server.go
pkg/metrics/prometheus/server.go
package prometheus import ( "github.com/prometheus/client_golang/prometheus" "github.com/fatedier/frp/server/metrics" ) const ( namespace = "frp" serverSubsystem = "server" ) var ServerMetrics metrics.ServerMetrics = newServerMetrics() type serverMetrics struct { clientCount prometheus.Gauge proxyCount *prometheus.GaugeVec proxyCountDetailed *prometheus.GaugeVec connectionCount *prometheus.GaugeVec trafficIn *prometheus.CounterVec trafficOut *prometheus.CounterVec } func (m *serverMetrics) NewClient() { m.clientCount.Inc() } func (m *serverMetrics) CloseClient() { m.clientCount.Dec() } func (m *serverMetrics) NewProxy(name string, proxyType string) { m.proxyCount.WithLabelValues(proxyType).Inc() m.proxyCountDetailed.WithLabelValues(proxyType, name).Inc() } func (m *serverMetrics) CloseProxy(name string, proxyType string) { m.proxyCount.WithLabelValues(proxyType).Dec() m.proxyCountDetailed.WithLabelValues(proxyType, name).Dec() } func (m *serverMetrics) OpenConnection(name string, proxyType string) { m.connectionCount.WithLabelValues(name, proxyType).Inc() } func (m *serverMetrics) CloseConnection(name string, proxyType string) { m.connectionCount.WithLabelValues(name, proxyType).Dec() } func (m *serverMetrics) AddTrafficIn(name string, proxyType string, trafficBytes int64) { m.trafficIn.WithLabelValues(name, proxyType).Add(float64(trafficBytes)) } func (m *serverMetrics) AddTrafficOut(name string, proxyType string, trafficBytes int64) { m.trafficOut.WithLabelValues(name, proxyType).Add(float64(trafficBytes)) } func newServerMetrics() *serverMetrics { m := &serverMetrics{ clientCount: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: namespace, Subsystem: serverSubsystem, Name: "client_counts", Help: "The current client counts of frps", }), proxyCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: namespace, Subsystem: serverSubsystem, Name: "proxy_counts", Help: "The current proxy counts", }, []string{"type"}), proxyCountDetailed: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: namespace, Subsystem: serverSubsystem, Name: "proxy_counts_detailed", Help: "The current number of proxies grouped by type and name", }, []string{"type", "name"}), connectionCount: prometheus.NewGaugeVec(prometheus.GaugeOpts{ Namespace: namespace, Subsystem: serverSubsystem, Name: "connection_counts", Help: "The current connection counts", }, []string{"name", "type"}), trafficIn: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: namespace, Subsystem: serverSubsystem, Name: "traffic_in", Help: "The total in traffic", }, []string{"name", "type"}), trafficOut: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: namespace, Subsystem: serverSubsystem, Name: "traffic_out", Help: "The total out traffic", }, []string{"name", "type"}), } prometheus.MustRegister(m.clientCount) prometheus.MustRegister(m.proxyCount) prometheus.MustRegister(m.proxyCountDetailed) prometheus.MustRegister(m.connectionCount) prometheus.MustRegister(m.trafficIn) prometheus.MustRegister(m.trafficOut) return m }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/metrics/mem/types.go
pkg/metrics/mem/types.go
// Copyright 2017 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package mem import ( "time" "github.com/fatedier/frp/pkg/util/metric" ) const ( ReserveDays = 7 ) type ServerStats struct { TotalTrafficIn int64 TotalTrafficOut int64 CurConns int64 ClientCounts int64 ProxyTypeCounts map[string]int64 } type ProxyStats struct { Name string Type string TodayTrafficIn int64 TodayTrafficOut int64 LastStartTime string LastCloseTime string CurConns int64 } type ProxyTrafficInfo struct { Name string TrafficIn []int64 TrafficOut []int64 } type ProxyStatistics struct { Name string ProxyType string TrafficIn metric.DateCounter TrafficOut metric.DateCounter CurConns metric.Counter LastStartTime time.Time LastCloseTime time.Time } type ServerStatistics struct { TotalTrafficIn metric.DateCounter TotalTrafficOut metric.DateCounter CurConns metric.Counter // counter for clients ClientCounts metric.Counter // counter for proxy types ProxyTypeCounts map[string]metric.Counter // statistics for different proxies // key is proxy name ProxyStatistics map[string]*ProxyStatistics } type Collector interface { GetServer() *ServerStats GetProxiesByType(proxyType string) []*ProxyStats GetProxiesByTypeAndName(proxyType string, proxyName string) *ProxyStats GetProxyTraffic(name string) *ProxyTrafficInfo ClearOfflineProxies() (int, int) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/metrics/mem/server.go
pkg/metrics/mem/server.go
// Copyright 2019 fatedier, fatedier@gmail.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package mem import ( "sync" "time" "github.com/fatedier/frp/pkg/util/log" "github.com/fatedier/frp/pkg/util/metric" server "github.com/fatedier/frp/server/metrics" ) var ( sm = newServerMetrics() ServerMetrics server.ServerMetrics StatsCollector Collector ) func init() { ServerMetrics = sm StatsCollector = sm sm.run() } type serverMetrics struct { info *ServerStatistics mu sync.Mutex } func newServerMetrics() *serverMetrics { return &serverMetrics{ info: &ServerStatistics{ TotalTrafficIn: metric.NewDateCounter(ReserveDays), TotalTrafficOut: metric.NewDateCounter(ReserveDays), CurConns: metric.NewCounter(), ClientCounts: metric.NewCounter(), ProxyTypeCounts: make(map[string]metric.Counter), ProxyStatistics: make(map[string]*ProxyStatistics), }, } } func (m *serverMetrics) run() { go func() { for { time.Sleep(12 * time.Hour) start := time.Now() count, total := m.clearUselessInfo(time.Duration(7*24) * time.Hour) log.Debugf("clear useless proxy statistics data count %d/%d, cost %v", count, total, time.Since(start)) } }() } func (m *serverMetrics) clearUselessInfo(continuousOfflineDuration time.Duration) (int, int) { count := 0 total := 0 // To check if there are any proxies that have been closed for more than continuousOfflineDuration and remove them. m.mu.Lock() defer m.mu.Unlock() total = len(m.info.ProxyStatistics) for name, data := range m.info.ProxyStatistics { if !data.LastCloseTime.IsZero() && data.LastStartTime.Before(data.LastCloseTime) && time.Since(data.LastCloseTime) > continuousOfflineDuration { delete(m.info.ProxyStatistics, name) count++ log.Tracef("clear proxy [%s]'s statistics data, lastCloseTime: [%s]", name, data.LastCloseTime.String()) } } return count, total } func (m *serverMetrics) ClearOfflineProxies() (int, int) { return m.clearUselessInfo(0) } func (m *serverMetrics) NewClient() { m.info.ClientCounts.Inc(1) } func (m *serverMetrics) CloseClient() { m.info.ClientCounts.Dec(1) } func (m *serverMetrics) NewProxy(name string, proxyType string) { m.mu.Lock() defer m.mu.Unlock() counter, ok := m.info.ProxyTypeCounts[proxyType] if !ok { counter = metric.NewCounter() } counter.Inc(1) m.info.ProxyTypeCounts[proxyType] = counter proxyStats, ok := m.info.ProxyStatistics[name] if !ok || proxyStats.ProxyType != proxyType { proxyStats = &ProxyStatistics{ Name: name, ProxyType: proxyType, CurConns: metric.NewCounter(), TrafficIn: metric.NewDateCounter(ReserveDays), TrafficOut: metric.NewDateCounter(ReserveDays), } m.info.ProxyStatistics[name] = proxyStats } proxyStats.LastStartTime = time.Now() } func (m *serverMetrics) CloseProxy(name string, proxyType string) { m.mu.Lock() defer m.mu.Unlock() if counter, ok := m.info.ProxyTypeCounts[proxyType]; ok { counter.Dec(1) } if proxyStats, ok := m.info.ProxyStatistics[name]; ok { proxyStats.LastCloseTime = time.Now() } } func (m *serverMetrics) OpenConnection(name string, _ string) { m.info.CurConns.Inc(1) m.mu.Lock() defer m.mu.Unlock() proxyStats, ok := m.info.ProxyStatistics[name] if ok { proxyStats.CurConns.Inc(1) m.info.ProxyStatistics[name] = proxyStats } } func (m *serverMetrics) CloseConnection(name string, _ string) { m.info.CurConns.Dec(1) m.mu.Lock() defer m.mu.Unlock() proxyStats, ok := m.info.ProxyStatistics[name] if ok { proxyStats.CurConns.Dec(1) m.info.ProxyStatistics[name] = proxyStats } } func (m *serverMetrics) AddTrafficIn(name string, _ string, trafficBytes int64) { m.info.TotalTrafficIn.Inc(trafficBytes) m.mu.Lock() defer m.mu.Unlock() proxyStats, ok := m.info.ProxyStatistics[name] if ok { proxyStats.TrafficIn.Inc(trafficBytes) m.info.ProxyStatistics[name] = proxyStats } } func (m *serverMetrics) AddTrafficOut(name string, _ string, trafficBytes int64) { m.info.TotalTrafficOut.Inc(trafficBytes) m.mu.Lock() defer m.mu.Unlock() proxyStats, ok := m.info.ProxyStatistics[name] if ok { proxyStats.TrafficOut.Inc(trafficBytes) m.info.ProxyStatistics[name] = proxyStats } } // Get stats data api. func (m *serverMetrics) GetServer() *ServerStats { m.mu.Lock() defer m.mu.Unlock() s := &ServerStats{ TotalTrafficIn: m.info.TotalTrafficIn.TodayCount(), TotalTrafficOut: m.info.TotalTrafficOut.TodayCount(), CurConns: int64(m.info.CurConns.Count()), ClientCounts: int64(m.info.ClientCounts.Count()), ProxyTypeCounts: make(map[string]int64), } for k, v := range m.info.ProxyTypeCounts { s.ProxyTypeCounts[k] = int64(v.Count()) } return s } func (m *serverMetrics) GetProxiesByType(proxyType string) []*ProxyStats { res := make([]*ProxyStats, 0) m.mu.Lock() defer m.mu.Unlock() for name, proxyStats := range m.info.ProxyStatistics { if proxyStats.ProxyType != proxyType { continue } ps := &ProxyStats{ Name: name, Type: proxyStats.ProxyType, TodayTrafficIn: proxyStats.TrafficIn.TodayCount(), TodayTrafficOut: proxyStats.TrafficOut.TodayCount(), CurConns: int64(proxyStats.CurConns.Count()), } if !proxyStats.LastStartTime.IsZero() { ps.LastStartTime = proxyStats.LastStartTime.Format("01-02 15:04:05") } if !proxyStats.LastCloseTime.IsZero() { ps.LastCloseTime = proxyStats.LastCloseTime.Format("01-02 15:04:05") } res = append(res, ps) } return res } func (m *serverMetrics) GetProxiesByTypeAndName(proxyType string, proxyName string) (res *ProxyStats) { m.mu.Lock() defer m.mu.Unlock() for name, proxyStats := range m.info.ProxyStatistics { if proxyStats.ProxyType != proxyType { continue } if name != proxyName { continue } res = &ProxyStats{ Name: name, Type: proxyStats.ProxyType, TodayTrafficIn: proxyStats.TrafficIn.TodayCount(), TodayTrafficOut: proxyStats.TrafficOut.TodayCount(), CurConns: int64(proxyStats.CurConns.Count()), } if !proxyStats.LastStartTime.IsZero() { res.LastStartTime = proxyStats.LastStartTime.Format("01-02 15:04:05") } if !proxyStats.LastCloseTime.IsZero() { res.LastCloseTime = proxyStats.LastCloseTime.Format("01-02 15:04:05") } break } return } func (m *serverMetrics) GetProxyTraffic(name string) (res *ProxyTrafficInfo) { m.mu.Lock() defer m.mu.Unlock() proxyStats, ok := m.info.ProxyStatistics[name] if ok { res = &ProxyTrafficInfo{ Name: name, } res.TrafficIn = proxyStats.TrafficIn.GetLastDaysCount(ReserveDays) res.TrafficOut = proxyStats.TrafficOut.GetLastDaysCount(ReserveDays) } return }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/ssh/terminal.go
pkg/ssh/terminal.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ssh import ( "github.com/fatedier/frp/client/proxy" v1 "github.com/fatedier/frp/pkg/config/v1" ) func createSuccessInfo(user string, pc v1.ProxyConfigurer, ps *proxy.WorkingStatus) string { base := pc.GetBaseConfig() out := "\n" out += "frp (via SSH) (Ctrl+C to quit)\n\n" out += "User: " + user + "\n" out += "ProxyName: " + base.Name + "\n" out += "Type: " + base.Type + "\n" out += "RemoteAddress: " + ps.RemoteAddr + "\n" return out }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/ssh/server.go
pkg/ssh/server.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ssh import ( "context" "encoding/binary" "errors" "fmt" "net" "slices" "strings" "sync" "time" libio "github.com/fatedier/golib/io" "github.com/spf13/cobra" flag "github.com/spf13/pflag" "golang.org/x/crypto/ssh" "github.com/fatedier/frp/client/proxy" "github.com/fatedier/frp/pkg/config" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" "github.com/fatedier/frp/pkg/util/util" "github.com/fatedier/frp/pkg/util/xlog" "github.com/fatedier/frp/pkg/virtual" ) const ( // https://datatracker.ietf.org/doc/html/rfc4254#page-16 ChannelTypeServerOpenChannel = "forwarded-tcpip" RequestTypeForward = "tcpip-forward" ) type tcpipForward struct { Host string Port uint32 } // https://datatracker.ietf.org/doc/html/rfc4254#page-16 type forwardedTCPPayload struct { Addr string Port uint32 OriginAddr string OriginPort uint32 } type TunnelServer struct { underlyingConn net.Conn sshConn *ssh.ServerConn sc *ssh.ServerConfig firstChannel ssh.Channel vc *virtual.Client peerServerListener *netpkg.InternalListener doneCh chan struct{} closeDoneChOnce sync.Once } func NewTunnelServer(conn net.Conn, sc *ssh.ServerConfig, peerServerListener *netpkg.InternalListener) (*TunnelServer, error) { s := &TunnelServer{ underlyingConn: conn, sc: sc, peerServerListener: peerServerListener, doneCh: make(chan struct{}), } return s, nil } func (s *TunnelServer) Run() error { sshConn, channels, requests, err := ssh.NewServerConn(s.underlyingConn, s.sc) if err != nil { return err } s.sshConn = sshConn addr, extraPayload, err := s.waitForwardAddrAndExtraPayload(channels, requests, 3*time.Second) if err != nil { return err } clientCfg, pc, helpMessage, err := s.parseClientAndProxyConfigurer(addr, extraPayload) if err != nil { if errors.Is(err, flag.ErrHelp) { s.writeToClient(helpMessage) return nil } s.writeToClient(err.Error()) return fmt.Errorf("parse flags from ssh client error: %v", err) } if err := clientCfg.Complete(); err != nil { s.writeToClient(fmt.Sprintf("failed to complete client config: %v", err)) return fmt.Errorf("complete client config error: %v", err) } if sshConn.Permissions != nil { clientCfg.User = util.EmptyOr(sshConn.Permissions.Extensions["user"], clientCfg.User) } pc.Complete(clientCfg.User) vc, err := virtual.NewClient(virtual.ClientOptions{ Common: clientCfg, Spec: &msg.ClientSpec{ Type: "ssh-tunnel", // If ssh does not require authentication, then the virtual client needs to authenticate through a token. // Otherwise, once ssh authentication is passed, the virtual client does not need to authenticate again. AlwaysAuthPass: !s.sc.NoClientAuth, }, HandleWorkConnCb: func(base *v1.ProxyBaseConfig, workConn net.Conn, m *msg.StartWorkConn) bool { // join workConn and ssh channel c, err := s.openConn(addr) if err != nil { log.Tracef("open conn error: %v", err) workConn.Close() return false } libio.Join(c, workConn) return false }, }) if err != nil { return err } s.vc = vc // transfer connection from virtual client to server peer listener go func() { l := s.vc.PeerListener() for { conn, err := l.Accept() if err != nil { return } _ = s.peerServerListener.PutConn(conn) } }() xl := xlog.New().AddPrefix(xlog.LogPrefix{Name: "sshVirtualClient", Value: "sshVirtualClient", Priority: 100}) ctx := xlog.NewContext(context.Background(), xl) go func() { vcErr := s.vc.Run(ctx) if vcErr != nil { s.writeToClient(vcErr.Error()) } // If vc.Run returns, it means that the virtual client has been closed, and the ssh tunnel connection should be closed. // One scenario is that the virtual client exits due to login failure. s.closeDoneChOnce.Do(func() { _ = sshConn.Close() close(s.doneCh) }) }() s.vc.UpdateProxyConfigurer([]v1.ProxyConfigurer{pc}) if ps, err := s.waitProxyStatusReady(pc.GetBaseConfig().Name, time.Second); err != nil { s.writeToClient(err.Error()) log.Warnf("wait proxy status ready error: %v", err) } else { // success s.writeToClient(createSuccessInfo(clientCfg.User, pc, ps)) _ = sshConn.Wait() } s.vc.Close() log.Tracef("ssh tunnel connection from %v closed", sshConn.RemoteAddr()) s.closeDoneChOnce.Do(func() { _ = sshConn.Close() close(s.doneCh) }) return nil } func (s *TunnelServer) writeToClient(data string) { if s.firstChannel == nil { return } _, _ = s.firstChannel.Write([]byte(data + "\n")) } func (s *TunnelServer) waitForwardAddrAndExtraPayload( channels <-chan ssh.NewChannel, requests <-chan *ssh.Request, timeout time.Duration, ) (*tcpipForward, string, error) { addrCh := make(chan *tcpipForward, 1) extraPayloadCh := make(chan string, 1) // get forward address go func() { addrGot := false for req := range requests { if req.Type == RequestTypeForward && !addrGot { payload := tcpipForward{} if err := ssh.Unmarshal(req.Payload, &payload); err != nil { return } addrGot = true addrCh <- &payload } if req.WantReply { _ = req.Reply(true, nil) } } }() // get extra payload go func() { for newChannel := range channels { // extraPayload will send to extraPayloadCh go s.handleNewChannel(newChannel, extraPayloadCh) } }() var ( addr *tcpipForward extraPayload string ) timer := time.NewTimer(timeout) defer timer.Stop() for { select { case v := <-addrCh: addr = v case extra := <-extraPayloadCh: extraPayload = extra case <-timer.C: return nil, "", fmt.Errorf("get addr and extra payload timeout") } if addr != nil && extraPayload != "" { break } } return addr, extraPayload, nil } func (s *TunnelServer) parseClientAndProxyConfigurer(_ *tcpipForward, extraPayload string) (*v1.ClientCommonConfig, v1.ProxyConfigurer, string, error) { helpMessage := "" cmd := &cobra.Command{ Use: "ssh v0@{address} [command]", Short: "ssh v0@{address} [command]", Run: func(*cobra.Command, []string) {}, } cmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc) args := strings.Split(extraPayload, " ") if len(args) < 1 { return nil, nil, helpMessage, fmt.Errorf("invalid extra payload") } proxyType := strings.TrimSpace(args[0]) supportTypes := []string{"tcp", "http", "https", "tcpmux", "stcp"} if !slices.Contains(supportTypes, proxyType) { return nil, nil, helpMessage, fmt.Errorf("invalid proxy type: %s, support types: %v", proxyType, supportTypes) } pc := v1.NewProxyConfigurerByType(v1.ProxyType(proxyType)) if pc == nil { return nil, nil, helpMessage, fmt.Errorf("new proxy configurer error") } config.RegisterProxyFlags(cmd, pc, config.WithSSHMode()) clientCfg := v1.ClientCommonConfig{} config.RegisterClientCommonConfigFlags(cmd, &clientCfg, config.WithSSHMode()) cmd.InitDefaultHelpCmd() if err := cmd.ParseFlags(args); err != nil { if errors.Is(err, flag.ErrHelp) { helpMessage = cmd.UsageString() } return nil, nil, helpMessage, err } // if name is not set, generate a random one if pc.GetBaseConfig().Name == "" { id, err := util.RandIDWithLen(8) if err != nil { return nil, nil, helpMessage, fmt.Errorf("generate random id error: %v", err) } pc.GetBaseConfig().Name = fmt.Sprintf("sshtunnel-%s-%s", proxyType, id) } return &clientCfg, pc, helpMessage, nil } func (s *TunnelServer) handleNewChannel(channel ssh.NewChannel, extraPayloadCh chan string) { ch, reqs, err := channel.Accept() if err != nil { return } if s.firstChannel == nil { s.firstChannel = ch } go s.keepAlive(ch) for req := range reqs { if req.WantReply { _ = req.Reply(true, nil) } if req.Type != "exec" || len(req.Payload) <= 4 { continue } end := 4 + binary.BigEndian.Uint32(req.Payload[:4]) if len(req.Payload) < int(end) { continue } extraPayload := string(req.Payload[4:end]) select { case extraPayloadCh <- extraPayload: default: } } } func (s *TunnelServer) keepAlive(ch ssh.Channel) { tk := time.NewTicker(time.Second * 30) defer tk.Stop() for { select { case <-tk.C: _, err := ch.SendRequest("heartbeat", false, nil) if err != nil { return } case <-s.doneCh: return } } } func (s *TunnelServer) openConn(addr *tcpipForward) (net.Conn, error) { payload := forwardedTCPPayload{ Addr: addr.Host, Port: addr.Port, // Note: Here is just for compatibility, not the real source address. OriginAddr: addr.Host, OriginPort: addr.Port, } channel, reqs, err := s.sshConn.OpenChannel(ChannelTypeServerOpenChannel, ssh.Marshal(&payload)) if err != nil { return nil, fmt.Errorf("open ssh channel error: %v", err) } go ssh.DiscardRequests(reqs) conn := netpkg.WrapReadWriteCloserToConn(channel, s.underlyingConn) return conn, nil } func (s *TunnelServer) waitProxyStatusReady(name string, timeout time.Duration) (*proxy.WorkingStatus, error) { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() timer := time.NewTimer(timeout) defer timer.Stop() statusExporter := s.vc.Service().StatusExporter() for { select { case <-ticker.C: ps, ok := statusExporter.GetProxyStatus(name) if !ok { continue } switch ps.Phase { case proxy.ProxyPhaseRunning: return ps, nil case proxy.ProxyPhaseStartErr, proxy.ProxyPhaseClosed: return ps, errors.New(ps.Err) } case <-timer.C: return nil, fmt.Errorf("wait proxy status ready timeout") case <-s.doneCh: return nil, fmt.Errorf("ssh tunnel server closed") } } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/ssh/gateway.go
pkg/ssh/gateway.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ssh import ( "fmt" "net" "os" "strconv" "strings" "golang.org/x/crypto/ssh" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/transport" "github.com/fatedier/frp/pkg/util/log" netpkg "github.com/fatedier/frp/pkg/util/net" ) type Gateway struct { bindPort int ln net.Listener peerServerListener *netpkg.InternalListener sshConfig *ssh.ServerConfig } func NewGateway( cfg v1.SSHTunnelGateway, bindAddr string, peerServerListener *netpkg.InternalListener, ) (*Gateway, error) { sshConfig := &ssh.ServerConfig{} // privateKey var ( privateKeyBytes []byte err error ) if cfg.PrivateKeyFile != "" { privateKeyBytes, err = os.ReadFile(cfg.PrivateKeyFile) } else { if cfg.AutoGenPrivateKeyPath != "" { privateKeyBytes, _ = os.ReadFile(cfg.AutoGenPrivateKeyPath) } if len(privateKeyBytes) == 0 { privateKeyBytes, err = transport.NewRandomPrivateKey() if err == nil && cfg.AutoGenPrivateKeyPath != "" { err = os.WriteFile(cfg.AutoGenPrivateKeyPath, privateKeyBytes, 0o600) } } } if err != nil { return nil, err } privateKey, err := ssh.ParsePrivateKey(privateKeyBytes) if err != nil { return nil, err } sshConfig.AddHostKey(privateKey) sshConfig.NoClientAuth = cfg.AuthorizedKeysFile == "" sshConfig.PublicKeyCallback = func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { authorizedKeysMap, err := loadAuthorizedKeysFromFile(cfg.AuthorizedKeysFile) if err != nil { log.Errorf("load authorized keys file error: %v", err) return nil, fmt.Errorf("internal error") } user, ok := authorizedKeysMap[string(key.Marshal())] if !ok { return nil, fmt.Errorf("unknown public key for remoteAddr %q", conn.RemoteAddr()) } return &ssh.Permissions{ Extensions: map[string]string{ "user": user, }, }, nil } ln, err := net.Listen("tcp", net.JoinHostPort(bindAddr, strconv.Itoa(cfg.BindPort))) if err != nil { return nil, err } return &Gateway{ bindPort: cfg.BindPort, ln: ln, peerServerListener: peerServerListener, sshConfig: sshConfig, }, nil } func (g *Gateway) Run() { for { conn, err := g.ln.Accept() if err != nil { return } go g.handleConn(conn) } } func (g *Gateway) Close() error { return g.ln.Close() } func (g *Gateway) handleConn(conn net.Conn) { defer conn.Close() ts, err := NewTunnelServer(conn, g.sshConfig, g.peerServerListener) if err != nil { return } if err := ts.Run(); err != nil { log.Errorf("ssh tunnel server run error: %v", err) } } func loadAuthorizedKeysFromFile(path string) (map[string]string, error) { authorizedKeysMap := make(map[string]string) // value is username authorizedKeysBytes, err := os.ReadFile(path) if err != nil { return nil, err } for len(authorizedKeysBytes) > 0 { pubKey, comment, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes) if err != nil { return nil, err } authorizedKeysMap[string(pubKey.Marshal())] = strings.TrimSpace(comment) authorizedKeysBytes = rest } return authorizedKeysMap, nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/virtual/client.go
pkg/virtual/client.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package virtual import ( "context" "net" "github.com/fatedier/frp/client" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/msg" netpkg "github.com/fatedier/frp/pkg/util/net" ) type ClientOptions struct { Common *v1.ClientCommonConfig Spec *msg.ClientSpec HandleWorkConnCb func(*v1.ProxyBaseConfig, net.Conn, *msg.StartWorkConn) bool } type Client struct { l *netpkg.InternalListener svr *client.Service } func NewClient(options ClientOptions) (*Client, error) { if options.Common != nil { if err := options.Common.Complete(); err != nil { return nil, err } } ln := netpkg.NewInternalListener() serviceOptions := client.ServiceOptions{ Common: options.Common, ClientSpec: options.Spec, ConnectorCreator: func(context.Context, *v1.ClientCommonConfig) client.Connector { return &pipeConnector{ peerListener: ln, } }, HandleWorkConnCb: options.HandleWorkConnCb, } svr, err := client.NewService(serviceOptions) if err != nil { return nil, err } return &Client{ l: ln, svr: svr, }, nil } func (c *Client) PeerListener() net.Listener { return c.l } func (c *Client) UpdateProxyConfigurer(proxyCfgs []v1.ProxyConfigurer) { _ = c.svr.UpdateAllConfigurer(proxyCfgs, nil) } func (c *Client) Run(ctx context.Context) error { return c.svr.Run(ctx) } func (c *Client) Service() *client.Service { return c.svr } func (c *Client) Close() { c.svr.Close() c.l.Close() } type pipeConnector struct { peerListener *netpkg.InternalListener } func (pc *pipeConnector) Open() error { return nil } func (pc *pipeConnector) Connect() (net.Conn, error) { c1, c2 := net.Pipe() if err := pc.peerListener.PutConn(c1); err != nil { c1.Close() c2.Close() return nil, err } return c2, nil } func (pc *pipeConnector) Close() error { pc.peerListener.Close() return nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/flags.go
pkg/config/flags.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "fmt" "strconv" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/fatedier/frp/pkg/config/types" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/config/v1/validation" ) // WordSepNormalizeFunc changes all flags that contain "_" separators func WordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { if strings.Contains(name, "_") { return pflag.NormalizedName(strings.ReplaceAll(name, "_", "-")) } return pflag.NormalizedName(name) } type RegisterFlagOption func(*registerFlagOptions) type registerFlagOptions struct { sshMode bool } func WithSSHMode() RegisterFlagOption { return func(o *registerFlagOptions) { o.sshMode = true } } type BandwidthQuantityFlag struct { V *types.BandwidthQuantity } func (f *BandwidthQuantityFlag) Set(s string) error { return f.V.UnmarshalString(s) } func (f *BandwidthQuantityFlag) String() string { return f.V.String() } func (f *BandwidthQuantityFlag) Type() string { return "string" } func RegisterProxyFlags(cmd *cobra.Command, c v1.ProxyConfigurer, opts ...RegisterFlagOption) { registerProxyBaseConfigFlags(cmd, c.GetBaseConfig(), opts...) switch cc := c.(type) { case *v1.TCPProxyConfig: cmd.Flags().IntVarP(&cc.RemotePort, "remote_port", "r", 0, "remote port") case *v1.UDPProxyConfig: cmd.Flags().IntVarP(&cc.RemotePort, "remote_port", "r", 0, "remote port") case *v1.HTTPProxyConfig: registerProxyDomainConfigFlags(cmd, &cc.DomainConfig) cmd.Flags().StringSliceVarP(&cc.Locations, "locations", "", []string{}, "locations") cmd.Flags().StringVarP(&cc.HTTPUser, "http_user", "", "", "http auth user") cmd.Flags().StringVarP(&cc.HTTPPassword, "http_pwd", "", "", "http auth password") cmd.Flags().StringVarP(&cc.HostHeaderRewrite, "host_header_rewrite", "", "", "host header rewrite") case *v1.HTTPSProxyConfig: registerProxyDomainConfigFlags(cmd, &cc.DomainConfig) case *v1.TCPMuxProxyConfig: registerProxyDomainConfigFlags(cmd, &cc.DomainConfig) cmd.Flags().StringVarP(&cc.Multiplexer, "mux", "", "", "multiplexer") cmd.Flags().StringVarP(&cc.HTTPUser, "http_user", "", "", "http auth user") cmd.Flags().StringVarP(&cc.HTTPPassword, "http_pwd", "", "", "http auth password") case *v1.STCPProxyConfig: cmd.Flags().StringVarP(&cc.Secretkey, "sk", "", "", "secret key") cmd.Flags().StringSliceVarP(&cc.AllowUsers, "allow_users", "", []string{}, "allow visitor users") case *v1.SUDPProxyConfig: cmd.Flags().StringVarP(&cc.Secretkey, "sk", "", "", "secret key") cmd.Flags().StringSliceVarP(&cc.AllowUsers, "allow_users", "", []string{}, "allow visitor users") case *v1.XTCPProxyConfig: cmd.Flags().StringVarP(&cc.Secretkey, "sk", "", "", "secret key") cmd.Flags().StringSliceVarP(&cc.AllowUsers, "allow_users", "", []string{}, "allow visitor users") } } func registerProxyBaseConfigFlags(cmd *cobra.Command, c *v1.ProxyBaseConfig, opts ...RegisterFlagOption) { if c == nil { return } options := &registerFlagOptions{} for _, opt := range opts { opt(options) } cmd.Flags().StringVarP(&c.Name, "proxy_name", "n", "", "proxy name") cmd.Flags().StringToStringVarP(&c.Metadatas, "metadatas", "", nil, "metadata key-value pairs (e.g., key1=value1,key2=value2)") cmd.Flags().StringToStringVarP(&c.Annotations, "annotations", "", nil, "annotation key-value pairs (e.g., key1=value1,key2=value2)") if !options.sshMode { cmd.Flags().StringVarP(&c.LocalIP, "local_ip", "i", "127.0.0.1", "local ip") cmd.Flags().IntVarP(&c.LocalPort, "local_port", "l", 0, "local port") cmd.Flags().BoolVarP(&c.Transport.UseEncryption, "ue", "", false, "use encryption") cmd.Flags().BoolVarP(&c.Transport.UseCompression, "uc", "", false, "use compression") cmd.Flags().StringVarP(&c.Transport.BandwidthLimitMode, "bandwidth_limit_mode", "", types.BandwidthLimitModeClient, "bandwidth limit mode") cmd.Flags().VarP(&BandwidthQuantityFlag{V: &c.Transport.BandwidthLimit}, "bandwidth_limit", "", "bandwidth limit (e.g. 100KB or 1MB)") } } func registerProxyDomainConfigFlags(cmd *cobra.Command, c *v1.DomainConfig) { if c == nil { return } cmd.Flags().StringSliceVarP(&c.CustomDomains, "custom_domain", "d", []string{}, "custom domains") cmd.Flags().StringVarP(&c.SubDomain, "sd", "", "", "sub domain") } func RegisterVisitorFlags(cmd *cobra.Command, c v1.VisitorConfigurer, opts ...RegisterFlagOption) { registerVisitorBaseConfigFlags(cmd, c.GetBaseConfig(), opts...) // add visitor flags if exist } func registerVisitorBaseConfigFlags(cmd *cobra.Command, c *v1.VisitorBaseConfig, _ ...RegisterFlagOption) { if c == nil { return } cmd.Flags().StringVarP(&c.Name, "visitor_name", "n", "", "visitor name") cmd.Flags().BoolVarP(&c.Transport.UseEncryption, "ue", "", false, "use encryption") cmd.Flags().BoolVarP(&c.Transport.UseCompression, "uc", "", false, "use compression") cmd.Flags().StringVarP(&c.SecretKey, "sk", "", "", "secret key") cmd.Flags().StringVarP(&c.ServerName, "server_name", "", "", "server name") cmd.Flags().StringVarP(&c.ServerUser, "server-user", "", "", "server user") cmd.Flags().StringVarP(&c.BindAddr, "bind_addr", "", "", "bind addr") cmd.Flags().IntVarP(&c.BindPort, "bind_port", "", 0, "bind port") } func RegisterClientCommonConfigFlags(cmd *cobra.Command, c *v1.ClientCommonConfig, opts ...RegisterFlagOption) { options := &registerFlagOptions{} for _, opt := range opts { opt(options) } if !options.sshMode { cmd.PersistentFlags().StringVarP(&c.ServerAddr, "server_addr", "s", "127.0.0.1", "frp server's address") cmd.PersistentFlags().IntVarP(&c.ServerPort, "server_port", "P", 7000, "frp server's port") cmd.PersistentFlags().StringVarP(&c.Transport.Protocol, "protocol", "p", "tcp", fmt.Sprintf("optional values are %v", validation.SupportedTransportProtocols)) cmd.PersistentFlags().StringVarP(&c.Log.Level, "log_level", "", "info", "log level") cmd.PersistentFlags().StringVarP(&c.Log.To, "log_file", "", "console", "console or file path") cmd.PersistentFlags().Int64VarP(&c.Log.MaxDays, "log_max_days", "", 3, "log file reversed days") cmd.PersistentFlags().BoolVarP(&c.Log.DisablePrintColor, "disable_log_color", "", false, "disable log color in console") cmd.PersistentFlags().StringVarP(&c.Transport.TLS.ServerName, "tls_server_name", "", "", "specify the custom server name of tls certificate") cmd.PersistentFlags().StringVarP(&c.DNSServer, "dns_server", "", "", "specify dns server instead of using system default one") c.Transport.TLS.Enable = cmd.PersistentFlags().BoolP("tls_enable", "", true, "enable frpc tls") } cmd.PersistentFlags().StringVarP(&c.User, "user", "u", "", "user") cmd.PersistentFlags().StringVarP(&c.Auth.Token, "token", "t", "", "auth token") } type PortsRangeSliceFlag struct { V *[]types.PortsRange } func (f *PortsRangeSliceFlag) String() string { if f.V == nil { return "" } return types.PortsRangeSlice(*f.V).String() } func (f *PortsRangeSliceFlag) Set(s string) error { slice, err := types.NewPortsRangeSliceFromString(s) if err != nil { return err } *f.V = slice return nil } func (f *PortsRangeSliceFlag) Type() string { return "string" } type BoolFuncFlag struct { TrueFunc func() FalseFunc func() v bool } func (f *BoolFuncFlag) String() string { return strconv.FormatBool(f.v) } func (f *BoolFuncFlag) Set(s string) error { f.v = strconv.FormatBool(f.v) == "true" if !f.v { if f.FalseFunc != nil { f.FalseFunc() } return nil } if f.TrueFunc != nil { f.TrueFunc() } return nil } func (f *BoolFuncFlag) Type() string { return "bool" } func RegisterServerConfigFlags(cmd *cobra.Command, c *v1.ServerConfig, opts ...RegisterFlagOption) { cmd.PersistentFlags().StringVarP(&c.BindAddr, "bind_addr", "", "0.0.0.0", "bind address") cmd.PersistentFlags().IntVarP(&c.BindPort, "bind_port", "p", 7000, "bind port") cmd.PersistentFlags().IntVarP(&c.KCPBindPort, "kcp_bind_port", "", 0, "kcp bind udp port") cmd.PersistentFlags().IntVarP(&c.QUICBindPort, "quic_bind_port", "", 0, "quic bind udp port") cmd.PersistentFlags().StringVarP(&c.ProxyBindAddr, "proxy_bind_addr", "", "0.0.0.0", "proxy bind address") cmd.PersistentFlags().IntVarP(&c.VhostHTTPPort, "vhost_http_port", "", 0, "vhost http port") cmd.PersistentFlags().IntVarP(&c.VhostHTTPSPort, "vhost_https_port", "", 0, "vhost https port") cmd.PersistentFlags().Int64VarP(&c.VhostHTTPTimeout, "vhost_http_timeout", "", 60, "vhost http response header timeout") cmd.PersistentFlags().StringVarP(&c.WebServer.Addr, "dashboard_addr", "", "0.0.0.0", "dashboard address") cmd.PersistentFlags().IntVarP(&c.WebServer.Port, "dashboard_port", "", 0, "dashboard port") cmd.PersistentFlags().StringVarP(&c.WebServer.User, "dashboard_user", "", "admin", "dashboard user") cmd.PersistentFlags().StringVarP(&c.WebServer.Password, "dashboard_pwd", "", "admin", "dashboard password") cmd.PersistentFlags().BoolVarP(&c.EnablePrometheus, "enable_prometheus", "", false, "enable prometheus dashboard") cmd.PersistentFlags().StringVarP(&c.Log.To, "log_file", "", "console", "log file") cmd.PersistentFlags().StringVarP(&c.Log.Level, "log_level", "", "info", "log level") cmd.PersistentFlags().Int64VarP(&c.Log.MaxDays, "log_max_days", "", 3, "log max days") cmd.PersistentFlags().BoolVarP(&c.Log.DisablePrintColor, "disable_log_color", "", false, "disable log color in console") cmd.PersistentFlags().StringVarP(&c.Auth.Token, "token", "t", "", "auth token") cmd.PersistentFlags().StringVarP(&c.SubDomainHost, "subdomain_host", "", "", "subdomain host") cmd.PersistentFlags().VarP(&PortsRangeSliceFlag{V: &c.AllowPorts}, "allow_ports", "", "allow ports") cmd.PersistentFlags().Int64VarP(&c.MaxPortsPerClient, "max_ports_per_client", "", 0, "max ports per client") cmd.PersistentFlags().BoolVarP(&c.Transport.TLS.Force, "tls_only", "", false, "frps tls only") webServerTLS := v1.TLSConfig{} cmd.PersistentFlags().StringVarP(&webServerTLS.CertFile, "dashboard_tls_cert_file", "", "", "dashboard tls cert file") cmd.PersistentFlags().StringVarP(&webServerTLS.KeyFile, "dashboard_tls_key_file", "", "", "dashboard tls key file") cmd.PersistentFlags().VarP(&BoolFuncFlag{ TrueFunc: func() { c.WebServer.TLS = &webServerTLS }, }, "dashboard_tls_mode", "", "if enable dashboard tls mode") }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/load.go
pkg/config/load.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "bytes" "encoding/json" "fmt" "os" "path/filepath" "strings" "text/template" toml "github.com/pelletier/go-toml/v2" "github.com/samber/lo" "gopkg.in/ini.v1" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/yaml" "github.com/fatedier/frp/pkg/config/legacy" v1 "github.com/fatedier/frp/pkg/config/v1" "github.com/fatedier/frp/pkg/config/v1/validation" "github.com/fatedier/frp/pkg/msg" "github.com/fatedier/frp/pkg/util/util" ) var glbEnvs map[string]string func init() { glbEnvs = make(map[string]string) envs := os.Environ() for _, env := range envs { pair := strings.SplitN(env, "=", 2) if len(pair) != 2 { continue } glbEnvs[pair[0]] = pair[1] } } type Values struct { Envs map[string]string // environment vars } func GetValues() *Values { return &Values{ Envs: glbEnvs, } } func DetectLegacyINIFormat(content []byte) bool { f, err := ini.Load(content) if err != nil { return false } if _, err := f.GetSection("common"); err == nil { return true } return false } func DetectLegacyINIFormatFromFile(path string) bool { b, err := os.ReadFile(path) if err != nil { return false } return DetectLegacyINIFormat(b) } func RenderWithTemplate(in []byte, values *Values) ([]byte, error) { tmpl, err := template.New("frp").Funcs(template.FuncMap{ "parseNumberRange": parseNumberRange, "parseNumberRangePair": parseNumberRangePair, }).Parse(string(in)) if err != nil { return nil, err } buffer := bytes.NewBufferString("") if err := tmpl.Execute(buffer, values); err != nil { return nil, err } return buffer.Bytes(), nil } func LoadFileContentWithTemplate(path string, values *Values) ([]byte, error) { b, err := os.ReadFile(path) if err != nil { return nil, err } return RenderWithTemplate(b, values) } func LoadConfigureFromFile(path string, c any, strict bool) error { content, err := LoadFileContentWithTemplate(path, GetValues()) if err != nil { return err } return LoadConfigure(content, c, strict) } // parseYAMLWithDotFieldsHandling parses YAML with dot-prefixed fields handling // This function handles both cases efficiently: with or without dot fields func parseYAMLWithDotFieldsHandling(content []byte, target any) error { var temp any if err := yaml.Unmarshal(content, &temp); err != nil { return err } // Remove dot fields if it's a map if tempMap, ok := temp.(map[string]any); ok { for key := range tempMap { if strings.HasPrefix(key, ".") { delete(tempMap, key) } } } // Convert to JSON and decode with strict validation jsonBytes, err := json.Marshal(temp) if err != nil { return err } decoder := json.NewDecoder(bytes.NewReader(jsonBytes)) decoder.DisallowUnknownFields() return decoder.Decode(target) } // LoadConfigure loads configuration from bytes and unmarshal into c. // Now it supports json, yaml and toml format. func LoadConfigure(b []byte, c any, strict bool) error { v1.DisallowUnknownFieldsMu.Lock() defer v1.DisallowUnknownFieldsMu.Unlock() v1.DisallowUnknownFields = strict var tomlObj any // Try to unmarshal as TOML first; swallow errors from that (assume it's not valid TOML). if err := toml.Unmarshal(b, &tomlObj); err == nil { b, err = json.Marshal(&tomlObj) if err != nil { return err } } // If the buffer smells like JSON (first non-whitespace character is '{'), unmarshal as JSON directly. if yaml.IsJSONBuffer(b) { decoder := json.NewDecoder(bytes.NewBuffer(b)) if strict { decoder.DisallowUnknownFields() } return decoder.Decode(c) } // Handle YAML content if strict { // In strict mode, always use our custom handler to support YAML merge return parseYAMLWithDotFieldsHandling(b, c) } // Non-strict mode, parse normally return yaml.Unmarshal(b, c) } func NewProxyConfigurerFromMsg(m *msg.NewProxy, serverCfg *v1.ServerConfig) (v1.ProxyConfigurer, error) { m.ProxyType = util.EmptyOr(m.ProxyType, string(v1.ProxyTypeTCP)) configurer := v1.NewProxyConfigurerByType(v1.ProxyType(m.ProxyType)) if configurer == nil { return nil, fmt.Errorf("unknown proxy type: %s", m.ProxyType) } configurer.UnmarshalFromMsg(m) configurer.Complete("") if err := validation.ValidateProxyConfigurerForServer(configurer, serverCfg); err != nil { return nil, err } return configurer, nil } func LoadServerConfig(path string, strict bool) (*v1.ServerConfig, bool, error) { var ( svrCfg *v1.ServerConfig isLegacyFormat bool ) // detect legacy ini format if DetectLegacyINIFormatFromFile(path) { content, err := legacy.GetRenderedConfFromFile(path) if err != nil { return nil, true, err } legacyCfg, err := legacy.UnmarshalServerConfFromIni(content) if err != nil { return nil, true, err } svrCfg = legacy.Convert_ServerCommonConf_To_v1(&legacyCfg) isLegacyFormat = true } else { svrCfg = &v1.ServerConfig{} if err := LoadConfigureFromFile(path, svrCfg, strict); err != nil { return nil, false, err } } if svrCfg != nil { if err := svrCfg.Complete(); err != nil { return nil, isLegacyFormat, err } } return svrCfg, isLegacyFormat, nil } func LoadClientConfig(path string, strict bool) ( *v1.ClientCommonConfig, []v1.ProxyConfigurer, []v1.VisitorConfigurer, bool, error, ) { var ( cliCfg *v1.ClientCommonConfig proxyCfgs = make([]v1.ProxyConfigurer, 0) visitorCfgs = make([]v1.VisitorConfigurer, 0) isLegacyFormat bool ) if DetectLegacyINIFormatFromFile(path) { legacyCommon, legacyProxyCfgs, legacyVisitorCfgs, err := legacy.ParseClientConfig(path) if err != nil { return nil, nil, nil, true, err } cliCfg = legacy.Convert_ClientCommonConf_To_v1(&legacyCommon) for _, c := range legacyProxyCfgs { proxyCfgs = append(proxyCfgs, legacy.Convert_ProxyConf_To_v1(c)) } for _, c := range legacyVisitorCfgs { visitorCfgs = append(visitorCfgs, legacy.Convert_VisitorConf_To_v1(c)) } isLegacyFormat = true } else { allCfg := v1.ClientConfig{} if err := LoadConfigureFromFile(path, &allCfg, strict); err != nil { return nil, nil, nil, false, err } cliCfg = &allCfg.ClientCommonConfig for _, c := range allCfg.Proxies { proxyCfgs = append(proxyCfgs, c.ProxyConfigurer) } for _, c := range allCfg.Visitors { visitorCfgs = append(visitorCfgs, c.VisitorConfigurer) } } // Load additional config from includes. // legacy ini format already handle this in ParseClientConfig. if len(cliCfg.IncludeConfigFiles) > 0 && !isLegacyFormat { extProxyCfgs, extVisitorCfgs, err := LoadAdditionalClientConfigs(cliCfg.IncludeConfigFiles, isLegacyFormat, strict) if err != nil { return nil, nil, nil, isLegacyFormat, err } proxyCfgs = append(proxyCfgs, extProxyCfgs...) visitorCfgs = append(visitorCfgs, extVisitorCfgs...) } // Filter by start if len(cliCfg.Start) > 0 { startSet := sets.New(cliCfg.Start...) proxyCfgs = lo.Filter(proxyCfgs, func(c v1.ProxyConfigurer, _ int) bool { return startSet.Has(c.GetBaseConfig().Name) }) visitorCfgs = lo.Filter(visitorCfgs, func(c v1.VisitorConfigurer, _ int) bool { return startSet.Has(c.GetBaseConfig().Name) }) } // Filter by enabled field in each proxy // nil or true means enabled, false means disabled proxyCfgs = lo.Filter(proxyCfgs, func(c v1.ProxyConfigurer, _ int) bool { enabled := c.GetBaseConfig().Enabled return enabled == nil || *enabled }) visitorCfgs = lo.Filter(visitorCfgs, func(c v1.VisitorConfigurer, _ int) bool { enabled := c.GetBaseConfig().Enabled return enabled == nil || *enabled }) if cliCfg != nil { if err := cliCfg.Complete(); err != nil { return nil, nil, nil, isLegacyFormat, err } } for _, c := range proxyCfgs { c.Complete(cliCfg.User) } for _, c := range visitorCfgs { c.Complete(cliCfg) } return cliCfg, proxyCfgs, visitorCfgs, isLegacyFormat, nil } func LoadAdditionalClientConfigs(paths []string, isLegacyFormat bool, strict bool) ([]v1.ProxyConfigurer, []v1.VisitorConfigurer, error) { proxyCfgs := make([]v1.ProxyConfigurer, 0) visitorCfgs := make([]v1.VisitorConfigurer, 0) for _, path := range paths { absDir, err := filepath.Abs(filepath.Dir(path)) if err != nil { return nil, nil, err } if _, err := os.Stat(absDir); os.IsNotExist(err) { return nil, nil, err } files, err := os.ReadDir(absDir) if err != nil { return nil, nil, err } for _, fi := range files { if fi.IsDir() { continue } absFile := filepath.Join(absDir, fi.Name()) if matched, _ := filepath.Match(filepath.Join(absDir, filepath.Base(path)), absFile); matched { // support yaml/json/toml cfg := v1.ClientConfig{} if err := LoadConfigureFromFile(absFile, &cfg, strict); err != nil { return nil, nil, fmt.Errorf("load additional config from %s error: %v", absFile, err) } for _, c := range cfg.Proxies { proxyCfgs = append(proxyCfgs, c.ProxyConfigurer) } for _, c := range cfg.Visitors { visitorCfgs = append(visitorCfgs, c.VisitorConfigurer) } } } } return proxyCfgs, visitorCfgs, nil }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/load_test.go
pkg/config/load_test.go
// Copyright 2023 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "fmt" "strings" "testing" "github.com/stretchr/testify/require" v1 "github.com/fatedier/frp/pkg/config/v1" ) const tomlServerContent = ` bindAddr = "127.0.0.1" kcpBindPort = 7000 quicBindPort = 7001 tcpmuxHTTPConnectPort = 7005 custom404Page = "/abc.html" transport.tcpKeepalive = 10 ` const yamlServerContent = ` bindAddr: 127.0.0.1 kcpBindPort: 7000 quicBindPort: 7001 tcpmuxHTTPConnectPort: 7005 custom404Page: /abc.html transport: tcpKeepalive: 10 ` const jsonServerContent = ` { "bindAddr": "127.0.0.1", "kcpBindPort": 7000, "quicBindPort": 7001, "tcpmuxHTTPConnectPort": 7005, "custom404Page": "/abc.html", "transport": { "tcpKeepalive": 10 } } ` func TestLoadServerConfig(t *testing.T) { tests := []struct { name string content string }{ {"toml", tomlServerContent}, {"yaml", yamlServerContent}, {"json", jsonServerContent}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) svrCfg := v1.ServerConfig{} err := LoadConfigure([]byte(test.content), &svrCfg, true) require.NoError(err) require.EqualValues("127.0.0.1", svrCfg.BindAddr) require.EqualValues(7000, svrCfg.KCPBindPort) require.EqualValues(7001, svrCfg.QUICBindPort) require.EqualValues(7005, svrCfg.TCPMuxHTTPConnectPort) require.EqualValues("/abc.html", svrCfg.Custom404Page) require.EqualValues(10, svrCfg.Transport.TCPKeepAlive) }) } } // Test that loading in strict mode fails when the config is invalid. func TestLoadServerConfigStrictMode(t *testing.T) { tests := []struct { name string content string }{ {"toml", tomlServerContent}, {"yaml", yamlServerContent}, {"json", jsonServerContent}, } for _, strict := range []bool{false, true} { for _, test := range tests { t.Run(fmt.Sprintf("%s-strict-%t", test.name, strict), func(t *testing.T) { require := require.New(t) // Break the content with an innocent typo brokenContent := strings.Replace(test.content, "bindAddr", "bindAdur", 1) svrCfg := v1.ServerConfig{} err := LoadConfigure([]byte(brokenContent), &svrCfg, strict) if strict { require.ErrorContains(err, "bindAdur") } else { require.NoError(err) // BindAddr didn't get parsed because of the typo. require.EqualValues("", svrCfg.BindAddr) } }) } } } func TestRenderWithTemplate(t *testing.T) { tests := []struct { name string content string want string }{ {"toml", tomlServerContent, tomlServerContent}, {"yaml", yamlServerContent, yamlServerContent}, {"json", jsonServerContent, jsonServerContent}, {"template numeric", `key = {{ 123 }}`, "key = 123"}, {"template string", `key = {{ "xyz" }}`, "key = xyz"}, {"template quote", `key = {{ printf "%q" "with space" }}`, `key = "with space"`}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) got, err := RenderWithTemplate([]byte(test.content), nil) require.NoError(err) require.EqualValues(test.want, string(got)) }) } } func TestCustomStructStrictMode(t *testing.T) { require := require.New(t) proxyStr := ` serverPort = 7000 [[proxies]] name = "test" type = "tcp" remotePort = 6000 ` clientCfg := v1.ClientConfig{} err := LoadConfigure([]byte(proxyStr), &clientCfg, true) require.NoError(err) proxyStr += `unknown = "unknown"` err = LoadConfigure([]byte(proxyStr), &clientCfg, true) require.Error(err) visitorStr := ` serverPort = 7000 [[visitors]] name = "test" type = "stcp" bindPort = 6000 serverName = "server" ` err = LoadConfigure([]byte(visitorStr), &clientCfg, true) require.NoError(err) visitorStr += `unknown = "unknown"` err = LoadConfigure([]byte(visitorStr), &clientCfg, true) require.Error(err) pluginStr := ` serverPort = 7000 [[proxies]] name = "test" type = "tcp" remotePort = 6000 [proxies.plugin] type = "unix_domain_socket" unixPath = "/tmp/uds.sock" ` err = LoadConfigure([]byte(pluginStr), &clientCfg, true) require.NoError(err) pluginStr += `unknown = "unknown"` err = LoadConfigure([]byte(pluginStr), &clientCfg, true) require.Error(err) } // TestYAMLMergeInStrictMode tests that YAML merge functionality works // even in strict mode by properly handling dot-prefixed fields func TestYAMLMergeInStrictMode(t *testing.T) { require := require.New(t) yamlContent := ` serverAddr: "127.0.0.1" serverPort: 7000 .common: &common type: stcp secretKey: "test-secret" localIP: 127.0.0.1 transport: useEncryption: true useCompression: true proxies: - name: ssh localPort: 22 <<: *common - name: web localPort: 80 <<: *common ` clientCfg := v1.ClientConfig{} // This should work in strict mode err := LoadConfigure([]byte(yamlContent), &clientCfg, true) require.NoError(err) // Verify the merge worked correctly require.Equal("127.0.0.1", clientCfg.ServerAddr) require.Equal(7000, clientCfg.ServerPort) require.Len(clientCfg.Proxies, 2) // Check first proxy sshProxy := clientCfg.Proxies[0].ProxyConfigurer require.Equal("ssh", sshProxy.GetBaseConfig().Name) require.Equal("stcp", sshProxy.GetBaseConfig().Type) // Check second proxy webProxy := clientCfg.Proxies[1].ProxyConfigurer require.Equal("web", webProxy.GetBaseConfig().Name) require.Equal("stcp", webProxy.GetBaseConfig().Type) } // TestOptimizedYAMLProcessing tests the optimization logic for YAML processing func TestOptimizedYAMLProcessing(t *testing.T) { require := require.New(t) yamlWithDotFields := []byte(` serverAddr: "127.0.0.1" .common: &common type: stcp proxies: - name: test <<: *common `) yamlWithoutDotFields := []byte(` serverAddr: "127.0.0.1" proxies: - name: test type: tcp localPort: 22 `) // Test that YAML without dot fields works in strict mode clientCfg := v1.ClientConfig{} err := LoadConfigure(yamlWithoutDotFields, &clientCfg, true) require.NoError(err) require.Equal("127.0.0.1", clientCfg.ServerAddr) require.Len(clientCfg.Proxies, 1) require.Equal("test", clientCfg.Proxies[0].ProxyConfigurer.GetBaseConfig().Name) // Test that YAML with dot fields still works in strict mode err = LoadConfigure(yamlWithDotFields, &clientCfg, true) require.NoError(err) require.Equal("127.0.0.1", clientCfg.ServerAddr) require.Len(clientCfg.Proxies, 1) require.Equal("test", clientCfg.Proxies[0].ProxyConfigurer.GetBaseConfig().Name) require.Equal("stcp", clientCfg.Proxies[0].ProxyConfigurer.GetBaseConfig().Type) } // TestYAMLEdgeCases tests edge cases for YAML parsing, including non-map types func TestYAMLEdgeCases(t *testing.T) { require := require.New(t) // Test array at root (should fail for frp config) arrayYAML := []byte(` - item1 - item2 `) clientCfg := v1.ClientConfig{} err := LoadConfigure(arrayYAML, &clientCfg, true) require.Error(err) // Should fail because ClientConfig expects an object // Test scalar at root (should fail for frp config) scalarYAML := []byte(`"just a string"`) err = LoadConfigure(scalarYAML, &clientCfg, true) require.Error(err) // Should fail because ClientConfig expects an object // Test empty object (should work) emptyYAML := []byte(`{}`) err = LoadConfigure(emptyYAML, &clientCfg, true) require.NoError(err) // Test nested structure without dots (should work) nestedYAML := []byte(` serverAddr: "127.0.0.1" serverPort: 7000 `) err = LoadConfigure(nestedYAML, &clientCfg, true) require.NoError(err) require.Equal("127.0.0.1", clientCfg.ServerAddr) require.Equal(7000, clientCfg.ServerPort) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/template.go
pkg/config/template.go
// Copyright 2024 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package config import ( "fmt" "github.com/fatedier/frp/pkg/util/util" ) type NumberPair struct { First int64 Second int64 } func parseNumberRangePair(firstRangeStr, secondRangeStr string) ([]NumberPair, error) { firstRangeNumbers, err := util.ParseRangeNumbers(firstRangeStr) if err != nil { return nil, err } secondRangeNumbers, err := util.ParseRangeNumbers(secondRangeStr) if err != nil { return nil, err } if len(firstRangeNumbers) != len(secondRangeNumbers) { return nil, fmt.Errorf("first and second range numbers are not in pairs") } pairs := make([]NumberPair, 0, len(firstRangeNumbers)) for i := 0; i < len(firstRangeNumbers); i++ { pairs = append(pairs, NumberPair{ First: firstRangeNumbers[i], Second: secondRangeNumbers[i], }) } return pairs, nil } func parseNumberRange(firstRangeStr string) ([]int64, error) { return util.ParseRangeNumbers(firstRangeStr) }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false
fatedier/frp
https://github.com/fatedier/frp/blob/33428ab538b7c55d46c70e2f04cc153f2400cd5b/pkg/config/v1/value_source_test.go
pkg/config/v1/value_source_test.go
// Copyright 2025 The frp Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v1 import ( "context" "os" "path/filepath" "testing" ) func TestValueSource_Validate(t *testing.T) { tests := []struct { name string vs *ValueSource wantErr bool }{ { name: "nil valueSource", vs: nil, wantErr: true, }, { name: "unsupported type", vs: &ValueSource{ Type: "unsupported", }, wantErr: true, }, { name: "file type without file config", vs: &ValueSource{ Type: "file", File: nil, }, wantErr: true, }, { name: "valid file type with absolute path", vs: &ValueSource{ Type: "file", File: &FileSource{ Path: "/tmp/test", }, }, wantErr: false, }, { name: "valid file type with relative path", vs: &ValueSource{ Type: "file", File: &FileSource{ Path: "configs/token", }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.vs.Validate() if (err != nil) != tt.wantErr { t.Errorf("ValueSource.Validate() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestFileSource_Validate(t *testing.T) { tests := []struct { name string fs *FileSource wantErr bool }{ { name: "nil fileSource", fs: nil, wantErr: true, }, { name: "empty path", fs: &FileSource{ Path: "", }, wantErr: true, }, { name: "relative path (allowed)", fs: &FileSource{ Path: "relative/path", }, wantErr: false, }, { name: "absolute path", fs: &FileSource{ Path: "/absolute/path", }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.fs.Validate() if (err != nil) != tt.wantErr { t.Errorf("FileSource.Validate() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestFileSource_Resolve(t *testing.T) { // Create a temporary file for testing tmpDir := t.TempDir() testFile := filepath.Join(tmpDir, "test_token") testContent := "test-token-value\n\t " expectedContent := "test-token-value" err := os.WriteFile(testFile, []byte(testContent), 0o600) if err != nil { t.Fatalf("failed to create test file: %v", err) } tests := []struct { name string fs *FileSource want string wantErr bool }{ { name: "valid file path", fs: &FileSource{ Path: testFile, }, want: expectedContent, wantErr: false, }, { name: "non-existent file", fs: &FileSource{ Path: "/non/existent/file", }, want: "", wantErr: true, }, { name: "path traversal attempt (should fail validation)", fs: &FileSource{ Path: "../../../etc/passwd", }, want: "", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.fs.Resolve(context.Background()) if (err != nil) != tt.wantErr { t.Errorf("FileSource.Resolve() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("FileSource.Resolve() = %v, want %v", got, tt.want) } }) } } func TestValueSource_Resolve(t *testing.T) { // Create a temporary file for testing tmpDir := t.TempDir() testFile := filepath.Join(tmpDir, "test_token") testContent := "test-token-value" err := os.WriteFile(testFile, []byte(testContent), 0o600) if err != nil { t.Fatalf("failed to create test file: %v", err) } tests := []struct { name string vs *ValueSource want string wantErr bool }{ { name: "valid file type", vs: &ValueSource{ Type: "file", File: &FileSource{ Path: testFile, }, }, want: testContent, wantErr: false, }, { name: "unsupported type", vs: &ValueSource{ Type: "unsupported", }, want: "", wantErr: true, }, { name: "file type with path traversal", vs: &ValueSource{ Type: "file", File: &FileSource{ Path: "../../../etc/passwd", }, }, want: "", wantErr: true, }, } ctx := context.Background() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.vs.Resolve(ctx) if (err != nil) != tt.wantErr { t.Errorf("ValueSource.Resolve() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("ValueSource.Resolve() = %v, want %v", got, tt.want) } }) } }
go
Apache-2.0
33428ab538b7c55d46c70e2f04cc153f2400cd5b
2026-01-07T08:35:43.420197Z
false