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 import asyncdispatch, strformat
from net import IpAddress, Port, `$`, toSockAddr from net import IpAddress, Port, `$`
from nativesockets import SockAddr, Sockaddr_storage, SockLen
from sequtils import any from sequtils import any
import asyncutils import asyncutils
import ip_packet
type type
Attempt = tuple | object Attempt = tuple | object
@ -30,18 +28,6 @@ proc findAttemptsByLocalAddr*(puncher: Puncher[Attempt], address: IpAddress,
if attempt.srcIp == address and attempt.srcPort == port: if attempt.srcIp == address and attempt.srcPort == port:
result.add(attempt) 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, proc makeFirewallRule(srcIp: IpAddress, srcPort: Port,
dstIp: IpAddress, dstPort: Port): string = dstIp: IpAddress, dstPort: Port): string =
# FIXME: use & instead of fmt? # FIXME: use & instead of fmt?

View File

@ -5,8 +5,10 @@ from nativesockets import
SOCK_RAW, SOCK_RAW,
bindAddr, bindAddr,
htons 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 network_interface
import ip_packet
type type
RawSocketError* = object of CatchableError RawSocketError* = object of CatchableError
@ -78,3 +80,12 @@ proc setupTcpInjectingSocket*(): AsyncFD =
sizeof(sockOpt).SockLen) != 0: sizeof(sockOpt).SockLen) != 0:
closeSocket(result) closeSocket(result)
raise newException(RawSocketError, "cannot set IP_HDRINCL option") 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)