move injectTcpPacket to raw_socket module

This commit is contained in:
Christian Ulrich 2020-10-22 17:04:20 +02:00
parent 504ff6795a
commit 2c5ce97fca
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
2 changed files with 13 additions and 16 deletions

View File

@ -1,9 +1,7 @@
import asyncdispatch, strformat
from net import IpAddress, Port, `$`, toSockAddr
from nativesockets import SockAddr, Sockaddr_storage, SockLen
from net import IpAddress, Port, `$`
from sequtils import any
import asyncutils
import ip_packet
type
Attempt = tuple | object
@ -30,18 +28,6 @@ proc findAttemptsByLocalAddr*(puncher: Puncher[Attempt], address: IpAddress,
if attempt.srcIp == address and attempt.srcPort == port:
result.add(attempt)
proc injectTcpPacket*(rawFd: AsyncFD, ipPacket: IpPacket) {.async.} =
assert(ipPacket.protocol == tcp)
try:
let packet = serialize(ipPacket)
var sockaddr: Sockaddr_storage
var sockaddrLen: SockLen
toSockAddr(ipPacket.ipAddrDst, ipPacket.tcpPortDst, sockaddr, sockaddrLen)
await rawFd.sendTo(packet.cstring, packet.len,
cast[ptr SockAddr](addr sockaddr), sockaddrLen)
except OSError as e:
raise newException(PunchHoleError, e.msg)
proc makeFirewallRule(srcIp: IpAddress, srcPort: Port,
dstIp: IpAddress, dstPort: Port): string =
# FIXME: use & instead of fmt?

View File

@ -5,8 +5,10 @@ from nativesockets import
SOCK_RAW,
bindAddr,
htons
from posix import setsockopt, SockAddr, SockLen, SocketHandle
from net import toSockAddr
from posix import setsockopt, SockAddr, Sockaddr_storage, SockLen, SocketHandle
import network_interface
import ip_packet
type
RawSocketError* = object of CatchableError
@ -78,3 +80,12 @@ proc setupTcpInjectingSocket*(): AsyncFD =
sizeof(sockOpt).SockLen) != 0:
closeSocket(result)
raise newException(RawSocketError, "cannot set IP_HDRINCL option")
proc injectTcpPacket*(rawFd: AsyncFD, ipPacket: IpPacket) {.async.} =
assert(ipPacket.protocol == tcp)
let packet = serialize(ipPacket)
var sockaddr: Sockaddr_storage
var sockaddrLen: SockLen
toSockAddr(ipPacket.ipAddrDst, ipPacket.tcpPortDst, sockaddr, sockaddrLen)
await rawFd.sendTo(packet.cstring, packet.len,
cast[ptr SockAddr](addr sockaddr), sockaddrLen)