From d7d1b6fea197980a2f5f65ba9deee948ab7a2be3 Mon Sep 17 00:00:00 2001 From: John Benediktsson Date: Fri, 19 Aug 2011 14:19:09 -0700 Subject: [PATCH] io.sockets: check ipv4 and ipv6 for valid address strings. --- basis/io/sockets/sockets-tests.factor | 6 +++ basis/io/sockets/sockets.factor | 54 +++++++++++++++++---------- 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/basis/io/sockets/sockets-tests.factor b/basis/io/sockets/sockets-tests.factor index 7e57f87a9e..685d5a649a 100644 --- a/basis/io/sockets/sockets-tests.factor +++ b/basis/io/sockets/sockets-tests.factor @@ -29,6 +29,12 @@ os unix? [ [ T{ inet f "google.com" 80 } ] [ "google.com" 80 with-port ] unit-test +! Test bad hostnames +[ "google.com" f ] must-fail +[ "a.b.c.d" f ] must-fail +[ "google.com" f ] must-fail +[ "a.b.c.d" f ] must-fail + ! Test present on addrspecs [ "4.4.4.4:12" ] [ "4.4.4.4" 12 present ] unit-test [ "::1:12" ] [ "::1" 12 present ] unit-test diff --git a/basis/io/sockets/sockets.factor b/basis/io/sockets/sockets.factor index 0865500f76..2da840833c 100644 --- a/basis/io/sockets/sockets.factor +++ b/basis/io/sockets/sockets.factor @@ -68,27 +68,32 @@ SLOT: port TUPLE: ipv4 { host ?string read-only } ; -C: ipv4 - -M: ipv4 inet-ntop ( data addrspec -- str ) - drop 4 memory>byte-array [ number>string ] { } map-as "." join ; - number [ ] [ bad-ipv4-component ] ?if ] B{ } map-as ; + [ f ] [ + "." split dup length 4 = [ malformed-ipv4 ] unless + [ dup string>number [ ] [ bad-ipv4-component ] ?if ] B{ } map-as + ] if-empty ; -ERROR: invalid-ipv4 string reason ; - -M: invalid-ipv4 summary drop "Invalid IPv4 address" ; +: check-ipv4 ( string -- ) + [ parse-ipv4 drop ] [ invalid-ipv4 ] recover ; PRIVATE> +: ( host -- ipv4 ) dup check-ipv4 ipv4 boa ; + +M: ipv4 inet-ntop ( data addrspec -- str ) + drop 4 memory>byte-array [ number>string ] { } map-as "." join ; + M: ipv4 inet-pton ( str addrspec -- data ) drop [ parse-ipv4 ] [ invalid-ipv4 ] recover ; @@ -113,7 +118,8 @@ M: ipv4 parse-sockaddr ( sockaddr-in addrspec -- newaddrspec ) TUPLE: inet4 < ipv4 { port integer read-only } ; -C: inet4 +: ( host port -- inet4 ) + over check-ipv4 inet4 boa ; M: ipv4 with-port [ host>> ] dip ; @@ -129,15 +135,12 @@ TUPLE: ipv6 { host ?string read-only } { scope-id integer read-only } ; -: ( host -- ipv6 ) 0 ipv6 boa ; - -M: ipv6 inet-ntop ( data addrspec -- str ) - drop 16 memory>byte-array 2 [ be> >hex ] map ":" join ; - -ERROR: invalid-ipv6 string reason ; - + +: ( host -- ipv6 ) dup check-ipv6 0 ipv6 boa ; + +M: ipv6 inet-ntop ( data addrspec -- str ) + drop 16 memory>byte-array 2 [ be> >hex ] map ":" join ; + + ( host port -- inet6 ) [ 0 ] dip inet6 boa ; +: ( host port -- inet6 ) + [ dup check-ipv6 0 ] dip inet6 boa ; M: ipv6 with-port [ [ host>> ] [ scope-id>> ] bi ] dip