use Sprintf instead of concatenation for command

This commit is contained in:
eyedeekay
2024-11-22 18:48:09 -05:00
parent 88786afa0c
commit a22cde30eb
15 changed files with 94 additions and 65 deletions

View File

@ -2,12 +2,13 @@ package sam3
import (
"fmt"
"github.com/sirupsen/logrus"
"math/rand"
"net"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"github.com/go-i2p/i2pkeys"
)
@ -54,7 +55,7 @@ type I2PConfig struct {
ReduceIdleQuantity string
LeaseSetEncryption string
//Streaming Library options
// Streaming Library options
AccessListType string
AccessList []string
}
@ -264,10 +265,11 @@ func (f *I2PConfig) DoZero() string {
log.WithField("zeroHopSettings", r).Debug("Zero hop settings applied")
return r
}
func (f *I2PConfig) Print() []string {
lsk, lspk, lspsk := f.Leasesetsettings()
return []string{
//f.targetForPort443(),
// f.targetForPort443(),
"inbound.length=" + f.InLength,
"outbound.length=" + f.OutLength,
"inbound.lengthVariance=" + f.InVariance,
@ -326,7 +328,7 @@ func (f *I2PConfig) LeaseSetEncryptionType() string {
for _, s := range strings.Split(f.LeaseSetEncryption, ",") {
if _, err := strconv.Atoi(s); err != nil {
log.WithField("invalidType", s).Panic("Invalid encrypted leaseSet type")
//panic("Invalid encrypted leaseSet type: " + s)
// panic("Invalid encrypted leaseSet type: " + s)
}
}
log.WithField("leaseSetEncType", f.LeaseSetEncryption).Debug("Lease set encryption type set")

View File

@ -127,7 +127,7 @@ func ExampleDatagramSession() {
return
// Output:
//Got message: Hello myself!
// Got message: Hello myself!
}
func ExampleMiniDatagramSession() {
@ -178,5 +178,5 @@ func ExampleMiniDatagramSession() {
return
// Output:
//Got message: Hello myself!
// Got message: Hello myself!
}

View File

@ -2,9 +2,10 @@ package sam3
import (
"fmt"
"github.com/sirupsen/logrus"
"strconv"
"strings"
"github.com/sirupsen/logrus"
)
// Option is a SAMEmit Option

17
emit.go
View File

@ -2,9 +2,10 @@ package sam3
import (
"fmt"
"github.com/sirupsen/logrus"
"net"
"strings"
"github.com/sirupsen/logrus"
)
type SAMEmit struct {
@ -51,13 +52,13 @@ func (e *SAMEmit) Create() string {
create := fmt.Sprintf(
// //1 2 3 4 5 6 7
"SESSION CREATE %s%s%s%s%s%s%s \n",
e.I2PConfig.SessionStyle(), //1
e.I2PConfig.FromPort(), //2
e.I2PConfig.ToPort(), //3
e.I2PConfig.ID(), //4
e.I2PConfig.DestinationKey(), //5
e.I2PConfig.SignatureType(), //6
e.OptStr(), //7
e.I2PConfig.SessionStyle(), // 1
e.I2PConfig.FromPort(), // 2
e.I2PConfig.ToPort(), // 3
e.I2PConfig.ID(), // 4
e.I2PConfig.DestinationKey(), // 5
e.I2PConfig.SignatureType(), // 6
e.OptStr(), // 7
)
log.WithField("create", create).Debug("Generated SESSION CREATE command")
return create

6
log.go
View File

@ -4,9 +4,7 @@ import (
logger "github.com/go-i2p/logger"
)
var (
log *logger.Logger
)
var log *logger.Logger
func InitializeSAM3Logger() {
logger.InitializeGoI2PLogger()
@ -19,5 +17,5 @@ func GetSAM3Logger() *logger.Logger {
}
func init() {
InitializeSAM3Logger()
InitializeSAM3Logger()
}

View File

@ -3,13 +3,14 @@ package sam3
import (
"errors"
"fmt"
"github.com/sirupsen/logrus"
"math/rand"
"net"
"strconv"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/go-i2p/i2pkeys"
)
@ -81,11 +82,11 @@ func (ss *PrimarySession) Keys() i2pkeys.I2PKeys {
func (sam *PrimarySession) Dial(network, addr string) (net.Conn, error) {
log.WithFields(logrus.Fields{"network": network, "addr": addr}).Debug("Dial() called")
if network == "udp" || network == "udp4" || network == "udp6" {
//return sam.DialUDPI2P(network, network+addr[0:4], addr)
// return sam.DialUDPI2P(network, network+addr[0:4], addr)
return sam.DialUDPI2P(network, network+addr[0:4], addr)
}
if network == "tcp" || network == "tcp4" || network == "tcp6" {
//return sam.DialTCPI2P(network, network+addr[0:4], addr)
// return sam.DialTCPI2P(network, network+addr[0:4], addr)
return sam.DialTCPI2P(network, network+addr[0:4], addr)
}
log.WithField("network", network).Error("Invalid network type")
@ -289,7 +290,7 @@ func (sam *PrimarySession) newGenericSubSessionWithSignatureAndPorts(style, id,
}
text := string(buf[:n])
log.WithField("response", text).Debug("Received response from SAM")
//log.Println("SAM:", text)
// log.Println("SAM:", text)
if strings.HasPrefix(text, session_ADDOK) {
//if sam.keys.String() != text[len(session_ADDOK):len(text)-1] {
//conn.Close()
@ -343,7 +344,7 @@ func (sam *PrimarySession) NewUniqueStreamSubSession(id string) (*StreamSession,
}
fromPort, toPort := randport(), randport()
log.WithFields(logrus.Fields{"fromPort": fromPort, "toPort": toPort}).Debug("Generated random ports")
//return &StreamSession{sam.Config.I2PConfig.Sam(), id, conn, sam.keys, time.Duration(600 * time.Second), time.Now(), Sig_NONE, randport(), randport()}, nil
// return &StreamSession{sam.Config.I2PConfig.Sam(), id, conn, sam.keys, time.Duration(600 * time.Second), time.Now(), Sig_NONE, randport(), randport()}, nil
return &StreamSession{sam.Config.I2PConfig.Sam(), id, conn, sam.keys, time.Duration(600 * time.Second), time.Now(), Sig_NONE, fromPort, toPort}, nil
}

View File

@ -144,5 +144,5 @@ func ExamplePrimaryDatagramSession() {
return
// Output:
//Got message: Hello myself!
// Got message: Hello myself!
}

View File

@ -190,7 +190,7 @@ func ExamplePrimaryStreamSession() {
return
}
defer sam.Close()
conn, err := sam.Dial("tcp", "idk.i2p") //someone.Base32())
conn, err := sam.Dial("tcp", "idk.i2p") // someone.Base32())
if err != nil {
fmt.Println(err.Error())
return
@ -211,8 +211,8 @@ func ExamplePrimaryStreamSession() {
log.Println("Read HTTP/HTML from idk.i2p")
}
// Output:
//Sending HTTP GET /
//Read HTTP/HTML from idk.i2p
// Sending HTTP GET /
// Read HTTP/HTML from idk.i2p
}
func ExamplePrimaryStreamListener() {
@ -253,7 +253,7 @@ func ExamplePrimaryStreamListener() {
return
}
defer l.Close()
//fmt.Println("Serving on primary listener", l.Addr().String())
// fmt.Println("Serving on primary listener", l.Addr().String())
if err := http.Serve(l, &exitHandler{}); err != nil {
fmt.Println(err.Error())
}
@ -281,7 +281,7 @@ func ExamplePrimaryStreamListener() {
Dial: sc.Dial,
},
}
//resp, err := client.Get("http://" + "idk.i2p") //ss.Addr().Base32())
// resp, err := client.Get("http://" + "idk.i2p") //ss.Addr().Base32())
resp, err := client.Get("http://" + ss.Addr().Base32())
if err != nil {
fmt.Println(err.Error())
@ -299,8 +299,7 @@ func ExamplePrimaryStreamListener() {
// Got response: Hello world!
}
type exitHandler struct {
}
type exitHandler struct{}
func (e *exitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world!"))

3
raw.go
View File

@ -3,11 +3,12 @@ package sam3
import (
"bytes"
"errors"
"github.com/sirupsen/logrus"
"net"
"strconv"
"time"
"github.com/sirupsen/logrus"
"github.com/go-i2p/i2pkeys"
)

View File

@ -60,7 +60,7 @@ func (sam *SAMResolver) Resolve(name string) (i2pkeys.I2PAddr, error) {
for s.Scan() {
text := s.Text()
log.WithField("text", text).Debug("Parsing SAM response token")
//log.Println("SAM3", text)
// log.Println("SAM3", text)
if text == "RESULT=OK" {
continue
} else if text == "RESULT=INVALID_KEY" {

View File

@ -6,13 +6,14 @@ import (
"bytes"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"io"
"math/rand"
"net"
"os"
"strings"
"github.com/sirupsen/logrus"
"github.com/go-i2p/i2pkeys"
. "github.com/go-i2p/i2pkeys"
@ -87,7 +88,7 @@ func NewSAM(address string) (*SAM, error) {
log.Debug("SAM hello successful")
s.Config.I2PConfig.SetSAMAddress(address)
s.conn = conn
//s.Config.I2PConfig.DestinationKeys = nil
// s.Config.I2PConfig.DestinationKeys = nil
s.resolver, err = NewSAMResolver(&s)
if err != nil {
log.WithError(err).Error("Failed to create SAM resolver")
@ -106,7 +107,7 @@ func NewSAM(address string) (*SAM, error) {
}
func (sam *SAM) Keys() (k *i2pkeys.I2PKeys) {
//TODO: copy them?
// TODO: copy them?
log.Debug("Retrieving SAM keys")
k = &sam.Config.I2PConfig.DestinationKeys
return
@ -147,7 +148,7 @@ func (sam *SAM) EnsureKeyfile(fname string) (keys i2pkeys.I2PKeys, err error) {
sam.Config.I2PConfig.DestinationKeys = keys
// save keys
var f io.WriteCloser
f, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE, 0600)
f, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE, 0o600)
if err == nil {
err = i2pkeys.StoreKeysIncompat(keys, f)
f.Close()

View File

@ -5,12 +5,14 @@ import (
"bytes"
"context"
"errors"
"github.com/sirupsen/logrus"
"fmt"
"io"
"net"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/go-i2p/i2pkeys"
)
@ -212,7 +214,7 @@ func (s *StreamSession) Dial(n, addr string) (c net.Conn, err error) {
var i2paddr i2pkeys.I2PAddr
var host string
host, _, err = SplitHostPort(addr)
//log.Println("Dialing:", host)
// log.Println("Dialing:", host)
if err = IgnorePortError(err); err == nil {
// check for name
if strings.HasSuffix(host, ".b32.i2p") || strings.HasSuffix(host, ".i2p") {
@ -222,8 +224,8 @@ func (s *StreamSession) Dial(n, addr string) (c net.Conn, err error) {
} else {
// probably a destination
i2paddr, err = i2pkeys.NewI2PAddrFromBytes([]byte(host))
//i2paddr = i2pkeys.I2PAddr(host)
//log.Println("Destination:", i2paddr, err)
// i2paddr = i2pkeys.I2PAddr(host)
// log.Println("Destination:", i2paddr, err)
log.WithFields(logrus.Fields{"host": host, "i2paddr": i2paddr}).Debug("Created I2P address from bytes")
}
if err == nil {
@ -243,7 +245,12 @@ func (s *StreamSession) DialI2P(addr i2pkeys.I2PAddr) (*SAMConn, error) {
return nil, err
}
conn := sam.conn
_, err = conn.Write([]byte("STREAM CONNECT ID=" + s.id + " FROM_PORT=" + s.from + " TO_PORT=" + s.to + " DESTINATION=" + addr.Base64() + " SILENT=false\n"))
cmd := fmt.Sprintf("STREAM CONNECT ID=%s DESTINATION=%s FROM_PORT=%s TO_PORT=%s SILENT=false\n",
s.id,
addr.Base64(),
s.from,
s.to)
_, err = conn.Write([]byte(cmd))
if err != nil {
log.WithError(err).Error("Failed to write STREAM CONNECT command")
conn.Close()

View File

@ -3,12 +3,13 @@ package sam3
import (
"bufio"
"errors"
"github.com/sirupsen/logrus"
"io"
"net"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"github.com/go-i2p/i2pkeys"
)

View File

@ -198,8 +198,8 @@ func ExampleStreamSession() {
return
// Output:
//Sending HTTP GET /
//Read HTTP/HTML from idk.i2p
// Sending HTTP GET /
// Read HTTP/HTML from idk.i2p
}
func ExampleStreamListener() {
@ -279,5 +279,5 @@ func ExampleStreamListener() {
<-quit // waits for client to die, for example only
// Output:
//Hello world!
// Hello world!
}

View File

@ -1,63 +1,78 @@
package sam3
import (
"github.com/sirupsen/logrus"
"net"
"net/http"
"os"
"strings"
"github.com/sirupsen/logrus"
)
// Examples and suggestions for options when creating sessions.
var (
// Suitable options if you are shuffling A LOT of traffic. If unused, this
// will waste your resources.
Options_Humongous = []string{"inbound.length=3", "outbound.length=3",
Options_Humongous = []string{
"inbound.length=3", "outbound.length=3",
"inbound.lengthVariance=1", "outbound.lengthVariance=1",
"inbound.backupQuantity=3", "outbound.backupQuantity=3",
"inbound.quantity=6", "outbound.quantity=6"}
"inbound.quantity=6", "outbound.quantity=6",
}
// Suitable for shuffling a lot of traffic.
Options_Large = []string{"inbound.length=3", "outbound.length=3",
Options_Large = []string{
"inbound.length=3", "outbound.length=3",
"inbound.lengthVariance=1", "outbound.lengthVariance=1",
"inbound.backupQuantity=1", "outbound.backupQuantity=1",
"inbound.quantity=4", "outbound.quantity=4"}
"inbound.quantity=4", "outbound.quantity=4",
}
// Suitable for shuffling a lot of traffic quickly with minimum
// anonymity. Uses 1 hop and multiple tunnels.
Options_Wide = []string{"inbound.length=1", "outbound.length=1",
Options_Wide = []string{
"inbound.length=1", "outbound.length=1",
"inbound.lengthVariance=1", "outbound.lengthVariance=1",
"inbound.backupQuantity=2", "outbound.backupQuantity=2",
"inbound.quantity=3", "outbound.quantity=3"}
"inbound.quantity=3", "outbound.quantity=3",
}
// Suitable for shuffling medium amounts of traffic.
Options_Medium = []string{"inbound.length=3", "outbound.length=3",
Options_Medium = []string{
"inbound.length=3", "outbound.length=3",
"inbound.lengthVariance=1", "outbound.lengthVariance=1",
"inbound.backupQuantity=0", "outbound.backupQuantity=0",
"inbound.quantity=2", "outbound.quantity=2"}
"inbound.quantity=2", "outbound.quantity=2",
}
// Sensible defaults for most people
Options_Default = []string{"inbound.length=3", "outbound.length=3",
Options_Default = []string{
"inbound.length=3", "outbound.length=3",
"inbound.lengthVariance=0", "outbound.lengthVariance=0",
"inbound.backupQuantity=1", "outbound.backupQuantity=1",
"inbound.quantity=1", "outbound.quantity=1"}
"inbound.quantity=1", "outbound.quantity=1",
}
// Suitable only for small dataflows, and very short lasting connections:
// You only have one tunnel in each direction, so if any of the nodes
// through which any of your two tunnels pass through go offline, there will
// be a complete halt in the dataflow, until a new tunnel is built.
Options_Small = []string{"inbound.length=3", "outbound.length=3",
Options_Small = []string{
"inbound.length=3", "outbound.length=3",
"inbound.lengthVariance=1", "outbound.lengthVariance=1",
"inbound.backupQuantity=0", "outbound.backupQuantity=0",
"inbound.quantity=1", "outbound.quantity=1"}
"inbound.quantity=1", "outbound.quantity=1",
}
// Does not use any anonymization, you connect directly to others tunnel
// endpoints, thus revealing your identity but not theirs. Use this only
// if you don't care.
Options_Warning_ZeroHop = []string{"inbound.length=0", "outbound.length=0",
Options_Warning_ZeroHop = []string{
"inbound.length=0", "outbound.length=0",
"inbound.lengthVariance=0", "outbound.lengthVariance=0",
"inbound.backupQuantity=0", "outbound.backupQuantity=0",
"inbound.quantity=2", "outbound.quantity=2"}
"inbound.quantity=2", "outbound.quantity=2",
}
)
func PrimarySessionString() string {
@ -115,8 +130,10 @@ func getEnv(key, fallback string) string {
return value
}
var SAM_HOST = getEnv("sam_host", "127.0.0.1")
var SAM_PORT = getEnv("sam_port", "7656")
var (
SAM_HOST = getEnv("sam_host", "127.0.0.1")
SAM_PORT = getEnv("sam_port", "7656")
)
func SAMDefaultAddr(fallforward string) string {
if fallforward == "" {
@ -138,5 +155,5 @@ func GenerateOptionString(opts []string) string {
finalOpts := optStr + " i2cp.leaseSetEncType=4,0"
log.WithField("finalOptions", finalOpts).Debug("Added default i2cp.leaseSetEncType to options")
return finalOpts
//return optStr + " i2cp.leaseSetEncType=4,0"
// return optStr + " i2cp.leaseSetEncType=4,0"
}