Git Product home page Git Product logo

xtaci / kcptun Goto Github PK

View Code? Open in Web Editor NEW
13.7K 13.7K 2.5K 8.95 MB

A Stable & Secure Tunnel based on KCP with N:M multiplexing and FEC. Available for ARM, MIPS, 386 and AMD64。N:M 多重化と FEC を備えた KCP に基づく安定した安全なトンネル。 N:M 다중화 및 FEC를 사용하는 KCP 기반의 안정적이고 안전한 터널입니다. Un tunnel stable et sécurisé basé sur KCP avec multiplexage N:M et FEC.

License: MIT License

Go 73.64% Shell 25.19% Dockerfile 1.17%
accelerator cryptography kcp multiplexing reedsolomon shannon tunnel udp

kcptun's Introduction

kcptun

Release Powered MIT licensed Build Status Go Report Card Downloads Docker

kcptun

Disclaimer: kcptun maintains a single website — github.com/xtaci/kcptun. Any websites other than github.com/xtaci/kcptun are not endorsed by xtaci.

Requirements

Target Minimum Recommended
System aix darwin dragonfly freebsd linux netbsd openbsd solaris windows linux
Memory >20MB >32MB
CPU ANY amd64 with AES-NI & AVX2

NOTE: if you are using kvm, make sure the guest os can do AES instructions cpuinfo

QuickStart

Increase the number of open files on your server, as:

ulimit -n 65535, or write it in ~/.bashrc.

Suggested sysctl.conf parameters for better handling of UDP packets:

net.core.rmem_max=26214400 // BDP - bandwidth delay product
net.core.rmem_default=26214400
net.core.wmem_max=26214400
net.core.wmem_default=26214400
net.core.netdev_max_backlog=2048 // proportional to -rcvwnd

You can also increase the per-socket buffer by adding parameter(default 4MB):

-sockbuf 16777217

for slow processors, increasing this buffer is CRITICAL to receive packets properly.

Download a corresponding one from precompiled Releases.

KCP Client: ./client_darwin_amd64 -r "KCP_SERVER_IP:4000" -l ":8388" -mode fast3 -nocomp -autoexpire 900 -sockbuf 16777217 -dscp 46
KCP Server: ./server_linux_amd64 -t "TARGET_IP:8388" -l ":4000" -mode fast3 -nocomp -sockbuf 16777217 -dscp 46

The above commands will establish port forwarding channel for 8388/tcp as:

Application -> KCP Client(8388/tcp) -> KCP Server(4000/udp) -> Target Server(8388/tcp)

which tunnels the original connection:

Application -> Target Server(8388/tcp)

Build from source

$ git clone https://github.com/xtaci/kcptun.git
$ cd kcptun
$ ./build-release.sh
$ cd build

All precompiled releases are genereated from build-release.sh script.

Performance

fast.com

bandwidth

flame

Practical bandwidth graph with parameters: -mode fast3 -ds 10 -ps 3

Basic Tuning Guide

Improving Thoughput

Q: I have a high speed network link, how to reach the maximum bandwidth?

A: Increase -rcvwnd on KCP Client and -sndwnd on KCP Server simultaneously & gradually, the mininum one decides the maximum transfer rate of the link, as wnd * mtu / rtt; Then try downloading something and to see if it meets your requirements. (mtu is adjustable by -mtu)

Improving Latency

Q: I'm using kcptun for game, I don't want any lag happening.

A: Lag means packet loss for most of the time, lags can be improved by changing -mode.

eg: -mode fast3

Aggresiveness/Responsiveness on retransmission for embedded modes are:

fast3 > fast2 > fast > normal > default

HOLB

Since streams are multiplexed into a single physical channel, head of line blocking may appear under certain circumstances, by increasing -smuxbuf to a larger value (default 4MB) may mitigate this problem, obviously this will costs more memory.

For versions >= v20190924, you can switch to smux version 2, smux v2 has options to limit per-stream memory usage, now set -smuxver 2 to enable smux v2, and adjust -streambuf to limit per-stream memory usage, eg: -streambuf 2097152 can limit per-stream memory usage to 2MB. By limiting stream buffer on the receiver side, a back-pressure will be conducted to the sender and limits reading, and finally prevent source from sending too much data to occupy every bits of buffer along the link. (Setting -smuxver MUST be IDENTICAL on both side, default is 1. )

Slow Devices

kcptun made use of ReedSolomon-Codes to recover lost packets, which requires massive amount of computation, a low-end ARM device cannot satisfy kcptun well. To unleash the full potential of kcptun, a multi-core x86 homeserver CPU like AMD Opteron is recommended. If you insist on running under some ARM routers, you'd better turn off FEC and use salsa20 as the encryption method.

Expert Tuning Guide

Overview

params

Usage

➜  ~ ./client_linux_amd64 -h
NAME:
   kcptun - client(with SMUX)

USAGE:
   client_linux_amd64 [global options] command [command options] [arguments...]

VERSION:
   20190924

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --localaddr value, -l value      local listen address (default: ":12948")
   --remoteaddr value, -r value     kcp server address, eg: "IP:29900" a for single port, "IP:minport-maxport" for port range (default: "vps:29900")
   --key value                      pre-shared secret between client and server (default: "it's a secrect") [$KCPTUN_KEY]
   --crypt value                    aes, aes-128, aes-192, salsa20, blowfish, twofish, cast5, 3des, tea, xtea, xor, sm4, none (default: "aes")
   --mode value                     profiles: fast3, fast2, fast, normal, manual (default: "fast")
   --conn value                     set num of UDP connections to server (default: 1)
   --autoexpire value               set auto expiration time(in seconds) for a single UDP connection, 0 to disable (default: 0)
   --scavengettl value              set how long an expired connection can live (in seconds) (default: 600)
   --mtu value                      set maximum transmission unit for UDP packets (default: 1350)
   --sndwnd value                   set send window size(num of packets) (default: 128)
   --rcvwnd value                   set receive window size(num of packets) (default: 512)
   --datashard value, --ds value    set reed-solomon erasure coding - datashard (default: 10)
   --parityshard value, --ps value  set reed-solomon erasure coding - parityshard (default: 3)
   --dscp value                     set DSCP(6bit) (default: 0)
   --nocomp                         disable compression
   --sockbuf value                  per-socket buffer in bytes (default: 4194304)
   --smuxver value                  specify smux version, available 1,2 (default: 1)
   --smuxbuf value                  the overall de-mux buffer in bytes (default: 4194304)
   --streambuf value                per stream receive buffer in bytes, smux v2+ (default: 2097152)
   --keepalive value                seconds between heartbeats (default: 10)
   --snmplog value                  collect snmp to file, aware of timeformat in golang, like: ./snmp-20060102.log
   --snmpperiod value               snmp collect period, in seconds (default: 60)
   --log value                      specify a log file to output, default goes to stderr
   --quiet                          to suppress the 'stream open/close' messages
   --tcp                            to emulate a TCP connection(linux)
   -c value                         config from json file, which will override the command from shell
   --help, -h                       show help
   --version, -v                    print the version
   
➜  ~ ./server_linux_amd64 -h
NAME:
   kcptun - server(with SMUX)

USAGE:
   server_linux_amd64 [global options] command [command options] [arguments...]

VERSION:
   20190924

COMMANDS:
   help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --listen value, -l value         kcp server listen address, eg: "IP:29900" for a single port, "IP:minport-maxport" for port range (default: ":29900")
   --target value, -t value         target server address, or path/to/unix_socket (default: "127.0.0.1:12948")
   --key value                      pre-shared secret between client and server (default: "it's a secrect") [$KCPTUN_KEY]
   --crypt value                    aes, aes-128, aes-192, salsa20, blowfish, twofish, cast5, 3des, tea, xtea, xor, sm4, none (default: "aes")
   --mode value                     profiles: fast3, fast2, fast, normal, manual (default: "fast")
   --mtu value                      set maximum transmission unit for UDP packets (default: 1350)
   --sndwnd value                   set send window size(num of packets) (default: 1024)
   --rcvwnd value                   set receive window size(num of packets) (default: 1024)
   --datashard value, --ds value    set reed-solomon erasure coding - datashard (default: 10)
   --parityshard value, --ps value  set reed-solomon erasure coding - parityshard (default: 3)
   --dscp value                     set DSCP(6bit) (default: 0)
   --nocomp                         disable compression
   --sockbuf value                  per-socket buffer in bytes (default: 4194304)
   --smuxver value                  specify smux version, available 1,2 (default: 1)
   --smuxbuf value                  the overall de-mux buffer in bytes (default: 4194304)
   --streambuf value                per stream receive buffer in bytes, smux v2+ (default: 2097152)
   --keepalive value                seconds between heartbeats (default: 10)
   --snmplog value                  collect snmp to file, aware of timeformat in golang, like: ./snmp-20060102.log
   --snmpperiod value               snmp collect period, in seconds (default: 60)
   --pprof                          start profiling server on :6060
   --log value                      specify a log file to output, default goes to stderr
   --quiet                          to suppress the 'stream open/close' messages
   --tcp                            to emulate a TCP connection(linux)
   -c value                         config from json file, which will override the command from shell
   --help, -h                       show help
   --version, -v                    print the version

Multiport Dialer

kcptun supports multi-port dialer like below:

client: --remoteaddr IP:minport-maxport
server: --listen IP:minport-maxport

eg:
client: --remoteaddr IP:3000-4000
server: --listen 0.0.0.0:3000-4000

by specifying port-range, kcptun will automatically switch to next random port within port-range when establishing each new connection.

Forward Error Correction

In coding theory, the Reed–Solomon code belongs to the class of non-binary cyclic error-correcting codes. The Reed–Solomon code is based on univariate polynomials over finite fields.

It is able to detect and correct multiple symbol errors. By adding t check symbols to the data, a Reed–Solomon code can detect any combination of up to t erroneous symbols, or correct up to ⌊t/2⌋ symbols. As an erasure code, it can correct up to t known erasures, or it can detect and correct combinations of errors and erasures. Furthermore, Reed–Solomon codes are suitable as multiple-burst bit-error correcting codes, since a sequence of b + 1 consecutive bit errors can affect at most two symbols of size b. The choice of t is up to the designer of the code, and may be selected within wide limits.

FED

DSCP

Differentiated services or DiffServ is a computer networking architecture that specifies a simple, scalable and coarse-grained mechanism for classifying and managing network traffic and providing quality of service (QoS) on modern IP networks. DiffServ can, for example, be used to provide low-latency to critical network traffic such as voice or streaming media while providing simple best-effort service to non-critical services such as web traffic or file transfers.

DiffServ uses a 6-bit differentiated services code point (DSCP) in the 8-bit differentiated services field (DS field) in the IP header for packet classification purposes. The DS field and ECN field replace the outdated IPv4 TOS field.

setting each side with -dscp value, Here are some Commonly used DSCP values.

Cryptanalysis

kcptun is shipped with builtin packet encryption powered by various block encryption algorithms and works in Cipher Feedback Mode, for each packet to be sent, the encryption process will start from encrypting a nonce from the system entropy, so encryption to same plaintexts never leads to a same ciphertexts thereafter.

The contents of the packets are completely anonymous with encryption, including the headers(FEC,KCP), checksums and contents. Note that, no matter which encryption method you choose on you upper layer, if you disable encryption by specifying -crypt none to kcptun, the transmit will be insecure somehow, since the header is PLAINTEXT to everyone it would be susceptible to header tampering, such as jamming the sliding window size, round-trip time, FEC property and checksums. aes-128 is suggested for minimal encryption since modern CPUs are shipped with AES-NI instructions and performs even better than salsa20(check the table below).

Other possible attacks to kcptun includes: a) traffic analysis, dataflow on specific websites may have pattern while interchanging data, but this type of eavesdropping has been mitigated by adapting smux to mix data streams so as to introduce noises, perfect solution to this has not appeared yet, theroretically by shuffling/mixing messages on larger scale network may mitigate this problem. b) replay attack, since the asymmetrical encryption has not been introduced into kcptun for some reason, capturing the packets and replay them on a different machine is possible, (notice: hijacking the session and decrypting the contents is still impossible), so upper layers should contain a asymmetrical encryption system to guarantee the authenticity of each message(to process message exactly once), such as HTTPS/OpenSSL/LibreSSL, only by signing the requests with private keys can eliminate this type of attack.

Important:

  1. -crypt and -key must be the same on both KCP Client & KCP Server.
  2. -crypt xor is also insecure and vulnerable to known-plaintext attack, do not use this unless you know what you are doing. (cryptanalysis note: any type of counter mode is insecure in packet encryption due to the shorten of counter period and leads to iv/nonce collision)

Benchmarks for crypto algorithms supported by kcptun:

BenchmarkSM4-4                 	   50000	     32087 ns/op	  93.49 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES128-4              	  500000	      3274 ns/op	 916.15 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES192-4              	  500000	      3587 ns/op	 836.34 MB/s	       0 B/op	       0 allocs/op
BenchmarkAES256-4              	  300000	      3828 ns/op	 783.60 MB/s	       0 B/op	       0 allocs/op
BenchmarkTEA-4                 	  100000	     15359 ns/op	 195.32 MB/s	       0 B/op	       0 allocs/op
BenchmarkXOR-4                 	20000000	        90.2 ns/op	33249.02 MB/s	       0 B/op	       0 allocs/op
BenchmarkBlowfish-4            	   50000	     26885 ns/op	 111.58 MB/s	       0 B/op	       0 allocs/op
BenchmarkNone-4                	30000000	        45.8 ns/op	65557.11 MB/s	       0 B/op	       0 allocs/op
BenchmarkCast5-4               	   50000	     34370 ns/op	  87.29 MB/s	       0 B/op	       0 allocs/op
Benchmark3DES-4                	   10000	    117893 ns/op	  25.45 MB/s	       0 B/op	       0 allocs/op
BenchmarkTwofish-4             	   50000	     33477 ns/op	  89.61 MB/s	       0 B/op	       0 allocs/op
BenchmarkXTEA-4                	   30000	     45825 ns/op	  65.47 MB/s	       0 B/op	       0 allocs/op
BenchmarkSalsa20-4             	  500000	      3282 ns/op	 913.90 MB/s	       0 B/op	       0 allocs/op

Benchmark result from openssl

$ openssl speed -evp aes-128-cfb
Doing aes-128-cfb for 3s on 16 size blocks: 157794127 aes-128-cfb's in 2.98s
Doing aes-128-cfb for 3s on 64 size blocks: 39614018 aes-128-cfb's in 2.98s
Doing aes-128-cfb for 3s on 256 size blocks: 9971090 aes-128-cfb's in 2.99s
Doing aes-128-cfb for 3s on 1024 size blocks: 2510877 aes-128-cfb's in 2.99s
Doing aes-128-cfb for 3s on 8192 size blocks: 310865 aes-128-cfb's in 2.98s
OpenSSL 1.0.2p  14 Aug 2018
built on: reproducible build, date unspecified
options:bn(64,64) rc4(ptr,int) des(idx,cisc,16,int) aes(partial) idea(int) blowfish(idx)
compiler: clang -I. -I.. -I../include  -fPIC -fno-common -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -arch x86_64 -O3 -DL_ENDIAN -Wall -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-128-cfb     847216.79k   850770.86k   853712.05k   859912.39k   854565.80k

The encrytion performance in kcptun is as fast as in openssl library(if not faster).

Memory Control

Routers, mobile devices are susceptible to memory consumption; by setting GOGC environment(eg: GOGC=20) will make the garbage collector to recycle faster. Reference: https://blog.golang.org/go15gc

Primary memory allocation are done from a global buffer pool xmit.Buf, in kcp-go, when we need to allocate some bytes, we can get from that pool, and a fixed-capacity 1500 bytes(mtuLimit) will be returned, the rx queue, tx queue and fec queue all receive bytes from there, and they will return the bytes to the pool after using to prevent unnecessary zer0ing of bytes. The pool mechanism maintained a high watermark for slice objects, these in-flight objects from the pool will survive from the perodical garbage collection, meanwhile the pool kept the ability to return the memory to runtime if in idle, -sndwnd,-rcvwnd,-ds, -ps, these parameters affect this high watermark, the larger the value, the bigger the memory consumption will be.

-smuxbuf also affects the maximum memory consumption, this parameter maintains a subtle balance between concurrency and resource, you can increase this value(default 4MB) to boost concurrency if you have many clients to serve and you get a powerful server at the same time, and also you can decrease this value to serve only 1 or 2 clients and hope this program can run under some embedded SoC system with limited memory and only you can access. (Notice that the -smuxbuf value is not proprotional to concurrency, you need to test.)

Compression

kcptun has builtin snappy algorithms for compressing streams:

Snappy is a compression/decompression library. It does not aim for maximum compression, or compatibility with any other compression library; instead, it aims for very high speeds and reasonable compression. For instance, compared to the fastest mode of zlib, Snappy is an order of magnitude faster for most inputs, but the resulting compressed files are anywhere from 20% to 100% bigger.

Reference: http://google.github.io/snappy/

Compression may save bandwidth for PLAINTEXT data, it's quite useful for specific scenarios as cross-datacenter replications, by compressing the redologs in dbms or kafka-like message queues and then transfer the data streams across the continent can be much faster.

Compression is enabled by default, you can disable it by setting -nocomp on BOTH KCP Client & KCP Server MUST be IDENTICAL.

SNMP

type Snmp struct {
    BytesSent        uint64 // bytes sent from upper level
    BytesReceived    uint64 // bytes received to upper level
    MaxConn          uint64 // max number of connections ever reached
    ActiveOpens      uint64 // accumulated active open connections
    PassiveOpens     uint64 // accumulated passive open connections
    CurrEstab        uint64 // current number of established connections
    InErrs           uint64 // UDP read errors reported from net.PacketConn
    InCsumErrors     uint64 // checksum errors from CRC32
    KCPInErrors      uint64 // packet iput errors reported from KCP
    InPkts           uint64 // incoming packets count
    OutPkts          uint64 // outgoing packets count
    InSegs           uint64 // incoming KCP segments
    OutSegs          uint64 // outgoing KCP segments
    InBytes          uint64 // UDP bytes received
    OutBytes         uint64 // UDP bytes sent
    RetransSegs      uint64 // accmulated retransmited segments
    FastRetransSegs  uint64 // accmulated fast retransmitted segments
    EarlyRetransSegs uint64 // accmulated early retransmitted segments
    LostSegs         uint64 // number of segs infered as lost
    RepeatSegs       uint64 // number of segs duplicated
    FECRecovered     uint64 // correct packets recovered from FEC
    FECErrs          uint64 // incorrect packets recovered from FEC
    FECParityShards  uint64 // FEC segments received
    FECShortShards   uint64 // number of data shards that's not enough for recovery
}

Sending a SIGUSR1 signal to KCP Client or KCP Server will dump SNMP information to console, just like /proc/net/snmp. You can use this information to do fine-grained tuning.

Manual Control

https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration

-mode manual -nodelay 1 -interval 20 -resend 2 -nc 1

Low-level KCP configuration can be altered by using manual mode like above, make sure you really UNDERSTAND what these means before doing ANY manual settings.

Identical Parmeters

These parameters MUST be IDENTICAL on BOTH side:

  1. -key
  2. -crypt
  3. -nocomp
  4. -smuxver

References

  1. https://github.com/skywind3000/kcp -- KCP - A Fast and Reliable ARQ Protocol.
  2. https://github.com/xtaci/kcp-go/ -- A Production-Grade Reliable-UDP Library for golang
  3. https://github.com/klauspost/reedsolomon -- Reed-Solomon Erasure Coding in Go.
  4. https://en.wikipedia.org/wiki/Differentiated_services -- DSCP.
  5. http://google.github.io/snappy/ -- A fast compressor/decompressor.
  6. https://www.backblaze.com/blog/reed-solomon/ -- Reed-Solomon Explained.
  7. http://www.qualcomm.cn/products/raptorq -- RaptorQ Forward Error Correction Scheme for Object Delivery.
  8. https://en.wikipedia.org/wiki/PBKDF2 -- Key stretching.
  9. http://blog.appcanary.com/2016/encrypt-or-compress.html -- Should you encrypt or compress first?
  10. https://github.com/hashicorp/yamux -- Connection multiplexing library.
  11. https://tools.ietf.org/html/rfc6937 -- Proportional Rate Reduction for TCP.
  12. https://tools.ietf.org/html/rfc5827 -- Early Retransmit for TCP and Stream Control Transmission Protocol (SCTP).
  13. http://http2.github.io/ -- What is HTTP/2?
  14. http://www.lartc.org/ -- Linux Advanced Routing & Traffic Control
  15. https://en.wikipedia.org/wiki/Noisy-channel_coding_theorem -- Noisy channel coding theorem
  16. https://zhuanlan.zhihu.com/p/53849089 -- kcptun开发小记

(注意:我没有任何社交网站的账号,请小心骗子。)

kcptun's People

Contributors

ansen avatar brlin-tw avatar dependabot[bot] avatar eagleoflqj avatar fesily avatar fulirockx avatar haraldnordgren avatar imcotton avatar ithewei avatar jiangtiandao avatar mateomartin1998 avatar mitnk avatar monkeywithacupcake avatar networkextension avatar purplegrape avatar tete1030 avatar xtaci avatar yiffyi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kcptun's Issues

局域网上行带宽占满问题

近期在办公室应用 kcptun 时碰到以下问题:

  • GPON 非对称接入,下行 100Mbps,上行 5Mbps,x86 网关连接光猫,网关 PPPOE 拨号
  • kcptun + ss-redir 部署在网关
  • 如当前主要是 kcptun 下行,则表现良好:kcp client RX 可超过 5MBps,tcp TX 超过 1MBps,多路 kcp 下行(如 Youtube 1080P)稳定
  • 当有人通过 kcptun 上传(如 Google Drive)时,kcptun client 积极占用带宽,kcptun 至光猫流量超过 1MBps。此时其它 kcp 流量(无论上下行)都基本无法使用,甚至网关的 PPPOE 拨号断开并自动重连

该情况在办公室多人应用环境下非常突出,调节 kcptun 参数也没解决。现在正在考虑在 ss-redir 和 kcptun 之间使用 tc 做 QoS 来控制。

希望 kcptun 可实现简单的 QoS 控制 kcp TX 的总带宽。

问一个很基本问题

作者您好,我基本没有这方面的知识,不过想问一个问题,remote address: 118.26.142.194:36144,为什么端口号不是设置的29900呢?那么kcptun监听的端口号作用是什么呢?有点不太理解,不好意思,打扰了。

这发包是不是不太正常

我客户端才600k速度
然后服务端发送是4000多KB的速度...
最可怕的是客户端速度跑到1MB左右
服务端差不多用了10-12MB左右速度.....

建议分析现有丢包和冗余情况,并考虑进一步改进方向

建议分析现有情况:

  • 发送冗余度(重发比例)
  • 接收冗余度
  • 丢包率

方法和工具:

  • Debug log
  • 增加统计实现和 log
  • Wireshark extension

进一步改进方向:

  • ACK 和重发机制改进
  • FEC

现在直观的感受是接收端冗余度很高,应该有空间进一步提高吞吐率和带宽利用率。

加大conn导致多线程下载效果很糟

环境:
服务器:西雅图ubuntu16.04(64) kcptun + 3proxy (socks5)
-mtu 1400 -sndwnd 2048 -rcvwnd 2048 -mode fast2
客户端:win10(64) IDM + kcptun,100M宽带 (因为电脑用的无线,实测下载大概有70M)
-conn 4 -mtu 1400 -sndwnd 256 -rcvwnd 2048 -mode fast2
测试用的都是最新的23号的版本

当我把conn设置为1时,下载可以稳定到2~3MB/s,任务管理器里显示大概用了40M的带宽
然而随着conn设置增大,下载效果越来越糟糕,看上去一卡一卡的,根本下不动
理论上调大点应该效果更好吧?不知道瓶颈在哪里,会不会在cpu运算上?

顺便还有一个问题,chrome上代理看网页,用的还是相同的设置。当载入图片很多的网页时,其它网页根本打不开,全部卡住。不知道这是kcptun的锅还是3proxy的?

谢谢

20160623 conn=4 时 Dropbox 上传失败

很高兴看见 conn 的实现,对于大上行阻塞其它连接流量有帮助。但今天的测试中,使用 conn=4 在Chrome中向 dropbox.com 上传 10MB 文件始终失败。换成 20160605 SNMP 版本上传成功。所以我现在还是退回到自己用 20160605 SNMP 4进程加 pen 做负载均衡,近两周在小型办公场景中运行稳定,只是内存吃得比较厉害。

server端进程无故退出

版本:kcptun-linux-amd64-20160602.tar.gz
运行环境:CentOS Linux release 7.2.1511 (Core) x64位 512M内存的VPS
运行命令:./kcptun_server -t "127.0.0.1:1583" -l "0.0.0.0:1755" -mtu 1480 -key "xxxxx" >/dev/null 2>&1 &
现象:运行一段时间后server端进程消失

把运行日志输出到log文件,也只能看到某个stream open后就没有后继日志了,进程就退出了
而Ubuntu 14.04.4 x64 PC机上的客户端跑得很稳定

在快速 TCP RX 情况下的 QoS

在较大的 TCP 侧带宽情况下,即使使用 tc sfq 控制这一侧输入,KCP TX 队列仍会被少数大流量连接占慢,导致大量短连接响应缓慢。最典型的是从千兆以太局域网中向 pppoe 拨号的 WAN 上传大文件,会导致 web page 访问缓慢 主要原因是 kcp TX 使用的是 fifo 策略,在 TCP rx 快于 kcp TX 时不利于小流量连接。而由于 kcptun 进程的发出的 udp sport 一致,也无法在 kcp 侧 TX 上使用 tc sfq 来处理这一问题。

有两种处理方法:

  • kcptun client 连接 server 时使用多个 udp sport, 甚至为每个 TCP 连接分配不同的 udp sport。此时即可使用 tc sfq 进行 QoS 。
  • 在 kcp tx 上应用 TCP 连接信息,实现类似 tc sfq 的机制。此时无需外部的 tc sfq 即可改善短连接体验。

请支持一个 config.json 这样的配置

在以往的观察当中,更多用户喜欢 config.json 的配置。类似: ./kcp_server -c config.json

这样的好处是文件容易传输,密码什么的在里面。启动也方便。用 cli 常常忘记上次写的密码是什么,参数有哪些。

问一个很基本问题

作者您好,我基本没有这方面的知识,不过想问一个问题,remote address: 118.26.142.194:36144,为什么端口号不是设置的29900呢?那么kcptun监听的端口号作用是什么呢?有点不太理解,不好意思,打扰了。

CPU优化讨论

降低CPU的途径如下:

  1. NewCipher creates and returns a new cipher.Block. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. 即是在kcp-go中,所有NewCipher的地方,只传入pass[:16],执行AES-128加密,如果-key给的足够长,依然很安全(8位以上数字字母)
  2. 不加--tuncrypt,这是一层额外的加密,上层有TLS/SSL加密的情况下,是不需要加这个参数的。

stream closed

stream closed2016/06/15 21:33:24 stream closed
2016/06/15 21:33:24 [ERR] yamux: keepalive failed: i/o deadline reached
2016/06/15 21:33:24 [ERR] yamux: Failed to read header: broken pipe
2016/06/15 21:33:24 keepalive timeout

.

当然我不是这么无聊发个issue不是专门来赞你.

而是要顺便问问有没有人转成.Net的kcp-go库和kcptun? 最好是C#的.

最后还是感谢作者的努力, 让我看youtube从900 kbps变成20000kbps.

Milestone [Adaptive] Discussion!

Milestone: Adaptive

Features to be included:

  1. Adaptive FEC settings based on SNMP exchange
  2. Adaptive SetNoDelay() settings based on SNMP exchange
  3. MTU auto discovery
  4. KCP window auto-expansion & shrinking based on SNMP exchange
  5. Standardized UDP packet header format

Plan On : September, 2016

For everyone interested in this project, please express yourself.

至从用了 mtu 选项的版本,感觉没有以前好用,确认下。

现象是,百度什么很好访问,确认走代理。但是 google 偶尔可以偶尔不行,很频繁。

当选用加密的时候:
https://github.com/xtaci/kcp-go/blob/master/sess.go#L108

加密的 mtu 会比默认 减去 headerSize

但是为何 SetMtu 这里的时候又没有减去? 会有什么后果?

mtu 值需要客户端与服务器端的 mtu值能通,不被分片就可以了吧?不关新与其它服务器的 mtu 值的关系。

我准备去掉 Mtu 选项试试。

Milestone [STREAM_ARQ] Discussion!

Single connection ARQ will lead to HOL Blocking problem.
https://en.wikipedia.org/wiki/Head-of-line_blocking
QUIC solved this problem by stream based ARQ, not connection based.

Multiplexing

HTTP/2 on TCP suffers from head-of-line blocking in TCP. Since HTTP/2 multiplexes many streams atop TCP's single-bytestream abstraction, a loss of a TCP segment results in blocking of all subsequent segments until a retransmission arrives, irrespective of the HTTP/2 stream that is encapsulated in subsequent segments.

Because QUIC is designed from the ground up for multiplexed operation, lost packets carrying data for an individual stream generally only impact that specific stream. Each stream frame can be immediately dispatched to that stream on arrival, so streams without loss can continue to be reassembled and make forward progress in the application.

Caveat: QUIC currently compresses HTTP headers via HTTP/2 HPACK header compression on a dedicated header stream(3), which imposes head-of-line blocking for header frames only.

试了好几次现在根本就连不上了

2016/06/16 14:34:44 [ERR] yamux: keepalive failed: i/o deadline reached
2016/06/16 14:34:44 [ERR] yamux: Failed to read header: broken pipe
2016/06/16 14:34:44 stream closed

kcptun的应用场景

大神你好, 我看了kcptun 的issues大家的讨论, 貌似kcptun是用来做点对点tcp通信加速的?
不知道kcptun能否像shadowsock这样做proxy?

FEC问题讨论贴

  1. 下载文件speedtest基本上下载2-3MB之后就会断开。
  2. 视频有时断有时不断,另外视频的status里面显示的connection speed也不正常,我只有10mbps的宽带,但是他能飙到60多k。
  3. 在视频播放视频的同时打开其他网站会很困难。

我之前用的版本印象中没有出现过以上问题,应该是 a79537f 这个版本。

mode fast2
mtu 1464
mtu试过默认也没用
sndwnd和rcvwnd都是默认,服务端和客户端的版本、参数都是一样的
另外我是配合ss-libev一起用

下载断开时服务端的错误信息

2016/05/21 09:38:31 [ERR] yamux: Failed to read header: broken pipe
2016/05/21 09:38:31 broken pipe
2016/05/21 09:38:31 stream closed
2016/05/21 09:38:33 i/o timeout

下载断开时客户端的错误信息

2016/05/21 09:39:00 [ERR] yamux: keepalive failed: i/o deadline reached
2016/05/21 09:39:01 [ERR] yamux: Failed to read stream data: broken pipe
2016/05/21 09:39:01 [WARN] yamux: failed to send go away: session shutdown

closed

如题,已知软路由支持pptp代理,支持域名分流,支持多线DNS,是不是可以采用kcptun来连接pptp服务器端和客户端?

multi conn crashing (probably?)

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x2444]

goroutine 248 [running]:
panic(0x243de0, 0xc8200100c0)
/usr/local/go/src/runtime/panic.go:481 +0x3e6
main.handleClient(0x4c5b10, 0xc82002e000, 0x0, 0x0)
/Users/trivita/mydev/src/github.com/xtaci/kcptun/client/main.go:28 +0x404
created by main.main.func1
/Users/trivita/mydev/src/github.com/xtaci/kcptun/client/main.go:228 +0x2009

use of closed network connection

@xtaci 您好,我在

426 packets transmitted, 359 received, 15% packet loss, time 425007ms
rtt min/avg/max/mdev = 343.108/485.715/644.402/77.218ms

的网络环境(欧洲aws实时发送数据=>北京阿里云收到后返回200,traceroute -I 显示18跳)下进行测试。

client端部署在欧洲aws上,连接 client端的是4个node进程,keepalive的超时时间设置为2分钟。
server端部署在国内阿里云上,阿里云机器的带宽是10M,server端转发给nginx(server和nginx在同一台机器),nginx直接返回200。

4个node进程刚启动后,其中三个进程的套接字会涨到200左右,然后回落到20,另一个稳定在40左右。
之后client出现下面信息:

2016/03/19 11:03:09 read tcp 127.0.0.1:54321->127.0.0.1:46589: use of closed network connection
2016/03/19 11:03:10 stream **opened**
2016/03/19 11:03:10 <nil>
2016/03/19 11:03:10 stream closed
2016/03/19 11:03:10 read tcp 127.0.0.1:54321->127.0.0.1:46590: use of closed network connection
2016/03/19 11:03:11 stream opened
2016/03/19 11:03:11 <nil>
2016/03/19 11:03:11 stream closed
2016/03/19 11:03:11 read tcp 127.0.0.1:54321->127.0.0.1:46591: use of closed network connection
2016/03/19 11:03:11 stream opened
2016/03/19 11:03:11 <nil>
2016/03/19 11:03:11 stream closed
2016/03/19 11:03:11 read tcp 127.0.0.1:54321->127.0.0.1:46592: use of closed network connection
2016/03/19 11:03:12 stream opened
2016/03/19 11:03:12 <nil>
2016/03/19 11:03:12 stream closed
2016/03/19 11:03:12 read tcp 127.0.0.1:54321->127.0.0.1:46593: use of closed network connection
2016/03/19 11:03:12 <nil>
2016/03/19 11:03:12 stream closed
2016/03/19 11:03:12 read tcp 127.0.0.1:54321->127.0.0.1:46594: use of closed network connection
2016/03/19 11:03:12 stream opened
2016/03/19 11:03:12 <nil>
2016/03/19 11:03:12 stream closed

查看套接字,前三个进程的套接字还是稳定在20,另一个由40涨到200左后,最后降到20.,同时4个node 程序无法向client发送数据,出现异常信息

socket hang up

node 进程由pm2 守护,程序对异常有处理,当发生这类异常时,会尝试重新发送,但一直没能成功。

发送的数据大小平均为52981字节。

请问:

  1. 发生use of closed network connection的原因是什么,如何解决?(我之前加了连接池,可以避免这个错误的发生,但觉得不是最好的解决方案);
  2. 在这样的网络环境下,kcp的一些参数比如像窗口size的大小,怎样设置比较合理,依据是什么;
  3. 正常发送的数据大小大约是211924(测试时的4倍)字节,这样的数据大小kcp调整参数后,是否可以发送?(我尝试过2倍,发送不成功,卡住了。具体原因还没查)

期待您的回复,非常感谢!

ubuntu 16.04的服务器端 snappy: corrupt input 错误

2016/06/27 15:28:24 version: 20160627
2016/06/27 15:28:24 listening on [::]:29900
2016/06/27 15:28:24 encryption: aes
2016/06/27 15:28:24 nodelay parameters: 1 20 2 1
2016/06/27 15:28:24 sndwnd: 2048 rcvwnd: 2048
2016/06/27 15:28:24 compression: true
2016/06/27 15:28:24 mtu: 1400
2016/06/27 15:28:24 datashard: 10 parityshard: 3
2016/06/27 15:28:24 acknodelay: false
2016/06/27 15:28:24 dscp: 0
2016/06/27 15:28:58 remote address: 2xx.x.2x.41:37849
2016/06/27 15:28:58 [ERR] yamux: Failed to read header: snappy: corrupt input
2016/06/27 15:28:58 snappy: corrupt input
2016/06/27 15:28:58 remote address: 2xx.x.2x.41:37849
2016/06/27 15:28:58 [ERR] yamux: Failed to read header: snappy: corrupt input
2016/06/27 15:28:58 snappy: corrupt input
2016/06/27 15:28:58 remote address: 2xx.x.2x.41:37849
2016/06/27 15:28:58 [ERR] yamux: Failed to read header: snappy: corrupt input
2016/06/27 15:28:58 snappy: corrupt input
2016/06/27 15:28:58 remote address: 2xx.x.2x.41:37849
2016/06/27 15:28:58 [ERR] yamux: Failed to read header: snappy: corrupt input
2016/06/27 15:28:58 snappy: corrupt input

vps 为 ubuntu 16.04的系统,之前用cetos6.4 就没有问题

doesn't support ipv6?

I try to use kcptun with ipv6 but the kcplog show that . I think maybe the kcptun doesn't support ipv6 address,Could you please consider supporting IPv6 addresses?

配置问题,小白求助

客户端错误:

2016/06/25 20:51:58 version: 20160623
2016/06/25 20:51:59 listening on: [::]:12948
2016/06/25 20:51:59 encryption: aes
2016/06/25 20:51:59 nodelay parameters: 1 20 2 1
2016/06/25 20:51:59 remote address: 23.105.214.29:29900
2016/06/25 20:51:59 sndwnd: 256 rcvwnd: 2048
2016/06/25 20:51:59 mtu: 1400
2016/06/25 20:51:59 datashard: 10 parityshard: 3
2016/06/25 20:51:59 acknodelay: false
2016/06/25 20:51:59 dscp: 0
2016/06/25 20:51:59 conn: 4
2016/06/25 20:52:05 stream opened
2016/06/25 20:52:05 stream opened
...

服务端错误:

2016/06/25 08:49:17 version: 20160623
2016/06/25 08:49:17 listening on [::]:29900
2016/06/25 08:49:17 encryption: aes
2016/06/25 08:49:17 nodelay parameters: 1 20 2 1
2016/06/25 08:49:17 sndwnd: 2048 rcvwnd: 2048
2016/06/25 08:49:17 mtu: 1400
2016/06/25 08:49:17 datashard: 10 parityshard: 3
2016/06/25 08:49:17 acknodelay: false
2016/06/25 08:49:17 dscp: 0
2016/06/25 08:52:02 remote address: 113.251.58.186:16169
2016/06/25 08:52:02 stream opened
2016/06/25 08:52:02 stream closed
2016/06/25 08:52:02 remote address: 113.251.58.186:16170
2016/06/25 08:52:02 stream opened
2016/06/25 08:52:02 stream closed
2016/06/25 08:52:02 remote address: 113.251.58.186:16171
2016/06/25 08:52:02 stream opened
2016/06/25 08:52:02 stream closed
2016/06/25 08:52:02 remote address: 113.251.58.186:16172
2016/06/25 08:52:02 stream opened
2016/06/25 08:52:02 stream closed
2016/06/25 08:52:02 stream opened
2016/06/25 08:52:02 stream closed
2016/06/25 08:52:02 stream opened
2016/06/25 08:52:02 stream closed
2016/06/25 08:52:02 stream opened
...

客户端配置:

Dim RunKcptun
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
'获取文件路径
currentPath = fso.GetFile(Wscript.ScriptFullName).ParentFolder.Path & ""
'软件运行参数
exeConfig = "client_windows_amd64.exe -l :12948 -r 23.105.214.29:29900 -key test -mtu 1400 -sndwnd 256 -rcvwnd 2048 -mode fast2 -conn 4"
'日志文件
logFile = "kcptun.log"
'拼接命令行
cmdLine = "cmd /c " & currentPath & exeConfig & " > " & currentPath & logFile & " 2>&1"
'启动软件
WshShell.Run cmdLine, 0, False
'等待1秒
'WScript.Sleep 1000
'打印运行命令
'Wscript.echo cmdLine
Set WshShell = Nothing
Set fso = Nothing
'退出脚本
WScript.quit

服务端配置:

./server_linux_amd64 -l :29900 -t 127.0.0.1:443 -key test -mtu 1400 -sndwnd 2048 -rcvwnd 2048 -mode fast2 > kcptun.log 2>&1 &

服务器OS: Centos 6 x86_64 RAM:256
客户端OS: windows7 64
重庆电信光纤100M

我在用shadowsocks,参考的此教程:https://blog.kuoruan.com/102.html

MIPS32的路由器上部署成功,但性能不行,求助性能优化参数

首先感谢作者提供如此优秀的程序!

我先说一下我这边的情况,我的测试环境是mt7620方案的openwrt路由器,MIPS32-LE构架,是目前的主流家用路由器。kcptun交叉编译成功,也可以正常运行。但是因为MIPS32的CPU性能比较弱,所以隧道以后只能跑到网速只能达到2-3Mbps(使用tea加密),在PC上测试的时候可以轻松超过20Mbps。猜测可能和kcptun使用加密传输有关。

请问作者能否增加 --crypt none 参数?不加密直接传输?另外其他参数是否有可以降低CPU和内存消耗的用法?路由器跑go语言实在伤不起的,谢谢作者!

--crypt value methods for encryption: aes, tea (default: "aes")

运行报错:[ERR] yamux: Failed to read header: broken pipe

Sever / Debian 7.10 64bit (Openvz vps)
Clinet / Win10 64bit
kcptun version 20160517

Sever log

2016/05/17 11:53:05 version: 20160517
2016/05/17 11:53:05 listening on [::]:9999
2016/05/17 11:53:05 communication mode: fast
2016/05/17 11:53:05 sndwnd: 1024 rcvwnd: 1024
2016/05/17 11:53:05 mtu: 1350
2016/05/17 11:53:05 tunnel encryption: true
2016/05/17 11:53:16 remote address: clientip:43481
2016/05/17 11:53:23 dial tcp 127.0.0.1:12948: getsockopt: connection refused
2016/05/17 11:53:24 remote address: clientip:43481
2016/05/17 11:53:24 [ERR] yamux: Failed to read header: broken pipe
2016/05/17 11:53:26 i/o timeout
2016/05/17 11:53:46 remote address: clientip:43481
2016/05/17 11:53:48 i/o timeout
2016/05/17 11:53:53 remote address: clientip:43481
2016/05/17 11:53:55 i/o timeout

Client log

2016/05/17 11:53:16 version: 20160517
2016/05/17 11:53:16 listening on: [::]:8080
2016/05/17 11:53:16 communication mode: fast
2016/05/17 11:53:16 remote address: serverip:9999
2016/05/17 11:53:16 sndwnd: 1024 rcvwnd: 1024
2016/05/17 11:53:16 mtu: 1450
2016/05/17 11:53:16 tunnel encryption: true
2016/05/17 11:53:23 stream opened
2016/05/17 11:53:53 stream closed
2016/05/17 11:53:56 [ERR] yamux: keepalive failed: i/o deadline reached
2016/05/17 11:53:56 [ERR] yamux: Failed to read header: broken pipe

请问我该如何进一步调试。

2016/06/27

2016/06/27 02:57:02 remote address: *************:28429
2016/06/27 02:57:02 [ERR] yamux: Failed to read header: snappy: corrupt input
2016/06/27 02:57:02 snappy: corrupt input
这个是上面原因造成的~

Does KCPTUN support IPv6

if not, pls add the ipv6 support.
if so, pls tell me how to config the client when ipv6 addr is used.

有效载荷比讨论

根据观察,下行的chrome/kcptun流量的有效载荷比大约是1:2,即50%的有效载荷,不考虑上行。

是否能根据某种方法,比如依照香农定理,丢包作为噪音,计算出最大带宽。

另外一个问题是,延迟,带宽占用,有效载荷比,是不是一个不可解决的问题,或者理论极限是什么?

还需要考虑在ADSL这种非对称流量情况。

@yaleh @jannson

Out of Memory

digitalocean vps: 512MB with 512MB swap

In client side, using wget to fetch a big file(~500MB), the server killed because OOM.

感觉文字说明有些费解。

“tcp网络程序的传输承载”,这个怎么理解?是说用kcptun可以代替标准tcp达到更好的效果,还是说其他?如果是我估计的这个意思,建议直接说“是标准TCP的更好替代品”。

broken pipe是怎么?

[ERR] yamux: keepalive failed: i/o deadline reached
[ERR] yamux: Failed to read header: broken pipe

客户端DNS解析问题

客户端的-r参数使用域名时会出现dns无法解析,报错信息如下
2016/06/27 14:56:28 lookup xxx.xxx on 223.5.5.5:53: dial udp 223.5.5.5:53: i/o timeout.
ping 该域名能ping通,并且能解析到正确的ip地址

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.