general code qualitity and readability. Mostlly no functional changes besides fixing potential null dereferece in SAM.go, avoiding potential (again) infitite loop in util.go.

This commit is contained in:
urgentquest
2025-04-07 23:48:02 +00:00
parent 7c5ff30a30
commit 477796de71
9 changed files with 35 additions and 88 deletions

View File

@ -226,6 +226,9 @@ func (sam *SAM) NewGenericSessionWithSignatureAndPorts(style, id, from, to strin
// close this sam session
func (sam *SAM) Close() error {
log.Debug("Closing SAM session")
return sam.Conn.Close()
if sam.Conn != nil {
log.Debug("Closing SAM session")
return sam.Conn.Close()
}
return nil
}

View File

@ -237,9 +237,9 @@ func (f *I2PConfig) SignatureType() string {
// EncryptLease returns the lease set encryption configuration string
// Returns "i2cp.encryptLeaseSet=true" if encryption is enabled, empty string otherwise
func (f *I2PConfig) EncryptLease() string {
if f.EncryptLeaseSet == true {
if f.EncryptLeaseSet {
log.Debug("Lease set encryption enabled")
return fmt.Sprintf(" i2cp.encryptLeaseSet=true ")
return " i2cp.encryptLeaseSet=true "
}
log.Debug("Lease set encryption not enabled")
return ""
@ -262,7 +262,7 @@ func (f *I2PConfig) Reliability() string {
// Reduce returns I2CP reduce-on-idle configuration settings as a string if enabled
func (f *I2PConfig) Reduce() string {
// If reduce idle is enabled, return formatted configuration string
if f.ReduceIdle == true {
if f.ReduceIdle {
// Log the reduce idle settings being applied
log.WithFields(logrus.Fields{
"reduceIdle": f.ReduceIdle,
@ -287,7 +287,7 @@ func (f *I2PConfig) Reduce() string {
// Close returns I2CP close-on-idle configuration settings as a string if enabled
func (f *I2PConfig) Close() string {
// If close idle is enabled, return formatted configuration string
if f.CloseIdle == true {
if f.CloseIdle {
// Log the close idle settings being applied
log.WithFields(logrus.Fields{
"closeIdle": f.CloseIdle,
@ -312,17 +312,17 @@ func (f *I2PConfig) DoZero() string {
var settings []string
// Add inbound zero hop setting if enabled
if f.InAllowZeroHop == true {
if f.InAllowZeroHop {
settings = append(settings, fmt.Sprintf("inbound.allowZeroHop=%t", f.InAllowZeroHop))
}
// Add outbound zero hop setting if enabled
if f.OutAllowZeroHop == true {
if f.OutAllowZeroHop {
settings = append(settings, fmt.Sprintf("outbound.allowZeroHop=%t", f.OutAllowZeroHop))
}
// Add fast receive setting if enabled
if f.FastRecieve == true {
if f.FastRecieve {
settings = append(settings, fmt.Sprintf("i2cp.fastRecieve=%t", f.FastRecieve))
}
@ -406,10 +406,10 @@ func (f *I2PConfig) Accesslisttype() string {
switch f.AccessListType {
case ACCESS_TYPE_WHITELIST:
log.Debug("Access list type set to whitelist")
return fmt.Sprintf("i2cp.enableAccessList=true")
return "i2cp.enableAccessList=true"
case ACCESS_TYPE_BLACKLIST:
log.Debug("Access list type set to blacklist")
return fmt.Sprintf("i2cp.enableBlackList=true")
return "i2cp.enableBlackList=true"
case ACCESS_TYPE_NONE:
log.Debug("Access list type set to none")
return ""
@ -469,7 +469,7 @@ func NewConfig(opts ...func(*I2PConfig) error) (*I2PConfig, error) {
config.SamMax = DEFAULT_SAM_MAX
config.TunName = ""
config.TunType = "server"
config.Style = "STREAM"
config.Style = SESSION_STYLE_STREAM
config.InLength = 3
config.OutLength = 3
config.InQuantity = 2

View File

@ -14,15 +14,9 @@ type Option func(*SAMEmit) error
// SetType sets the type of the forwarder server
func SetType(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if s == SESSION_STYLE_STREAM {
c.Style = s
log.WithField("style", s).Debug("Set session style")
return nil
} else if s == SESSION_STYLE_DATAGRAM {
c.Style = s
log.WithField("style", s).Debug("Set session style")
return nil
} else if s == SESSION_STYLE_RAW {
if s == SESSION_STYLE_STREAM ||
s == SESSION_STYLE_DATAGRAM ||
s == SESSION_STYLE_RAW {
c.Style = s
log.WithField("style", s).Debug("Set session style")
return nil

View File

@ -1,6 +1,7 @@
package common
import (
"fmt"
"math/rand"
"net"
"strconv"
@ -76,8 +77,9 @@ var (
randGen = rand.New(randSource)
)
func RandPort() string {
for {
func RandPort() (portNumber string, err error) {
maxAttempts := 30
for range maxAttempts {
p := randGen.Intn(55534) + 10000
port := strconv.Itoa(p)
if l, e := net.Listen("tcp", net.JoinHostPort("localhost", port)); e != nil {
@ -88,8 +90,10 @@ func RandPort() string {
continue
} else {
defer l.Close()
return strconv.Itoa(l.Addr().(*net.UDPAddr).Port)
return strconv.Itoa(l.Addr().(*net.UDPAddr).Port), nil
}
}
}
return "", fmt.Errorf("unable to find a pair of available tcp and udp ports in %v attempts", maxAttempts)
}

View File

@ -16,11 +16,11 @@ func NewConfig(opts ...func(*I2PConfig) error) (*I2PConfig, error) {
var config I2PConfig
config.SamHost = "127.0.0.1"
config.SamPort = 7656
config.SamMin = "3.0"
config.SamMax = "3.2"
config.SamMin = common.DEFAULT_SAM_MIN
config.SamMax = common.DEFAULT_SAM_MAX
config.TunName = ""
config.TunType = "server"
config.Style = "STREAM"
config.Style = common.SESSION_STYLE_STREAM
config.InLength = 3
config.OutLength = 3
config.InQuantity = 2

49
log.go
View File

@ -1,52 +1,11 @@
// package sam3 wraps the original sam3 API from github.com/go-i2p/sam3
package sam3
import (
"io"
"os"
"strings"
"sync"
import "github.com/go-i2p/go-sam-go/logger"
"github.com/sirupsen/logrus"
)
var (
log *logrus.Logger
once sync.Once
)
func InitializeSAM3Logger() {
once.Do(func() {
log = logrus.New()
// We do not want to log by default
log.SetOutput(io.Discard)
log.SetLevel(logrus.PanicLevel)
// Check if DEBUG_I2P is set
if logLevel := os.Getenv("DEBUG_I2P"); logLevel != "" {
log.SetOutput(os.Stdout)
switch strings.ToLower(logLevel) {
case "debug":
log.SetLevel(logrus.DebugLevel)
case "warn":
log.SetLevel(logrus.WarnLevel)
case "error":
log.SetLevel(logrus.ErrorLevel)
default:
log.SetLevel(logrus.DebugLevel)
}
log.WithField("level", log.GetLevel()).Debug("Logging enabled.")
}
})
}
// GetSAM3Logger returns the initialized logger
func GetSAM3Logger() *logrus.Logger {
if log == nil {
InitializeSAM3Logger()
}
return log
}
var log = logger.GetSAM3Logger()
func init() {
InitializeSAM3Logger()
logger.InitializeSAM3Logger()
log = logger.GetSAM3Logger()
}

View File

@ -29,8 +29,6 @@ func (sam *PrimarySession) NewUniqueStreamSubSession(id string) (*stream.StreamS
log.WithError(err).Error("Failed to create new generic sub-session")
return nil, err
}
fromPort, toPort := common.RandPort(), common.RandPort()
log.WithFields(logrus.Fields{"fromPort": fromPort, "toPort": toPort}).Debug("Generated random ports")
return newFromPrimary(sam, conn), nil
}

16
sam3.go
View File

@ -17,11 +17,11 @@ type SAM struct {
}
// Creates a new stream session by wrapping stream.NewStreamSession
func (s *SAM) NewStreamSession(param1 string, keys i2pkeys.I2PKeys, param3 []string) (*StreamSession, error) {
func (s *SAM) NewStreamSession(id string, keys i2pkeys.I2PKeys, options []string) (*StreamSession, error) {
sam := &stream.SAM{
SAM: s.SAM,
}
ss, err := sam.NewStreamSession(param1, keys, param3)
ss, err := sam.NewStreamSession(id, keys, options)
if err != nil {
return nil, err
}
@ -56,18 +56,8 @@ func (s *SAM) NewPrimarySession(id string, keys i2pkeys.I2PKeys, options []strin
return &primarySession, nil
}
const (
Sig_NONE = "SIGNATURE_TYPE=EdDSA_SHA512_Ed25519"
Sig_DSA_SHA1 = "SIGNATURE_TYPE=DSA_SHA1"
Sig_ECDSA_SHA256_P256 = "SIGNATURE_TYPE=ECDSA_SHA256_P256"
Sig_ECDSA_SHA384_P384 = "SIGNATURE_TYPE=ECDSA_SHA384_P384"
Sig_ECDSA_SHA512_P521 = "SIGNATURE_TYPE=ECDSA_SHA512_P521"
Sig_EdDSA_SHA512_Ed25519 = "SIGNATURE_TYPE=EdDSA_SHA512_Ed25519"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandString() string {
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
n := 4
b := make([]rune, n)
for i := range b {

View File

@ -76,7 +76,6 @@ var (
)
func getEnv(key, fallback string) string {
InitializeSAM3Logger()
value, ok := os.LookupEnv(key)
if !ok {
log.WithFields(logrus.Fields{