27 Commits

Author SHA1 Message Date
idk
1ef2d90f46 fix some debian stuff 2020-06-22 18:15:05 -04:00
idk
f90e3b2755 remove it from go mod 2020-06-22 14:09:44 -04:00
idk
a959ac58ba Merge pull request #2 from eyedeekay/fancy-config
Fancy config
2019-12-08 03:14:32 +00:00
idk
eecb73010c merge config parts of ramp 2019-12-07 22:10:55 -05:00
idk
442114200c purge ramp 2019-12-07 22:09:40 -05:00
idk
d4ac38fc97 purge ramp 2019-12-07 22:06:50 -05:00
idk
0a2d58418f Merge pull request #1 from eyedeekay/desthash44
add 44-char dest hashes
2019-12-07 22:31:43 +00:00
idk
ca1a4f7f54 update deb changelog 2019-12-07 17:31:04 -05:00
idk
6406efd277 add 44-char dest hashes 2019-12-07 17:26:28 -05:00
idk
a12f9ba498 add makefile to ease releases 2019-10-22 02:26:57 -04:00
idk
4a24538cd5 windows compatibility fixes 2019-10-22 02:24:38 -04:00
idk
f617388473 windows compatibility fixes 2019-10-22 02:19:01 -04:00
idk
c2b2b39c74 gofmt 2019-10-22 02:06:08 -04:00
idk
0067d37ca3 windows compatibility fixes 2019-10-22 02:05:58 -04:00
idk
f8d54526ea update go mod 2019-07-30 14:51:40 -04:00
idk
e9868b791e enable setting the write buffer size 2019-07-30 14:50:14 -04:00
idk
a810f009bd update modules 2019-07-29 20:02:43 -04:00
idk
99ad6522eb implement UDPConn as well 2019-06-12 23:41:17 -04:00
idk
6f6be01fb2 implement UDPConn too 2019-06-12 23:33:06 -04:00
idk
7438f855cd implement UDPConn too 2019-06-12 23:32:35 -04:00
idk
265e8b21b4 update changelog 2019-05-18 18:21:01 -04:00
idk
9d24d56c28 thought that might have happened 2019-04-29 16:21:40 -04:00
idk
d622765b79 forgot to add moved i2pkeys dir 2019-04-20 14:50:55 -04:00
idk
57c0d7fc54 Experimental branch 2019-04-10 00:47:41 -04:00
idk
777c148eee move i2pkeys to it's own standalone directory. 2019-04-09 14:31:59 -04:00
idk
2b8b539e44 move i2pkeys to it's own standalone directory. 2019-04-09 14:26:27 -04:00
idk
c30f54fc7b expose from and to in listener 2019-03-26 23:23:37 -04:00
18 changed files with 980 additions and 33 deletions

24
Makefile Normal file
View File

@@ -0,0 +1,24 @@
USER_GH=eyedeekay
VERSION=0.32.3
packagename=sam3
echo:
@echo "type make version to do release $(VERSION)"
version:
gothub release -s $(GITHUB_TOKEN) -u $(USER_GH) -r $(packagename) -t v$(VERSION) -d "version $(VERSION)"
del:
gothub delete -s $(GITHUB_TOKEN) -u $(USER_GH) -r $(packagename) -t v$(VERSION)
tar:
tar --exclude .git \
--exclude .go \
--exclude bin \
-cJvf ../$(packagename)_$(VERSION).orig.tar.xz .
copier:
echo '#! /usr/bin/env sh' > deb/copy.sh
echo 'for f in $$(ls); do scp $$f/*.deb user@192.168.99.106:~/DEBIAN_PKGS/$$f/main/; done' >> deb/copy.sh

View File

@@ -6,6 +6,11 @@ import (
"time"
)
/*
import (
. "github.com/eyedeekay/sam3/i2pkeys"
)
*/
// Implements net.Conn
type SAMConn struct {
laddr i2pkeys.I2PAddr

290
config.go
View File

@@ -2,13 +2,301 @@ package sam3
import (
"fmt"
"math/rand"
"net"
"strconv"
"strings"
"github.com/eyedeekay/sam3/i2pkeys"
)
// sam config
// I2PConfig is a struct which manages I2P configuration options
type I2PConfig struct {
SamHost string
SamPort string
TunName string
SamMin string
SamMax string
Fromport string
Toport string
Style string
TunType string
DestinationKeys i2pkeys.I2PKeys
SigType string
EncryptLeaseSet string
LeaseSetKey string
LeaseSetPrivateKey string
LeaseSetPrivateSigningKey string
LeaseSetKeys i2pkeys.I2PKeys
InAllowZeroHop string
OutAllowZeroHop string
InLength string
OutLength string
InQuantity string
OutQuantity string
InVariance string
OutVariance string
InBackupQuantity string
OutBackupQuantity string
FastRecieve string
UseCompression string
MessageReliability string
CloseIdle string
CloseIdleTime string
ReduceIdle string
ReduceIdleTime string
ReduceIdleQuantity string
//Streaming Library options
AccessListType string
AccessList []string
}
func (f *I2PConfig) Sam() string {
host := "127.0.0.1"
port := "7656"
if f.SamHost != "" {
host = f.SamHost
}
if f.SamPort != "" {
port = f.SamPort
}
return host + ":" + port
}
func (f *I2PConfig) SetSAMAddress(addr string) {
hp := strings.Split(addr, ":")
if len(hp) == 1 {
f.SamHost = hp[0]
} else if len(hp) == 2 {
f.SamPort = hp[1]
f.SamHost = hp[0]
}
f.SamPort = "7656"
f.SamHost = "127.0.0.1"
}
func (f *I2PConfig) ID() string {
if f.TunName == "" {
b := make([]byte, 12)
for i := range b {
b[i] = "abcdefghijklmnopqrstuvwxyz"[rand.Intn(len("abcdefghijklmnopqrstuvwxyz"))]
}
f.TunName = string(b)
}
return " ID=" + f.TunName + " "
}
func (f *I2PConfig) Leasesetsettings() (string, string, string) {
var r, s, t string
if f.LeaseSetKey != "" {
r = " i2cp.leaseSetKey=" + f.LeaseSetKey + " "
}
if f.LeaseSetPrivateKey != "" {
s = " i2cp.leaseSetPrivateKey=" + f.LeaseSetPrivateKey + " "
}
if f.LeaseSetPrivateSigningKey != "" {
t = " i2cp.leaseSetPrivateSigningKey=" + f.LeaseSetPrivateSigningKey + " "
}
return r, s, t
}
func (f *I2PConfig) FromPort() string {
if f.samMax() < 3.1 {
return ""
}
if f.Fromport != "0" {
return " FROM_PORT=" + f.Fromport + " "
}
return ""
}
func (f *I2PConfig) ToPort() string {
if f.samMax() < 3.1 {
return ""
}
if f.Toport != "0" {
return " TO_PORT=" + f.Toport + " "
}
return ""
}
func (f *I2PConfig) SessionStyle() string {
if f.Style != "" {
return " STYLE=" + f.Style + " "
}
return " STYLE=STREAM "
}
func (f *I2PConfig) samMax() float64 {
i, err := strconv.Atoi(f.SamMax)
if err != nil {
return 3.1
}
return float64(i)
}
func (f *I2PConfig) MinSAM() string {
if f.SamMin == "" {
return "3.0"
}
return f.SamMin
}
func (f *I2PConfig) MaxSAM() string {
if f.SamMax == "" {
return "3.1"
}
return f.SamMax
}
func (f *I2PConfig) DestinationKey() string {
if &f.DestinationKeys != nil {
return " DESTINATION=" + f.DestinationKeys.String() + " "
}
return " DESTINATION=TRANSIENT "
}
func (f *I2PConfig) SignatureType() string {
if f.samMax() < 3.1 {
return ""
}
if f.SigType != "" {
return " SIGNATURE_TYPE=" + f.SigType + " "
}
return ""
}
func (f *I2PConfig) EncryptLease() string {
if f.EncryptLeaseSet == "true" {
return " i2cp.encryptLeaseSet=true "
}
return ""
}
func (f *I2PConfig) Reliability() string {
if f.MessageReliability != "" {
return " i2cp.messageReliability=" + f.MessageReliability + " "
}
return ""
}
func (f *I2PConfig) Reduce() string {
if f.ReduceIdle == "true" {
return "i2cp.reduceOnIdle=" + f.ReduceIdle + "i2cp.reduceIdleTime=" + f.ReduceIdleTime + "i2cp.reduceQuantity=" + f.ReduceIdleQuantity
}
return ""
}
func (f *I2PConfig) Close() string {
if f.CloseIdle == "true" {
return "i2cp.closeOnIdle=" + f.CloseIdle + "i2cp.closeIdleTime=" + f.CloseIdleTime
}
return ""
}
func (f *I2PConfig) DoZero() string {
r := ""
if f.InAllowZeroHop == "true" {
r += " inbound.allowZeroHop=" + f.InAllowZeroHop + " "
}
if f.OutAllowZeroHop == "true" {
r += " outbound.allowZeroHop= " + f.OutAllowZeroHop + " "
}
if f.FastRecieve == "true" {
r += " " + f.FastRecieve + " "
}
return r
}
func (f *I2PConfig) Print() []string {
lsk, lspk, lspsk := f.Leasesetsettings()
return []string{
//f.targetForPort443(),
"inbound.length=" + f.InLength,
"outbound.length=" + f.OutLength,
"inbound.lengthVariance=" + f.InVariance,
"outbound.lengthVariance=" + f.OutVariance,
"inbound.backupQuantity=" + f.InBackupQuantity,
"outbound.backupQuantity=" + f.OutBackupQuantity,
"inbound.quantity=" + f.InQuantity,
"outbound.quantity=" + f.OutQuantity,
f.DoZero(),
//"i2cp.fastRecieve=" + f.FastRecieve,
"i2cp.gzip=" + f.UseCompression,
f.Reduce(),
f.Close(),
f.Reliability(),
f.EncryptLease(),
lsk, lspk, lspsk,
f.Accesslisttype(),
f.Accesslist(),
}
}
func (f *I2PConfig) Accesslisttype() string {
if f.AccessListType == "whitelist" {
return "i2cp.enableAccessList=true"
} else if f.AccessListType == "blacklist" {
return "i2cp.enableBlackList=true"
} else if f.AccessListType == "none" {
return ""
}
return ""
}
func (f *I2PConfig) Accesslist() string {
if f.AccessListType != "" && len(f.AccessList) > 0 {
r := ""
for _, s := range f.AccessList {
r += s + ","
}
return "i2cp.accessList=" + strings.TrimSuffix(r, ",")
}
return ""
}
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.TunName = ""
config.TunType = "server"
config.Style = "STREAM"
config.InLength = "3"
config.OutLength = "3"
config.InQuantity = "2"
config.OutQuantity = "2"
config.InVariance = "1"
config.OutVariance = "1"
config.InBackupQuantity = "3"
config.OutBackupQuantity = "3"
config.InAllowZeroHop = "false"
config.OutAllowZeroHop = "false"
config.EncryptLeaseSet = "false"
config.LeaseSetKey = ""
config.LeaseSetPrivateKey = ""
config.LeaseSetPrivateSigningKey = ""
config.FastRecieve = "false"
config.UseCompression = "true"
config.ReduceIdle = "false"
config.ReduceIdleTime = "15"
config.ReduceIdleQuantity = "4"
config.CloseIdle = "false"
config.CloseIdleTime = "300000"
config.MessageReliability = "none"
for _, o := range opts {
if err := o(&config); err != nil {
return nil, err
}
}
return &config, nil
}
// options map
type Options map[string]string

View File

@@ -15,12 +15,13 @@ import (
// also end-to-end encrypted, signed and includes replay-protection. And they
// are also built to be surveillance-resistant (yey!).
type DatagramSession struct {
samAddr string // address to the sam bridge (ipv4:port)
id string // tunnel name
conn net.Conn // connection to sam bridge
udpconn *net.UDPConn // used to deliver datagrams
keys i2pkeys.I2PKeys // i2p destination keys
rUDPAddr *net.UDPAddr // the SAM bridge UDP-port
samAddr string // address to the sam bridge (ipv4:port)
id string // tunnel name
conn net.Conn // connection to sam bridge
udpconn *net.UDPConn // used to deliver datagrams
keys i2pkeys.I2PKeys // i2p destination keys
rUDPAddr *net.UDPAddr // the SAM bridge UDP-port
remoteAddr *i2pkeys.I2PAddr // optional remote I2P address
}
// Creates a new datagram session. udpPort is the UDP port SAM is listening on,
@@ -59,13 +60,17 @@ func (s *SAM) NewDatagramSession(id string, keys i2pkeys.I2PKeys, options []stri
if err != nil {
return nil, err
}
return &DatagramSession{s.address, id, conn, udpconn, keys, rUDPAddr}, nil
return &DatagramSession{s.address, id, conn, udpconn, keys, rUDPAddr, nil}, nil
}
func (s *DatagramSession) B32() string {
return s.keys.Addr().Base32()
}
func (s *DatagramSession) RemoteAddr() net.Addr {
return s.remoteAddr
}
// Reads one datagram sent to the destination of the DatagramSession. Returns
// the number of bytes read, from what address it was sent, or an error.
// implements net.PacketConn
@@ -103,16 +108,25 @@ func (s *DatagramSession) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
}
}
func (s *DatagramSession) Read(b []byte) (n int, err error) {
rint, _, rerr := s.ReadFrom(b)
return rint, rerr
}
// Sends one signed datagram to the destination specified. At the time of
// writing, maximum size is 31 kilobyte, but this may change in the future.
// Implements net.PacketConn.
func (s *DatagramSession) WriteTo(b []byte, addr net.Addr) (n int, err error) {
header := []byte("3.0 " + s.id + " " + addr.String() + "\n")
header := []byte("3.1 " + s.id + " " + addr.String() + "\n")
msg := append(header, b...)
n, err = s.udpconn.WriteToUDP(msg, s.rUDPAddr)
return n, err
}
func (s *DatagramSession) Write(b []byte) (int, error) {
return s.WriteTo(b, s.remoteAddr)
}
// Closes the DatagramSession. Implements net.PacketConn
func (s *DatagramSession) Close() error {
err := s.conn.Close()
@@ -159,3 +173,7 @@ func (s *DatagramSession) SetReadDeadline(t time.Time) error {
func (s *DatagramSession) SetWriteDeadline(t time.Time) error {
return s.udpconn.SetWriteDeadline(t)
}
func (s *DatagramSession) SetWriteBuffer(bytes int) error {
return s.udpconn.SetWriteBuffer(bytes)
}

View File

@@ -4,6 +4,7 @@ package sam3
import (
"fmt"
"log"
"testing"
"time"
)
@@ -124,6 +125,58 @@ func ExampleDatagramSession() {
fmt.Println(err.Error())
return
}
log.Println("Got message: '" + string(buf[:n]) + "'")
fmt.Println("Got message: " + string(buf[:n]))
return
// Output:
//Got message: Hello myself!
}
func ExampleMiniDatagramSession() {
// Creates a new DatagramSession, which behaves just like a net.PacketConn.
const samBridge = "127.0.0.1:7656"
sam, err := NewSAM(samBridge)
if err != nil {
fmt.Println(err.Error())
return
}
keys, err := sam.NewKeys()
if err != nil {
fmt.Println(err.Error())
return
}
myself := keys.Addr()
// See the example Option_* variables.
dg, err := sam.NewDatagramSession("MINIDGTUN", keys, Options_Small, 0)
if err != nil {
fmt.Println(err.Error())
return
}
someone, err := sam.Lookup("zzz.i2p")
if err != nil {
fmt.Println(err.Error())
return
}
err = dg.SetWriteBuffer(14 * 1024)
if err != nil {
fmt.Println(err.Error())
return
}
dg.WriteTo([]byte("Hello stranger!"), someone)
dg.WriteTo([]byte("Hello myself!"), myself)
buf := make([]byte, 31*1024)
n, _, err := dg.ReadFrom(buf)
if err != nil {
fmt.Println(err.Error())
return
}
log.Println("Got message: '" + string(buf[:n]) + "'")
fmt.Println("Got message: " + string(buf[:n]))
return

33
debian/changelog vendored
View File

@@ -1,11 +1,40 @@
golang-github-eyedeekay-sam3 (0.3.2.3) unreleased; urgency=medium
[ idk ]
* Purge ramp, re-release
-- idk <hankhill19580@gmail.com> Mon, 22 Jun 2020 17:55:03 -0500
golang-github-eyedeekay-sam3 (0.3.2.2) bionic; urgency=medium
[ idk ]
* Purge ramp
-- idk <hankhill19580@gmail.com> Sat, 7 Dec 2019 22:05:34 -0500
golang-github-eyedeekay-sam3 (0.3.2.1) bionic; urgency=medium
[ idk ]
* Add support for 44-character destination hashes.
-- idk <hankhill19580@gmail.com> Sat, 7 Dec 2019 17:30:30 -0500
golang-github-eyedeekay-sam3 (0.3.2.01) bionic; urgency=medium
[ idk ]
* completely remove the old i2pkeys version and replace it with the new one.
-- idk <hankhill19580@gmail.com> Sat, 25 May 2019 14:38:11 -0500
golang-github-eyedeekay-sam3 (0.3.2.0) bionic; urgency=medium
[ idk ]
* Bug fixes, create stable branch
* Move i2pkeys
-- idk <hankhill19580@gmail.com> Fri, 18 May 2019 18:32:51 -0500
-- idk <hankhill19580@gmail.com> Sat, 18 May 2019 18:32:51 -0500
golang-github-eyedeekay-sam3 (0.0~git20190223.af5a3f3) bionic; urgency=medium

3
debian/control vendored
View File

@@ -5,7 +5,8 @@ Maintainer: Debian Go Packaging Team <team+pkg-go@tracker.debian.org>
Uploaders: idk <hankhill19580@gmail.com>
Build-Depends: debhelper (>= 11),
dh-golang,
golang-any
git,
golang-any | golang-go,
Standards-Version: 4.2.1
Homepage: https://github.com/eyedeekay/sam3
Vcs-Browser: https://github.com/eyedeekay/sam3

1
debian/files vendored
View File

@@ -1 +0,0 @@
golang-github-eyedeekay-sam3_0.3.2.0_source.buildinfo devel optional

369
emit-options.go Normal file
View File

@@ -0,0 +1,369 @@
package sam3
import (
"fmt"
"strconv"
"strings"
)
//Option is a SAMEmit Option
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 == "STREAM" {
c.Style = s
return nil
} else if s == "DATAGRAM" {
c.Style = s
return nil
} else if s == "RAW" {
c.Style = s
return nil
}
return fmt.Errorf("Invalid session STYLE=%s, must be STREAM, DATAGRAM, or RAW")
}
}
// SetSAMAddress sets the SAM address all-at-once
func SetSAMAddress(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
sp := strings.Split(s, ":")
if len(sp) > 2 {
return fmt.Errorf("Invalid address string: %s", sp)
}
if len(sp) == 2 {
c.I2PConfig.SamPort = sp[1]
}
c.I2PConfig.SamHost = sp[0]
return nil
}
}
//SetSAMHost sets the host of the SAMEmit's SAM bridge
func SetSAMHost(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.SamHost = s
return nil
}
}
//SetSAMPort sets the port of the SAMEmit's SAM bridge using a string
func SetSAMPort(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
port, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("Invalid SAM Port %s; non-number", s)
}
if port < 65536 && port > -1 {
c.I2PConfig.SamPort = s
return nil
}
return fmt.Errorf("Invalid port")
}
}
//SetName sets the host of the SAMEmit's SAM bridge
func SetName(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.TunName = s
return nil
}
}
//SetInLength sets the number of hops inbound
func SetInLength(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u < 7 && u >= 0 {
c.I2PConfig.InLength = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid inbound tunnel length")
}
}
//SetOutLength sets the number of hops outbound
func SetOutLength(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u < 7 && u >= 0 {
c.I2PConfig.OutLength = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid outbound tunnel length")
}
}
//SetInVariance sets the variance of a number of hops inbound
func SetInVariance(i int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if i < 7 && i > -7 {
c.I2PConfig.InVariance = strconv.Itoa(i)
return nil
}
return fmt.Errorf("Invalid inbound tunnel length")
}
}
//SetOutVariance sets the variance of a number of hops outbound
func SetOutVariance(i int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if i < 7 && i > -7 {
c.I2PConfig.OutVariance = strconv.Itoa(i)
return nil
}
return fmt.Errorf("Invalid outbound tunnel variance")
}
}
//SetInQuantity sets the inbound tunnel quantity
func SetInQuantity(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u <= 16 && u > 0 {
c.I2PConfig.InQuantity = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid inbound tunnel quantity")
}
}
//SetOutQuantity sets the outbound tunnel quantity
func SetOutQuantity(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u <= 16 && u > 0 {
c.I2PConfig.OutQuantity = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid outbound tunnel quantity")
}
}
//SetInBackups sets the inbound tunnel backups
func SetInBackups(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u < 6 && u >= 0 {
c.I2PConfig.InBackupQuantity = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid inbound tunnel backup quantity")
}
}
//SetOutBackups sets the inbound tunnel backups
func SetOutBackups(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u < 6 && u >= 0 {
c.I2PConfig.OutBackupQuantity = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid outbound tunnel backup quantity")
}
}
//SetEncrypt tells the router to use an encrypted leaseset
func SetEncrypt(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.EncryptLeaseSet = "true"
return nil
}
c.I2PConfig.EncryptLeaseSet = "false"
return nil
}
}
//SetLeaseSetKey sets the host of the SAMEmit's SAM bridge
func SetLeaseSetKey(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.LeaseSetKey = s
return nil
}
}
//SetLeaseSetPrivateKey sets the host of the SAMEmit's SAM bridge
func SetLeaseSetPrivateKey(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.LeaseSetPrivateKey = s
return nil
}
}
//SetLeaseSetPrivateSigningKey sets the host of the SAMEmit's SAM bridge
func SetLeaseSetPrivateSigningKey(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.LeaseSetPrivateSigningKey = s
return nil
}
}
//SetMessageReliability sets the host of the SAMEmit's SAM bridge
func SetMessageReliability(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.MessageReliability = s
return nil
}
}
//SetAllowZeroIn tells the tunnel to accept zero-hop peers
func SetAllowZeroIn(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.InAllowZeroHop = "true"
return nil
}
c.I2PConfig.InAllowZeroHop = "false"
return nil
}
}
//SetAllowZeroOut tells the tunnel to accept zero-hop peers
func SetAllowZeroOut(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.OutAllowZeroHop = "true"
return nil
}
c.I2PConfig.OutAllowZeroHop = "false"
return nil
}
}
//SetCompress tells clients to use compression
func SetCompress(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.UseCompression = "true"
return nil
}
c.I2PConfig.UseCompression = "false"
return nil
}
}
//SetFastRecieve tells clients to use compression
func SetFastRecieve(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.FastRecieve = "true"
return nil
}
c.I2PConfig.FastRecieve = "false"
return nil
}
}
//SetReduceIdle tells the connection to reduce it's tunnels during extended idle time.
func SetReduceIdle(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.ReduceIdle = "true"
return nil
}
c.I2PConfig.ReduceIdle = "false"
return nil
}
}
//SetReduceIdleTime sets the time to wait before reducing tunnels to idle levels
func SetReduceIdleTime(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.ReduceIdleTime = "300000"
if u >= 6 {
c.I2PConfig.ReduceIdleTime = strconv.Itoa((u * 60) * 1000)
return nil
}
return fmt.Errorf("Invalid reduce idle timeout(Measured in minutes) %v", u)
}
}
//SetReduceIdleTimeMs sets the time to wait before reducing tunnels to idle levels in milliseconds
func SetReduceIdleTimeMs(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.ReduceIdleTime = "300000"
if u >= 300000 {
c.I2PConfig.ReduceIdleTime = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid reduce idle timeout(Measured in milliseconds) %v", u)
}
}
//SetReduceIdleQuantity sets minimum number of tunnels to reduce to during idle time
func SetReduceIdleQuantity(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if u < 5 {
c.I2PConfig.ReduceIdleQuantity = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid reduce tunnel quantity")
}
}
//SetCloseIdle tells the connection to close it's tunnels during extended idle time.
func SetCloseIdle(b bool) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if b {
c.I2PConfig.CloseIdle = "true"
return nil
}
c.I2PConfig.CloseIdle = "false"
return nil
}
}
//SetCloseIdleTime sets the time to wait before closing tunnels to idle levels
func SetCloseIdleTime(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.CloseIdleTime = "300000"
if u >= 6 {
c.I2PConfig.CloseIdleTime = strconv.Itoa((u * 60) * 1000)
return nil
}
return fmt.Errorf("Invalid close idle timeout(Measured in minutes) %v", u)
}
}
//SetCloseIdleTimeMs sets the time to wait before closing tunnels to idle levels in milliseconds
func SetCloseIdleTimeMs(u int) func(*SAMEmit) error {
return func(c *SAMEmit) error {
c.I2PConfig.CloseIdleTime = "300000"
if u >= 300000 {
c.I2PConfig.CloseIdleTime = strconv.Itoa(u)
return nil
}
return fmt.Errorf("Invalid close idle timeout(Measured in milliseconds) %v", u)
}
}
//SetAccessListType tells the system to treat the AccessList as a whitelist
func SetAccessListType(s string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if s == "whitelist" {
c.I2PConfig.AccessListType = "whitelist"
return nil
} else if s == "blacklist" {
c.I2PConfig.AccessListType = "blacklist"
return nil
} else if s == "none" {
c.I2PConfig.AccessListType = ""
return nil
} else if s == "" {
c.I2PConfig.AccessListType = ""
return nil
}
return fmt.Errorf("Invalid Access list type(whitelist, blacklist, none)")
}
}
//SetAccessList tells the system to treat the AccessList as a whitelist
func SetAccessList(s []string) func(*SAMEmit) error {
return func(c *SAMEmit) error {
if len(s) > 0 {
for _, a := range s {
c.I2PConfig.AccessList = append(c.I2PConfig.AccessList, a)
}
return nil
}
return nil
}
}

98
emit.go Normal file
View File

@@ -0,0 +1,98 @@
package sam3
import (
"fmt"
"log"
)
type SAMEmit struct {
I2PConfig
}
func (e *SAMEmit) OptStr() string {
optStr := ""
for _, opt := range e.I2PConfig.Print() {
optStr += opt + " "
}
return optStr
}
func (e *SAMEmit) Hello() string {
return fmt.Sprintf("HELLO VERSION MIN=%s MAX=%s \n", e.I2PConfig.MinSAM(), e.I2PConfig.MaxSAM())
}
func (e *SAMEmit) HelloBytes() []byte {
return []byte(e.Hello())
}
func (e *SAMEmit) GenerateDestination() string {
return fmt.Sprintf("DEST GENERATE %s \n", e.I2PConfig.SignatureType())
}
func (e *SAMEmit) GenerateDestinationBytes() []byte {
return []byte(e.GenerateDestination())
}
func (e *SAMEmit) Lookup(name string) string {
return fmt.Sprintf("NAMING LOOKUP NAME=%s \n", name)
}
func (e *SAMEmit) LookupBytes(name string) []byte {
return []byte(e.Lookup(name))
}
func (e *SAMEmit) Create() string {
return 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
)
}
func (e *SAMEmit) CreateBytes() []byte {
log.Println("sam command: " + e.Create())
return []byte(e.Create())
}
func (e *SAMEmit) Connect(dest string) string {
return fmt.Sprintf(
"STREAM CONNECT ID=%s %s %s DESTINATION=%s \n",
e.I2PConfig.ID(),
e.I2PConfig.FromPort(),
e.I2PConfig.ToPort(),
dest,
)
}
func (e *SAMEmit) ConnectBytes(dest string) []byte {
return []byte(e.Connect(dest))
}
func (e *SAMEmit) Accept() string {
return fmt.Sprintf(
"STREAM ACCEPT ID=%s",
e.I2PConfig.ID(),
e.I2PConfig.FromPort(),
e.I2PConfig.ToPort(),
)
}
func (e *SAMEmit) AcceptBytes() []byte {
return []byte(e.Accept())
}
func NewEmit(opts ...func(*SAMEmit) error) (*SAMEmit, error) {
var emit SAMEmit
for _, o := range opts {
if err := o(&emit); err != nil {
return nil, err
}
}
return &emit, nil
}

4
go.mod Normal file
View File

@@ -0,0 +1,4 @@
module github.com/eyedeekay/sam3
go 1.12

View File

@@ -80,13 +80,23 @@ func DestHashFromString(str string) (dhash I2PDestHash, err error) {
return
}
// get string representation of i2p dest hash
// get string representation of i2p dest hash(base32 version)
func (h I2PDestHash) String() string {
b32addr := make([]byte, 56)
i2pB32enc.Encode(b32addr, h[:])
return string(b32addr[:52]) + ".b32.i2p"
}
// get base64 representation of i2p dest sha256 hash(the 44-character one)
func (h I2PDestHash) Hash() string {
hash := sha256.New()
hash.Write(h[:])
digest := hash.Sum(nil)
buf := make([]byte, 44)
i2pB64enc.Encode(buf, digest)
return string(buf)
}
// Returns "I2P"
func (h *I2PDestHash) Network() string {
return "I2P"

2
raw.go
View File

@@ -61,7 +61,7 @@ func (s *SAM) NewRawSession(id string, keys i2pkeys.I2PKeys, options []string, u
if err != nil {
return nil, err
}
return &RawSession{s.address, id, conn, udpconn, keys, rUDPAddr}, nil
return &RawSession{s.Config.I2PConfig.Sam(), id, conn, udpconn, keys, rUDPAddr}, nil
}
// Reads one raw datagram sent to the destination of the DatagramSession. Returns

View File

@@ -32,7 +32,7 @@ func NewFullSAMResolver(address string) (*SAMResolver, error) {
// Performs a lookup, probably this order: 1) routers known addresses, cached
// addresses, 3) by asking peers in the I2P network.
func (sam *SAMResolver) Resolve(name string) (i2pkeys.I2PAddr, error) {
if _, err := sam.conn.Write([]byte("NAMING LOOKUP NAME=" + name + "\n")); err != nil {
if _, err := sam.conn.Write([]byte("NAMING LOOKUP NAME=" + name + "\r\n")); err != nil {
sam.Close()
return i2pkeys.I2PAddr(""), err
}
@@ -51,6 +51,7 @@ func (sam *SAMResolver) Resolve(name string) (i2pkeys.I2PAddr, error) {
errStr := ""
for s.Scan() {
text := s.Text()
//log.Println("SAM3", text)
if text == "RESULT=OK" {
continue
} else if text == "RESULT=INVALID_KEY" {

23
sam3.go
View File

@@ -13,11 +13,16 @@ import (
"github.com/eyedeekay/sam3/i2pkeys"
)
import (
. "github.com/eyedeekay/sam3/i2pkeys"
)
// Used for controlling I2Ps SAMv3.
type SAM struct {
address string
conn net.Conn
resolver *SAMResolver
Config SAMEmit
keys *i2pkeys.I2PKeys
sigType int
}
@@ -47,7 +52,7 @@ func NewSAM(address string) (*SAM, error) {
if err != nil {
return nil, err
}
if _, err := conn.Write([]byte("HELLO VERSION MIN=3.0 MAX=3.1\n")); err != nil {
if _, err := conn.Write(s.Config.HelloBytes()); err != nil {
conn.Close()
return nil, err
}
@@ -58,9 +63,9 @@ func NewSAM(address string) (*SAM, error) {
return nil, err
}
if strings.Contains(string(buf[:n]), "HELLO REPLY RESULT=OK") {
s.address = address
s.Config.I2PConfig.SetSAMAddress(address)
s.conn = conn
s.keys = nil
//s.Config.I2PConfig.DestinationKeys = nil
s.resolver, err = NewSAMResolver(&s)
if err != nil {
return nil, err
@@ -78,7 +83,7 @@ func NewSAM(address string) (*SAM, error) {
func (sam *SAM) Keys() (k *i2pkeys.I2PKeys) {
//TODO: copy them?
k = sam.keys
k = &sam.Config.I2PConfig.DestinationKeys
return
}
@@ -87,7 +92,7 @@ func (sam *SAM) ReadKeys(r io.Reader) (err error) {
var keys i2pkeys.I2PKeys
keys, err = i2pkeys.LoadKeysIncompat(r)
if err == nil {
sam.keys = &keys
sam.Config.I2PConfig.DestinationKeys = keys
}
return
}
@@ -98,7 +103,7 @@ func (sam *SAM) EnsureKeyfile(fname string) (keys i2pkeys.I2PKeys, err error) {
// transient
keys, err = sam.NewKeys()
if err == nil {
sam.keys = &keys
sam.Config.I2PConfig.DestinationKeys = keys
}
} else {
// persistant
@@ -107,7 +112,7 @@ func (sam *SAM) EnsureKeyfile(fname string) (keys i2pkeys.I2PKeys, err error) {
// make the keys
keys, err = sam.NewKeys()
if err == nil {
sam.keys = &keys
sam.Config.I2PConfig.DestinationKeys = keys
// save keys
var f io.WriteCloser
f, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE, 0600)
@@ -123,7 +128,7 @@ func (sam *SAM) EnsureKeyfile(fname string) (keys i2pkeys.I2PKeys, err error) {
if err == nil {
keys, err = i2pkeys.LoadKeysIncompat(f)
if err == nil {
sam.keys = &keys
sam.Config.I2PConfig.DestinationKeys = keys
}
}
}
@@ -165,7 +170,7 @@ func (sam *SAM) NewKeys(sigType ...string) (i2pkeys.I2PKeys, error) {
return i2pkeys.I2PKeys{}, errors.New("Failed to parse keys.")
}
}
return i2pkeys.I2PKeys{i2pkeys.I2PAddr(pub), priv}, nil
return NewKeys(I2PAddr(pub), priv), nil
}
// Performs a lookup, probably this order: 1) routers known addresses, cached

View File

@@ -27,7 +27,7 @@ func Test_Basic(t *testing.T) {
t.Fail()
} else {
fmt.Println("\tAddress created: " + keys.Addr().Base32())
fmt.Println("\tI2PKeys: " + string(keys.Both)[:50] + "(...etc)")
fmt.Println("\tI2PKeys: " + string(keys.String())[:50] + "(...etc)")
}
addr2, err := sam.Lookup("zzz.i2p")

View File

@@ -6,7 +6,9 @@ import (
"context"
"errors"
"io"
"log"
"net"
"strconv"
"strings"
"time"
@@ -64,7 +66,7 @@ func (sam *SAM) NewStreamSession(id string, keys i2pkeys.I2PKeys, options []stri
if err != nil {
return nil, err
}
return &StreamSession{sam.address, id, conn, keys, time.Duration(600 * time.Second), time.Now(), Sig_NONE, "0", "0"}, nil
return &StreamSession{sam.Config.I2PConfig.Sam(), id, conn, keys, time.Duration(600 * time.Second), time.Now(), Sig_NONE, "0", "0"}, nil
}
// Creates a new StreamSession with the I2CP- and streaminglib options as
@@ -74,7 +76,7 @@ func (sam *SAM) NewStreamSessionWithSignature(id string, keys i2pkeys.I2PKeys, o
if err != nil {
return nil, err
}
return &StreamSession{sam.address, id, conn, keys, time.Duration(600 * time.Second), time.Now(), sigType, "0", "0"}, nil
return &StreamSession{sam.Config.I2PConfig.Sam(), id, conn, keys, time.Duration(600 * time.Second), time.Now(), sigType, "0", "0"}, nil
}
// Creates a new StreamSession with the I2CP- and streaminglib options as
@@ -84,7 +86,7 @@ func (sam *SAM) NewStreamSessionWithSignatureAndPorts(id, from, to string, keys
if err != nil {
return nil, err
}
return &StreamSession{sam.address, id, conn, keys, time.Duration(600 * time.Second), time.Now(), sigType, from, to}, nil
return &StreamSession{sam.Config.I2PConfig.Sam(), id, conn, keys, time.Duration(600 * time.Second), time.Now(), sigType, from, to}, nil
}
// lookup name, convienence function
@@ -205,7 +207,7 @@ func (s *StreamSession) DialI2P(addr i2pkeys.I2PAddr) (*SAMConn, error) {
case "STATUS":
continue
case "RESULT=OK":
return &SAMConn{s.keys.Address, addr, conn}, nil
return &SAMConn{s.keys.Addr(), addr, conn}, nil
case "RESULT=CANT_REACH_PEER":
conn.Close()
return nil, errors.New("Can not reach peer")
@@ -247,6 +249,14 @@ type StreamListener struct {
laddr i2pkeys.I2PAddr
}
func (l *StreamListener) From() string {
return l.session.from
}
func (l *StreamListener) To() string {
return l.session.to
}
// get our address
// implements net.Listener
func (l *StreamListener) Addr() net.Addr {
@@ -263,6 +273,31 @@ func (l *StreamListener) Accept() (net.Conn, error) {
return l.AcceptI2P()
}
func ExtractPairString(input, value string) string {
parts := strings.Split(input, " ")
for _, part := range parts {
if strings.HasPrefix(part, value) {
kv := strings.SplitN(input, "=", 2)
if len(kv) == 2 {
return kv[1]
}
}
}
return ""
}
func ExtractPairInt(input, value string) int {
rv, err := strconv.Atoi(ExtractPairString(input, value))
if err != nil {
return 0
}
return rv
}
func ExtractDest(input string) string {
return strings.Split(input, " ")[0]
}
// accept a new inbound connection
func (l *StreamListener) AcceptI2P() (*SAMConn, error) {
s, err := NewSAM(l.session.samAddr)
@@ -274,11 +309,16 @@ func (l *StreamListener) AcceptI2P() (*SAMConn, error) {
rd := bufio.NewReader(s.conn)
// read first line
line, err := rd.ReadString(10)
log.Println(line)
if err == nil {
if strings.HasPrefix(line, "STREAM STATUS RESULT=OK") {
// we gud read destination line
dest, err := rd.ReadString(10)
destline, err := rd.ReadString(10)
log.Println(destline)
if err == nil {
dest := ExtractDest(destline)
l.session.from = ExtractPairString(destline, "FROM_PORT")
l.session.to = ExtractPairString(destline, "TO_PORT")
// return wrapped connection
dest = strings.Trim(dest, "\n")
return &SAMConn{

View File

@@ -4,6 +4,7 @@ package sam3
import (
"fmt"
"log"
"strings"
"testing"
@@ -29,7 +30,7 @@ func Test_StreamingDial(t *testing.T) {
return
}
fmt.Println("\tBuilding tunnel")
ss, err := sam.NewStreamSession("streamTun", keys, []string{"inbound.length=0", "outbound.length=0", "inbound.lengthVariance=0", "outbound.lengthVariance=0", "inbound.quantity=1", "outbound.quantity=1"})
ss, err := sam.NewStreamSession("streamTun", keys, []string{"inbound.length=1", "outbound.length=1", "inbound.lengthVariance=0", "outbound.lengthVariance=0", "inbound.quantity=1", "outbound.quantity=1"})
if err != nil {
fmt.Println(err.Error())
t.Fail()
@@ -43,7 +44,7 @@ func Test_StreamingDial(t *testing.T) {
t.Fail()
return
}
fmt.Println("\tDialing i2p-projekt.i2p")
fmt.Println("\tDialing i2p-projekt.i2p(", forumAddr.Base32(), forumAddr.DestHash().Hash(), ")")
conn, err := ss.DialI2P(forumAddr)
if err != nil {
fmt.Println(err.Error())
@@ -192,8 +193,10 @@ func ExampleStreamSession() {
n, err := conn.Read(buf)
if !strings.Contains(strings.ToLower(string(buf[:n])), "http") && !strings.Contains(strings.ToLower(string(buf[:n])), "html") {
fmt.Printf("Probably failed to StreamSession.DialI2P(zzz.i2p)? It replied %d bytes, but nothing that looked like http/html", n)
log.Printf("Probably failed to StreamSession.DialI2P(zzz.i2p)? It replied %d bytes, but nothing that looked like http/html", n)
} else {
fmt.Println("Read HTTP/HTML from zzz.i2p")
log.Println("Read HTTP/HTML from zzz.i2p")
}
return