作者归档:softsim

python录制音频

import pyaudio
import wave
 
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 10
WAVE_OUTPUT_FILENAME = "file.wav"
 
audio = pyaudio.PyAudio()
 
# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
                rate=RATE, input=True,
                frames_per_buffer=CHUNK)
print("recording...")
frames = []
 
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print("finished recording")
 
 
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()
 
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

默认录制10秒

给headscale安装单独的DERP服务

headscale 内建 DERP服务, 在配置里启用即可

但是为了更好地中继, 可以在其他节点建立DERP中继服务

0. 先安装一个 Tailscale 客户端并注册到 Headscale

这样做的目的是让搭建的 DERP Server 开启客户端认证

1. 安装DERP

#  安装 DERP Server 
go install tailscale.com/cmd/derper@main

2. 验证

# derper --hostname=your-hostname.com --verify-clients

2022/11/25 10:19:35 no config path specified; using /var/lib/derper/derper.key
2022/11/25 10:19:35 derper: serving on :443 with TLS
2022/11/25 10:19:35 running STUN server on [::]:3478

derper –hostname=域名 -c $HOME/derper.conf -http-port -1 -a :81 –verify-clients=true –stun

解释
如果不指定 -a 参数, 则默认监听 :443
如果监听 :443 并且未指定 –certmode=manual 选项,就会 自动强制使用 –hostname 指定的域名进行 ACME 申请证书
指定了 -a 为非 :443 端口, 且没有指定 –certmode=manual 则只监听 HTTP

2.

# 复制到系统可执行目录
mv ${GOPATH}/bin/derper /usr/local/bin

setcap cap_net_bind_service=+ep  /usr/local/bin/derper

# 创建用户和运行目录
useradd \
        --create-home \
        --home-dir /var/lib/derper/ \
        --system \
        --user-group \
        --shell /usr/sbin/nologin \
        derper

3. systemd配置
/lib/systemd/system/derper.service
或者 /etc/systemd/system/derper.service

[Unit]
Description=tailscale derper server
After=syslog.target
After=network.target

[Service]
Type=simple
User=derper
Group=derper
ExecStart=/usr/local/bin/derper -c=/var/lib/derper/derper.key -a=:8989 -stun-port=3456 -verify-clients
Restart=always
RestartSec=5

# Optional security enhancements
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/derper /var/run/derper
AmbientCapabilities=CAP_NET_BIND_SERVICE
RuntimeDirectory=derper

[Install]
WantedBy=multi-user.target

4. 启动

systemctl enable derper --now

5. 在headscale服务器上修改配置,以启用这个DERP

/etc/headscale/derper.yaml
内容为

regions:
  901:
    regionid: 901
    regioncode: cn
    regionname: "CUCC LTE"
    nodes:
      - name: cucc-derper
        regionid: 901
        # 自行更改为自己的域名
        hostname: derper.xxxxx.com
        # Derper 节点的 IP
        # ipv4: 123.123.123.123 可以不社会自
        # Derper 设置的 STUN 端口
        stunport: 3456
        stunonly: false  ###表示除了使用 STUN 服务,还可以使用 DERP 服务
        derpport: 23456   ## 默认是443

https://derp.XXXX.ccom:23456 应该能看到一个页面

6. 修改 /etc/headscale/config.yaml 的内容

derp:
  server:
    # 这里关闭 Headscale 内置的 Derper Server
    enabled: false

  # urls 留空, 保证不加载官方的默认 Derper
  urls: []


  # 这里填写 Derper 节点信息配置的绝对路径
  paths:
  - /etc/headscale/derper.yaml

  # If enabled, a worker will be set up to periodically
  # refresh the given sources and update the derpmap
  # will be set up.
  auto_update_enabled: true

  # How often should we check for DERP updates?
  update_frequency: 24h

重启headscale服务
重启客户端, 在客户端运行

tailscale netcheck

应该可以看到添加的DERP中继服务

参考资料:
https://mritd.com/2022/10/19/use-headscale-to-build-a-p2p-network/

参数

-a string
server HTTPS listen address, in form “:port”, “ip:port”, or for IPv6 “[ip]:port”. If the IP is omitted, it defaults to all interfaces. (default “:443”)

-c string
config file path

-certdir string
directory to store LetsEncrypt certs, if addr’s port is :443 (default “/root/.cache/tailscale/derper-certs”)

-certmode string
mode for getting a cert. possible options: manual, letsencrypt (default “letsencrypt”)

-hostname string
LetsEncrypt host name, if addr’s port is :443 (default “derp.tailscale.com”)

-http-port int
The port on which to serve HTTP. Set to -1 to disable. The listener is bound to the same IP (if any) as specified in the -a flag. (default 80)

-stun
whether to run a STUN server. It will bind to the same IP (if any) as the –addr flag value. (default true)

-stun-port int
The UDP port on which to serve STUN. The listener is bound to the same IP (if any) as specified in the -a flag. (default 3478)

从代码看,如果不指定config, 且以root执行, /var/lib/derper/derper.key 就是配置文件

keyname := unsafeHostnameCharacters.ReplaceAllString(hostname, “”)
crtPath := filepath.Join(certdir, keyname+”.crt”)
keyPath := filepath.Join(certdir, keyname+”.key”)

安装headscale

官方文档
https://github.com/juanfont/headscale/blob/main/docs/running-headscale-linux.md

1. 下载编译好的二进制程序

wget --output-document=/usr/local/bin/headscale \
   https://github.com/juanfont/headscale/releases/download/v0.17.0-beta4/headscale_0.17.0-beta4_linux_amd64

 https://github.com/juanfont/headscale/releases/download/v0.17.0-beta5/headscale_0.17.0-beta5_linux_amd64

根据实际情况,修改下载地址

下载地址 可以在 https://github.com/juanfont/headscale/releases 查看

2. 加上可执行属性

chmod +x /usr/local/bin/headscale

3. 创建必要的目录来 存储配置文件和数据库, 创建一个headscale用户(创建用户可以选做)

# Directory for configuration

mkdir -p /etc/headscale

# Directory for Database, and other variable data (like certificates)
mkdir -p /var/lib/headscale


# or if you create a headscale user:
useradd \
	--create-home \
	--home-dir /var/lib/headscale/ \
	--system \
	--user-group \
	--shell /usr/bin/nologin \
	headscale

4. 生成空的数据库文件

touch /var/lib/headscale/db.sqlite

5. 下载配置文件,放到合适的目录

wget https://github.com/juanfont/headscale/raw/main/config-example.yaml -O /etc/headscale/config.yaml

6. 修改配置文件

server_url:  https://headscale.softs.im
listen_addr: 127.0.0.1:8080
grpc_listen_addr: 0.0.0.0:50443
grpc_allow_insecure: true    这个应该保持为false
private_key_path: /var/lib/headscale/private.key
private_key_path: /var/lib/headscale/noise_private.key
db_path: /var/lib/headscale/db.sqlite
unix_socket: /var/run/headscale.sock
randomize_client_port: true      随机端口 这个设置建议打开,否则同一个内网中多个终端会有问题

其实没有怎么修改, 主要是修改了 server_url, 几个文件型的路径,都按照注释里给的建议,进行修改的

因为服务器还跑了其他网站,也要占用443端口, 所以 我用caddy进行反向代理, listen_addr地址设置为 127.0.0.1:8080

7. 临时让 服务跑在tmux里,方便调试

#  headscale serve

8. 切到tmux另外的标签,以普通用户运行

$  curl http://127.0.0.1:9090/metrics

应该可以看到正常运行

9. 创建namespace, 也就是创建一个网络, 等下其他节点都加入进来

headscale namespaces create softeam
查看命令空间


10. 注册一个客户端
1) 在客户端机器上执行

       tailscale up --login-server YOUR_HEADSCALE_URL

2) 在 headscale服务器上确认

headscale --namespace myfirstnamespace      nodes register --key nodekey:the_key

也可以用预授权的方法
服务器上执行

headscale --namespace myfirstnamespace preauthkeys create --reusable --expiration 24h

客户端上执行

tailscale up --login-server YOUR_HEADSCALE_URL --authkey  YOUR_AUTH_KEY

11. 改用systemd的方式 而不是tmux的方式,执行在后台
创建一个 /etc/systemd/system/headscale.service 文件, 内容为

[Unit]
Description=headscale controller
After=syslog.target
After=network.target

[Service]
Type=simple
User=headscale
Group=headscale
ExecStart=/usr/local/bin/headscale serve
Restart=always
RestartSec=5

# Optional security enhancements
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/headscale /var/run/headscale
AmbientCapabilities=CAP_NET_BIND_SERVICE
RuntimeDirectory=headscale

[Install]
WantedBy=multi-user.target

12. 将当前用户添加到 headscale 组

usermod -a -G headscale current_user

或者将之后的所有命令都切换到 headscale分生执行

su - headscale

13. 将 /etc/headscale/config.yaml 配置中的

unix_socket: /var/run/headscale/headscale.sock

14. 启动 并验证

systemctl daemon-reload
systemctl enable --now headscale
systemctl status headscale
curl http://127.0.0.1:9090/metrics

15 . 其他命令

查看网络/空间
headscale namespaces list


查看所有节点
headscale nodes  list 


删除 ID为1 的节点机器
headscale nodes  delete  -i 1


查看日志

journalctl -xefu headscale


安装Tailscale客户端

0. 安装key

curl -fsSL https://pkgs.tailscale.com/stable/debian/bullseye.noarmor.gpg |  tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
curl -fsSL https://pkgs.tailscale.com/stable/debian/bullseye.tailscale-keyring.list |  tee /etc/apt/sources.list.d/tailscale.list

或者
curl -fsSL https://pkgs.tailscale.com/stable/debian/bookworm.noarmor.gpg |  tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
curl -fsSL https://pkgs.tailscale.com/stable/debian/bookworm.tailscale-keyring.list |  tee /etc/apt/sources.list.d/tailscale.list

1. 安装Tailscale

# apt update
# apt install tailscale

2. 注册并连接

tailscale up --login-server=http://headscale.softs.im:8080 --accept-routes=true --accept-dns=false

它会生成一个key并 通知healscale

https://headscale.softs.im/register/nodekey:1fd6a7cb0b68ce395465d2d5720c531d8c0fd7f2345f9ab71ee0b37463408024

在headscale机器上,进行确认

headscale -n softeam nodes register --key nodekey:1fd6a7cb0b68ce395465d2d5720c531d8c0fd7f2345f9ab71ee0b37463408024

确认后, 注册命令会自动成功, 因为它每秒都在向 tailscale进行查询

3. 断开

tailscale down

4. 注销

tailscale logout

5. 通过主机名 查到对方的IP

 tailscale ip  peer_hostname

如果不提供hostname, 就是查自己的IP

6. ping 对方结点

tailscale ping  hostname-or-ip

7.查看网络报告

tailscale netcheck

8. 查看连接状态

tailscale status
fd7a:115c:a1e0::1 voice                voiceteam    linux   -
fd7a:115c:a1e0::2 racknerd             voiceteam    linux   active; direct [2001:2002:2003:2004::9999]:41641, tx 9288 rx 7896

可以看出来, 到racknerd是通过IPV6直连的

Linux测试path mtu

ping   -c 2  -M do  -4    -s  1472      192.168.1.1
PING 192.168.1.1 (192.168.1.1) 1472(1500) bytes of data.
1480 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.680 ms
1480 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=1.15 ms

因为加上icmp的header长度为28, payload最多只能为1472, 因为ethernet的mtu是1500

ping -c 2 -M do -4 -s 1372 114.114.114.114
ping -c 2 -M do -4 -s 1372 218.104.111.122 (联通)

IPv6

ping   -c 2  -M do  -6    -s  1384      2408:8888::8
ping   -c 2  -M do  -6    -s  1384      www.qq.com

IPv4 header (20 bytes)
IPv6 header (40 bytes)

实际测试, IPV6路由设备比较新, 反而可以带更多数据

在阿里云上 连接 he.net

ping   -c 2  -M do  -4    -s  1472      he.net

ethernet 14
ipv4 20
ip 1480-1464 = 16
payload 1464

无线数据网络 4G LTE/5G NR MTU居然只有 1400

Some US based cellular networks require a lower than default MTU to be used on our router’s PPP interface.
If the MTU is left as the default value, the result will be that packets larger than the network maximum will be discarded. This shows up as web pages not displaying in the web browser when using our cellular router as a gateway to the internet.

Recommended values are:
AT&T 1420 bytes
Verizon 1428 bytes
Others 1430 bytes
(PPP interface default is 1500 bytes)

To ensure our routers work well on all carriers. set the PPP interface local and remote MRU to 1420.

Via CLI (telnet / SSH / ‘Execute a command’ in the GUI):
ppp 1 l_mru 1400
ppp 1 r_mru 1400
config 0 save
ppp 1 deact_rq

在VPS上测试google

 
ping   -c 2  -M do  -6    -s  1452      www.google.com
ping   -c 2  -M do  -4    -s  1472      www.google.com

恰好说明IPV6 头部 比 IPV4大20字节

电信 5G 对 电信5G, 也是 1452

ping -c 2 -M do -6 -s 1432 国外
ping -c 2 -M do -6 -s 1452 240e:d:1000:100::6

少的这20个字节,是 tb 😃

OpenGNB

OpenGNB 是一个开源的 P2P 去中心化的具有极致的内网穿透能力的软件自定义虚拟网络(Software Defined Virtual Network),可以让你把公司-家庭网络组成直接访问的局域网。

1. 极致的链路能力

内网穿透,无需公网IP,无限速影响,upnp,multi index,port detect,multi socket 等策略实现内网穿透
Discover in lan 自动发现局域网内其他节点建立 P2P 通信
Unified Forwarding 自动通过已经建立 P2P 通信的节点转发 IP 分组,多节点重传 IP 分组
Relay Forwarding 高度自定义中继路由,IP 分组发往下一个中继点前都会作加密处理
Standard Forwarding 用尽一切办法无法建立起 P2P 通信的节点可以通过位于公网 forward 节点中继 IP 分组

2. 数据安全
基于椭圆曲线数字签名实现可靠的身份验证
根据时间同步变更通信密钥
默认选项下对日志中的敏感信息进行隐藏

3. 多平台支持
GNB 用 C 语言开发,项目相关代码以开源方式发布, 编译时不需要引用第三方库文件,可以方便移植到当前流行的操作系统上,目前支持的操作系统及平台有 Linux_x86_64,Windows10_x86_64, macOS,FreeBSD_AMD64,OpenBSD_AMD64,树莓派,OpenWRT;大至服务器环境,桌面系统,小至仅有 32M 内存的OpenWRT路由器都能很好的运行 GNB 网络。


GNB节点间通过UDP协议传输数据,在一些网络环境下的路由器/防火墙会对UDP分组实施QOS策略,因此通过tcp链路转发GNB数据是不需要改动GNB通讯协议又可以提升GNB网络适应能力的一个办法。

gnb_udp_over_tcp是一个为 GNB 开发的通过 tcp 链路中转 UDP 分组转发的服务,也可以为其他基于 UDP 协议的服务中转数据。

tailscale

基于wireguard的mess vpn

headscale
https://github.com/juanfont/headscale

netmaker
https://github.com/gravitl/netmaker

innernet
https://github.com/tonarino/innernet

wesher
https://github.com/costela/wesher

tuic

https://github.com/EAimTY/tuic

Delicately-TUICed high-performance proxy built on top of the QUIC protocol

TUIC’s goal is to minimize the handshake latency as much as possible

用Rust编写的

nftables

由三个主要组件组成:内核实现、libnl netlink通信和nftables用户空间前端。 内核提供了一个netlink配置接口以及运行时规则集评估,libnl包含了与内核通信的基本函数,nftables前端是用户通过nft交互。

nftables 区分 命令行输入的临时规则 和 从文件加载或保存到文件的永久规则。
默认配置文件是/etc/nftables.conf,其中已经包含一个名为inet filter的简单ipv4/ipv6防火墙列表

#!/usr/sbin/nft -f

flush ruleset

table inet filter {
	chain input {
		type filter hook input priority filter;
	}
	chain forward {
		type filter hook forward priority filter;
	}
	chain output {
		type filter hook output priority filter;
	}
}

默认是关闭的

systemctl status  nftables
○ nftables.service - nftables
     Loaded: loaded (/lib/systemd/system/nftables.service; disabled; preset: enabled)
     Active: inactive (dead)

启用它
systemctl enable nftables
systemctl start nftables

iptables的缺点

iptables框架在内核态知道的太多,以至于产生了大量的代码冗余。
iptables的rule结构设计不合理。

检查 命令行 规则集

 nft list ruleset

列出所有的表

nft list tables