Refactor STUN client for safety, performance, and maintainability - #59
Refactor STUN client for safety, performance, and maintainability#59ErickXavier wants to merge 2 commits into
Conversation
ccding
left a comment
There was a problem hiding this comment.
I found two protocol-correctness regressions in the packet serialization/parsing changes. Both are reproducible with focused tests; details are inline.
| binary.BigEndian.PutUint16(packetBytes[0:2], v.types) | ||
| binary.BigEndian.PutUint16(packetBytes[2:4], v.length) | ||
| packetBytes = append(packetBytes, v.transID...) | ||
| size := 20 + int(v.length) |
There was a problem hiding this comment.
[P1] Preserve the FINGERPRINT CRC input boundary
sendBindingReq temporarily increments pkt.length by 8 before calling newFingerprintAttribute, so the header advertises the FINGERPRINT while the CRC input still excludes that attribute. Because this allocation now uses v.length, packet.bytes() returns eight unwritten zero bytes and newFingerprintAttribute hashes them too. As a result every generated request carries an invalid FINGERPRINT. Please either return only buf[:offset] here (while retaining the advertised header length) or make the fingerprint calculation explicitly hash only the bytes through the last serialized attribute.
| return nil, errors.New("Received data format mismatch") | ||
| } | ||
| value := packetBytes[pos+4 : end] | ||
| value := make([]byte, length) |
There was a problem hiding this comment.
[P2] Preserve the wire length before padding parsed attributes
This copied slice is passed to newAttribute, which pads it to a multiple of four and overwrites attribute.length with the padded size. A MAPPED-ADDRESS declaring only 5 bytes therefore becomes 8 bytes before rawAddr validates it, and is accepted as an address such as 127.0.0.0 instead of producing the intended decoding error (lengths 6/7 and IPv6 lengths 17–19 have the same issue). Please preserve the declared length for parsed attributes, or use a parsing constructor that does not turn wire padding into attribute data, and validate the exact family-specific length.
This PR refactors the STUN client for safety, performance, and usability:
Detailed Changes:
rawAddrandxorAddrto prevent runtime panics on truncated or malformed attributes.acquireConnto eliminate code duplication, and usednet.JoinHostPortto fix IPv6 literal address resolution.os.Stderrto prevent stdout pollution when using verbose mode.newResponseto the send/receive loop.bytes()) to pre-allocate the output buffer.newResponseto handle and propagate attribute decoding errors.sendWithLog.stun.sipgate.net:10000sincestun.ekiga.nethas been retired.net.PacketConnand comprehensive tests to verify DiscoverNATType state machine and error handling logic.