STUN problems - chan_sip.c: stun failed

My public IP changes less frequently than once a month but I decided to use STUN just in case it happens.
Unfortunately STUN support in asterisk is rather flaky at this point. I regularly get messages in my log:

[2010-06-05 13:44:55] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:55] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed [2010-06-05 13:44:56] WARNING[20697] chan_sip.c: stun failed

and then asterisk has no idea what my public IP is and I get one way audio.
sip show settings gives empty Externip in “Network Settings:”

I increased the log level to 99 and there are stun related messages when STUN packet is sent/received:

the problem is the packet from the STUN server is 96 bytes, not 4, yet asterisk has problems reading it.

My version is 1.6.0.22-samy-r60

UPDATE: Some more STUN related entries:

[2010-06-05 13:44:55] DEBUG[20697] rtp.c: Scrambled STUN packet length (got 20527, expecting 396) [2010-06-05 13:50:55] DEBUG[20697] rtp.c: Scrambled STUN packet length (got 18249, expecting 438) [2010-06-05 14:00:57] DEBUG[20697] rtp.c: Scrambled STUN packet length (got 18249, expecting 638)

which does not make sense at all …

more sniffing on the network explains why this problem happens. when sending stun request asterisk uses the sip socket as the source and the first packet after that, arriving on the sip socket, is assumed to be the stun reply. If it happens to be another sip message then asterisk throws an error because it does not verify if the packet is actually a stun reply and blindly tries to parse it. this makes stun unusable with asterisk.

The issue is currently being worked on:

issues.asterisk.org/view.php?id=17622

It might allow v1.8 to be the first version with a working STUN support.