2020-07-22 02:04:02 +02:00
|
|
|
import asyncdispatch, asyncnet, os, sequtils, strformat, strutils, tables
|
|
|
|
from nativesockets import htonl
|
|
|
|
from net import IpAddress, Port, getPrimaryIPAddr, parseIpAddress, `$`
|
|
|
|
import ../../asyncutils
|
2020-07-06 15:10:10 +02:00
|
|
|
import ../../message
|
2020-07-22 02:04:02 +02:00
|
|
|
import ../../network_interface
|
2020-07-06 15:10:10 +02:00
|
|
|
|
|
|
|
type
|
2020-07-07 19:34:34 +02:00
|
|
|
Client = object
|
|
|
|
sock: AsyncSocket
|
|
|
|
ip: IpAddress
|
2020-08-26 21:39:17 +02:00
|
|
|
ports: seq[Port]
|
2020-07-07 19:34:34 +02:00
|
|
|
|
|
|
|
# Requests
|
2020-07-06 15:10:10 +02:00
|
|
|
Register = object
|
|
|
|
peerId: string
|
|
|
|
ip: IpAddress
|
2020-08-26 21:39:17 +02:00
|
|
|
ports: seq[Port]
|
2020-07-06 15:10:10 +02:00
|
|
|
|
2020-07-26 17:48:47 +02:00
|
|
|
GetPeerinfo = object
|
2020-07-06 15:10:10 +02:00
|
|
|
peerId: string
|
|
|
|
|
|
|
|
NotifyPeer = object
|
|
|
|
sender: string
|
|
|
|
recipient: string
|
|
|
|
data: string
|
|
|
|
|
2020-07-22 02:04:02 +02:00
|
|
|
proc isPrivateIp(ip: IpAddress): bool =
|
|
|
|
const ranges: array[5, tuple[first: IpAddress, last: IpAddress]] =
|
|
|
|
[(parseIpAddress("10.0.0.0"), parseIpAddress("10.255.255.255")),
|
|
|
|
(parseIpAddress("172.16.0.0"), parseIpAddress("172.31.255.255")),
|
|
|
|
(parseIpAddress("192.168.0.0"), parseIpAddress("192.168.255.255")),
|
|
|
|
(parseIpAddress("169.254.0.0"), parseIpAddress("169.254.255.255")),
|
|
|
|
(parseIpAddress("127.0.0.0"), parseIpAddress("127.255.255.255"))]
|
|
|
|
for r in ranges:
|
|
|
|
let ipScalar = htonl(cast[uint32](ip.address_v4))
|
|
|
|
if ipScalar > htonl(cast[uint32](r.first.address_v4)) and
|
|
|
|
ipScalar < htonl(cast[uint32](r.last.address_v4)):
|
|
|
|
return true
|
|
|
|
return false
|
|
|
|
|
|
|
|
proc isInNetwork(ip: IpAddress, iface: NetworkInterface): bool =
|
|
|
|
let ipScalar = htonl(cast[uint32](ip.address_v4))
|
|
|
|
let ifaceIpScalar = htonl(cast[uint32](iface.ipAddress.address_v4))
|
2020-07-25 12:00:45 +02:00
|
|
|
let netmaskScalar = htonl(cast[uint32](iface.netMask.address_v4))
|
2020-07-22 02:04:02 +02:00
|
|
|
(ipScalar and netmaskScalar) == (ifaceIpScalar and netmaskScalar)
|
|
|
|
|
|
|
|
proc probePublicIp(): Future[IpAddress] {.async.} =
|
2020-10-15 19:20:51 +02:00
|
|
|
# FIXME: need more reliable solution
|
2020-07-22 02:04:02 +02:00
|
|
|
let output = await asyncExecCmd("ping -R -c 1 -s 1 -n 193.0.14.129")
|
|
|
|
let ipLines = output.splitLines()
|
|
|
|
.filter(proc(l: string): bool = l.startsWith("\t") or l.startsWith("RR:"))
|
|
|
|
.map(proc(l: string): string = l.strip(true, false, {'R', ':', '\t', ' '}))
|
|
|
|
for line in ipLines:
|
|
|
|
let ipAddr = parseIpAddress(line)
|
|
|
|
if not isPrivateIp(ipAddr):
|
|
|
|
return ipAddr
|
|
|
|
block:
|
|
|
|
raise newException(OSError, "cannot probe public IP address")
|
|
|
|
|
2020-07-06 15:10:10 +02:00
|
|
|
proc removeClient(clients: TableRef[string, Client], peerId: string) =
|
|
|
|
if peerId.len > 0: clients.del(peerId)
|
|
|
|
|
2020-07-26 17:46:17 +02:00
|
|
|
proc sendEndpoint(client: AsyncSocket, requestId: string) {.async.} =
|
2020-07-22 02:04:02 +02:00
|
|
|
let (address, port) = client.getPeerAddr()
|
|
|
|
var ipAddr = parseIpAddress(address)
|
|
|
|
if ipAddr.isPrivateIp() and
|
2020-10-12 21:37:22 +02:00
|
|
|
ipAddr.isInNetwork(getNetworkInterface(getPrimaryIPAddr(ipAddr))):
|
2020-07-22 02:04:02 +02:00
|
|
|
ipAddr = await probePublicIp()
|
2020-07-26 17:46:17 +02:00
|
|
|
await client.send(&"ok|{requestId}|{ipAddr}|{port.int}\n")
|
|
|
|
client.close
|
|
|
|
|
|
|
|
proc processClient(client: AsyncSocket,
|
|
|
|
clients: TableRef[string, Client]) {.async.} =
|
2020-07-06 15:10:10 +02:00
|
|
|
var id = ""
|
|
|
|
var peerId = ""
|
|
|
|
while true:
|
2020-07-21 10:17:36 +02:00
|
|
|
var line = await client.recvLine(maxLength = 400)
|
|
|
|
line = line.strip(leading = false, trailing = true, chars = {'\r', '\n'})
|
2020-07-06 15:10:10 +02:00
|
|
|
if line.len == 0:
|
|
|
|
removeClient(clients, peerId)
|
|
|
|
break
|
|
|
|
try:
|
2020-07-26 17:46:17 +02:00
|
|
|
let args = line.parseArgs(3, 1)
|
2020-07-06 15:10:10 +02:00
|
|
|
id = args[1]
|
|
|
|
case args[0]:
|
|
|
|
of "register":
|
|
|
|
let req = parseMessage[Register](args[2])
|
2020-07-26 17:46:17 +02:00
|
|
|
echo "register: ", req
|
2020-07-06 15:10:10 +02:00
|
|
|
peerId = req.peerId
|
|
|
|
clients[peerId] = Client(sock: client, ip: req.ip, ports: req.ports)
|
|
|
|
asyncCheck client.send(&"ok|{id}\n")
|
2020-07-26 17:46:17 +02:00
|
|
|
of "get-endpoint":
|
|
|
|
echo "get-endpoint"
|
|
|
|
asyncCheck client.sendEndpoint(id)
|
|
|
|
removeClient(clients, peerId)
|
|
|
|
break
|
2020-07-26 17:48:47 +02:00
|
|
|
of "get-peerinfo":
|
|
|
|
let req = parseMessage[GetPeerinfo](args[2])
|
2020-07-26 17:46:17 +02:00
|
|
|
echo "get-info: ", req
|
2020-07-06 15:10:10 +02:00
|
|
|
let peer = clients[req.peerId]
|
|
|
|
let peerPorts = peer.ports.join(",")
|
|
|
|
asyncCheck client.send(&"ok|{id}|{peer.ip}|{peerPorts}\n")
|
|
|
|
of "notify-peer":
|
|
|
|
let req = parseMessage[NotifyPeer](args[2])
|
2020-07-26 17:46:17 +02:00
|
|
|
echo "notify-peer: ", req
|
2020-07-06 15:10:10 +02:00
|
|
|
let recipient = clients[req.recipient]
|
|
|
|
asyncCheck recipient.sock.send(&"notify-peer|{req.sender}|{req.recipient}|{req.data}\n")
|
|
|
|
asyncCheck client.send(&"ok|{id}\n")
|
|
|
|
else:
|
2020-07-26 17:46:17 +02:00
|
|
|
echo "invalid request"
|
2020-07-06 15:10:10 +02:00
|
|
|
client.close()
|
|
|
|
removeClient(clients, peerId)
|
|
|
|
break
|
|
|
|
|
|
|
|
except KeyError:
|
|
|
|
asyncCheck client.send(&"error|{id}|peer not registered\n")
|
|
|
|
|
|
|
|
except ValueError:
|
2020-07-26 17:46:17 +02:00
|
|
|
echo "invalid message"
|
2020-07-06 15:10:10 +02:00
|
|
|
client.close
|
|
|
|
removeClient(clients, peerId)
|
|
|
|
break
|
|
|
|
|
|
|
|
proc serve(port: Port) {.async.} =
|
2020-10-07 00:07:45 +02:00
|
|
|
# FIXME: causes Error: unhandled exception: Too many open files [OSError] after a while
|
2020-07-06 15:10:10 +02:00
|
|
|
var clients = newTable[string, Client]()
|
|
|
|
var server = newAsyncSocket()
|
|
|
|
server.setSockOpt(OptReuseAddr, true)
|
|
|
|
server.bindAddr(port)
|
|
|
|
server.listen()
|
|
|
|
|
|
|
|
while true:
|
|
|
|
let client = await server.accept()
|
|
|
|
asyncCheck processClient(client, clients)
|
|
|
|
|
|
|
|
proc main() =
|
|
|
|
if paramCount() != 1:
|
2020-10-23 01:21:19 +02:00
|
|
|
echo(&"usage: {paramStr(0)} PORT")
|
2020-07-06 15:10:10 +02:00
|
|
|
quit(1)
|
|
|
|
|
|
|
|
try:
|
|
|
|
let portNumber = paramStr(1).parseUInt
|
|
|
|
if portNumber > uint16.high:
|
|
|
|
raise newException(ValueError, "port out of range")
|
|
|
|
let port = Port(portNumber)
|
|
|
|
asyncCheck serve(port)
|
|
|
|
runForever()
|
|
|
|
|
|
|
|
except ValueError as e:
|
|
|
|
echo e.msg
|
|
|
|
|
|
|
|
when isMainModule:
|
|
|
|
main()
|