Debian Codegraph @

src/libnet.scm

raw
1 ;;;
2 ;;; libnet.scm - network interface
3 ;;;
4 ;;; Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (declare) ;; a dummy form to suppress generation of "sci" file
35 (define-module gauche.net
36 (export <socket> make-socket
37
38 ;; NB: Many enum symbols are conditionally exported. They're
39 ;; handled specially in init routine. Here's the ones
40 ;; that are always exported.
41 PF_UNSPEC PF_UNIX PF_INET AF_UNSPEC AF_UNIX AF_INET
42 SOCK_STREAM SOCK_DGRAM SOCK_RAW
43 SHUT_RD SHUT_WR SHUT_RDWR
44
45 socket-address socket-status socket-input-port socket-output-port
46 socket-shutdown socket-close socket-bind socket-connect socket-fd
47 socket-listen socket-accept socket-setsockopt socket-getsockopt
48 socket-getsockname socket-getpeername socket-ioctl
49 socket-send socket-sendto socket-sendmsg socket-buildmsg
50 socket-recv socket-recv! socket-recvfrom socket-recvfrom!
51 <sockaddr> <sockaddr-in> <sockaddr-un> make-sockaddrs
52 sockaddr-name sockaddr-family sockaddr-addr sockaddr-port
53 make-client-socket make-server-socket make-server-sockets
54 call-with-client-socket
55 <sys-hostent> sys-gethostbyname sys-gethostbyaddr
56 <sys-protoent> sys-getprotobyname sys-getprotobynumber
57 <sys-servent> sys-getservbyname sys-getservbyport
58 sys-htonl sys-htons sys-ntohl sys-ntohs
59 inet-checksum
60 inet-string->address inet-string->address! inet-address->string
61
62 ;; connection protocol - autoloaded
63 connection-self-address connection-peer-address
64 connection-input-port connection-output-port
65 connection-shutdown connection-close
66 connection-address-name
67 )
68 )
69 (select-module gauche.net)
70
71 ;; Some generic functions needs to be defined after libobj initialization,
72 ;; so we delay its loading
73 (autoload "gauche/netutil"
74 connection-self-address
75 connection-peer-address
76 connection-input-port
77 connection-output-port
78 connection-shutdown
79 connection-close
80 connection-address-name)
81
82 (inline-stub
83 (.include "gauche/priv/configP.h"
84 "gauche/net.h")
85
86 (declare-stub-type <socket-address> "ScmSockAddr*" "socket address"
87 "Scm_SockAddrP" "SCM_SOCKADDR")
88
89 (declare-stub-type <socket> "ScmSocket*")
90 )
91
92 ;;----------------------------------------------------------
93 ;; Socket address methods
94
95 (inline-stub
96
97 (define-cgeneric sockaddr-name "Scm_GenericSockAddrName" (extern))
98 (define-cgeneric sockaddr-family "Scm_GenericSockAddrFamily" (extern))
99 (define-cgeneric sockaddr-addr "Scm_GenericSockAddrAddr" (extern))
100 (define-cgeneric sockaddr-port "Scm_GenericSockAddrPort" (extern))
101
102 (define-cmethod sockaddr-name ((addr "Scm_SockAddrClass"))
103 (cast void addr) ; suppress unused var warning
104 (return '"unknown"))
105
106 (define-cmethod sockaddr-family ((addr "Scm_SockAddrClass"))
107 (cast void addr) ; suppress unused var warning
108 (return 'unknown))
109
110 (define-cmethod sockaddr-name ((addr "Scm_SockAddrUnClass"))
111 (return
112 (?: (> (cast unsigned (-> (cast ScmSockAddr* addr) addrlen))
113 (sizeof (struct sockaddr)))
114 (SCM_MAKE_STR (ref (-> (cast ScmSockAddrUn* addr) addr) sun_path))
115 (SCM_MAKE_STR ""))))
116
117 ;; NB: We might just use inet_ntop or WSAAddressToString, but we don't bother
118 ;; checking their availability and #ifdefs.
119 (define-cmethod sockaddr-name ((addr "Scm_SockAddrInClass"))
120 (let* ([a::ScmSockAddrIn* (cast ScmSockAddrIn* addr)]
121 [addr::u_long (ntohl (ref (-> a addr) sin_addr s_addr))]
122 [port::u_short (ntohs (ref (-> a addr) sin_port))]
123 [buf::(.array char (10))])
124 (snprintf buf 10 ":%d" port)
125 (return
126 (Scm_StringAppendC
127 (SCM_STRING (Scm_InetAddressToString (Scm_MakeIntegerU addr) AF_INET))
128 buf -1 -1))))
129
130 (define-cmethod sockaddr-family ((addr "Scm_SockAddrUnClass"))
131 (cast void addr) ; suppress unused var warning
132 (return 'unix))
133
134 (define-cmethod sockaddr-family ((addr "Scm_SockAddrInClass"))
135 (cast void addr) ; suppress unused var warning
136 (return 'inet))
137
138 (define-cmethod sockaddr-addr ((addr "Scm_SockAddrInClass")) ::<ulong>
139 (let* ([a::ScmSockAddrIn* (cast ScmSockAddrIn* addr)])
140 (return (ntohl (ref (-> a addr) sin_addr s_addr)))))
141
142 (define-cmethod sockaddr-port ((addr "Scm_SockAddrInClass")) ::<ushort>
143 (let* ([a::ScmSockAddrIn* (cast ScmSockAddrIn* addr)])
144 (return (ntohs (ref (-> a addr) sin_port)))))
145
146 (.when (defined HAVE_IPV6)
147 (define-cmethod sockaddr-family ((addr "Scm_SockAddrIn6Class"))
148 (cast void addr) ; suppress unused var warning
149 (return 'inet6))
150
151 (define-cfn in6-addr (a::ScmSockAddrIn6*) :static
152 (let* ([p::uint32_t*
153 (cast uint32_t* (ref (-> a addr) sin6_addr s6_addr))]
154 [n (Scm_MakeIntegerFromUI (ntohl (* (post++ p))))])
155 (dotimes [i 3]
156 (set! n (Scm_LogIor (Scm_Ash n 32)
157 (Scm_MakeIntegerFromUI (ntohl (* (post++ p)))))))
158 (return n)))
159
160 (define-cmethod sockaddr-addr ((addr "Scm_SockAddrIn6Class"))
161 (return (in6-addr (cast ScmSockAddrIn6* addr))))
162
163 (define-cmethod sockaddr-port ((addr "Scm_SockAddrIn6Class")) ::<ushort>
164 (let* ([a::ScmSockAddrIn6* (cast ScmSockAddrIn6* addr)])
165 (return (ntohs (ref (-> a addr) sin6_port)))))
166
167 (define-cmethod sockaddr-name ((addr "Scm_SockAddrIn6Class"))
168 (let* ([a::ScmSockAddrIn6* (cast ScmSockAddrIn6* addr)]
169 [addr (in6-addr a)]
170 [port::u_short (ntohs (ref (-> a addr) sin6_port))]
171 [out (Scm_MakeOutputStringPort TRUE)])
172 (Scm_Printf (SCM_PORT out)
173 "[%A]:%d"
174 (Scm_InetAddressToString addr AF_INET6) port)
175 (return (Scm_GetOutputString (SCM_PORT out) 0))))
176 )
177 )
178
179 ;;----------------------------------------------------------
180 ;; low-level socket routines
181
182 (define-cproc make-socket (domain::<fixnum> type::<fixnum>
183 :optional (protocol::<fixnum> 0))
184 Scm_MakeSocket)
185
186 (define-enum PF_UNSPEC)
187 (define-enum PF_UNIX)
188 (define-enum PF_INET)
189
190 (define-enum AF_UNSPEC)
191 (define-enum AF_UNIX)
192 (define-enum AF_INET)
193
194 (define-enum SOCK_STREAM)
195 (define-enum SOCK_DGRAM)
196 (define-enum SOCK_RAW)
197
198 (define-enum-conditionally MSG_CTRUNC)
199 (define-enum-conditionally MSG_DONTROUTE)
200 (define-enum-conditionally MSG_EOR)
201 (define-enum-conditionally MSG_OOB)
202 (define-enum-conditionally MSG_PEEK)
203 (define-enum-conditionally MSG_TRUNC)
204 (define-enum-conditionally MSG_WAITALL)
205
206 (define-enum-conditionally IPPROTO_IP)
207 (define-enum-conditionally IPPROTO_ICMP)
208 (define-enum-conditionally IPPROTO_ICMPV6)
209 (define-enum-conditionally IPPROTO_TCP)
210 (define-enum-conditionally IPPROTO_UDP)
211
212 (define-enum-conditionally SOMAXCONN)
213
214 (define-cproc socket-address (sock::<socket>)
215 (if (-> sock address)
216 (return (SCM_OBJ (-> sock address)))
217 (return '#f)))
218
219 (define-cproc socket-status (sock::<socket>)
220 (case (-> sock status)
221 [(SCM_SOCKET_STATUS_NONE) (return 'none)]
222 [(SCM_SOCKET_STATUS_BOUND) (return 'bound)]
223 [(SCM_SOCKET_STATUS_LISTENING) (return 'listening)]
224 [(SCM_SOCKET_STATUS_CONNECTED) (return 'connected)]
225 [(SCM_SOCKET_STATUS_SHUTDOWN) (return 'shutdown)]
226 [(SCM_SOCKET_STATUS_CLOSED) (return 'closed)]
227 [else
228 (Scm_Error "invalid state of socket %S: implementation bugs?" sock)
229 (return SCM_UNDEFINED)]))
230
231 (define-cproc socket-fd (sock::<socket>) ::<long>
232 (return (cast long (-> sock fd))))
233
234 ;; NB: buffered? keyword args in the following two procedures are
235 ;; deprecated; use buffering arg.
236 (define-cproc socket-input-port (sock::<socket>
237 :key (buffering #f) (buffered? #f))
238 (let* ([bufmode::int])
239 (cond [(not (SCM_FALSEP buffered?)) ;for backward compatibility
240 (set! bufmode SCM_PORT_BUFFER_FULL)]
241 [else
242 (set! bufmode (Scm_BufferingMode buffering
243 SCM_PORT_INPUT
244 SCM_PORT_BUFFER_LINE))])
245 (return (Scm_SocketInputPort sock bufmode))))
246
247 (define-cproc socket-output-port (sock::<socket>
248 :key (buffering #f) (buffered? #f))
249 (let* ([bufmode::int])
250 (cond [(not (SCM_FALSEP buffered?)) ;for backward compatibility
251 (set! bufmode SCM_PORT_BUFFER_FULL)]
252 [else
253 (set! bufmode (Scm_BufferingMode buffering
254 SCM_PORT_OUTPUT
255 SCM_PORT_BUFFER_LINE))])
256 (return (Scm_SocketOutputPort sock bufmode))))
257
258 (inline-stub
259 (.if (and (defined SHUT_RD)
260 (defined SHUT_WR)
261 (defined SHUT_RDWR))
262 (begin
263 (define-enum SHUT_RD)
264 (define-enum SHUT_WR)
265 (define-enum SHUT_RDWR))
266 (begin
267 (define-constant SHUT_RD 0)
268 (define-constant SHUT_WR 1)
269 (define-constant SHUT_RDWR 2)))
270 )
271
272 (define-cproc socket-shutdown (sock::<socket> :optional (how::<fixnum> 2))
273 Scm_SocketShutdown)
274
275 (define-cproc socket-close (sock::<socket>)
276 Scm_SocketClose)
277
278 (define-cproc socket-bind (sock::<socket> addr::<socket-address>)
279 Scm_SocketBind)
280
281 (define-cproc socket-listen (sock::<socket> backlog::<fixnum>)
282 Scm_SocketListen)
283
284 (define-cproc socket-accept (sock::<socket>)
285 Scm_SocketAccept)
286
287 (define-cproc socket-connect (sock::<socket> addr::<socket-address>)
288 Scm_SocketConnect)
289
290 (define-cproc socket-getsockname (sock::<socket>)
291 Scm_SocketGetSockName)
292
293 (define-cproc socket-getpeername (sock::<socket>)
294 Scm_SocketGetPeerName)
295
296 (define-cproc socket-send (sock::<socket> msg
297 :optional (flags::<fixnum> 0))
298 Scm_SocketSend)
299
300 (define-cproc socket-sendto (sock::<socket> msg to::<socket-address>
301 :optional (flags::<fixnum> 0))
302 Scm_SocketSendTo)
303
304 (define-cproc socket-sendmsg (sock::<socket> msg :optional (flags::<fixnum> 0))
305 Scm_SocketSendMsg)
306
307 (define-cproc socket-recv (sock::<socket> bytes::<fixnum>
308 :optional (flags::<fixnum> 0))
309 Scm_SocketRecv)
310
311 (define-cproc socket-recv! (sock::<socket> buf::<uvector>
312 :optional (flags::<fixnum> 0))
313 Scm_SocketRecvX)
314
315 (define-cproc socket-recvfrom (sock::<socket> bytes::<fixnum>
316 :optional (flags::<fixnum> 0))
317 Scm_SocketRecvFrom)
318
319 (define-cproc socket-recvfrom! (sock::<socket> buf::<uvector> addrs
320 :optional (flags::<fixnum> 0))
321 Scm_SocketRecvFromX)
322
323 ;; struct msghdr builder
324 (define-cproc socket-buildmsg (name::<socket-address>?
325 iov::<vector>?
326 control ;list of (level type data)
327 flags::<int>
328 :optional (buf::<uvector>? #f))
329 Scm_SocketBuildMsg)
330
331 ;; socket option interface
332 (define-cproc socket-setsockopt (sock::<socket>
333 level::<fixnum> option::<fixnum> value)
334 Scm_SocketSetOpt)
335
336 (define-cproc socket-getsockopt (sock::<socket>
337 level::<fixnum> option::<fixnum>
338 rsize::<fixnum>)
339 Scm_SocketGetOpt)
340
341 (define-enum-conditionally SOL_SOCKET)
342 (define-enum-conditionally SO_ACCEPTCONN)
343 (define-enum-conditionally SO_BINDTODEVICE)
344 (define-enum-conditionally SO_BROADCAST)
345 (define-enum-conditionally SO_DEBUG)
346 (define-enum-conditionally SO_DONTROUTE)
347 (define-enum-conditionally SO_ERROR)
348 (define-enum-conditionally SO_KEEPALIVE)
349 (define-enum-conditionally SO_LINGER)
350 (define-enum-conditionally SO_OOBINLINE)
351 (define-enum-conditionally SO_PASSCRED)
352 (define-enum-conditionally SO_PEERCRED)
353 (define-enum-conditionally SO_PRIORITY)
354 (define-enum-conditionally SO_RCVBUF)
355 (define-enum-conditionally SO_RCVLOWAT)
356 (define-enum-conditionally SO_RCVTIMEO)
357 (define-enum-conditionally SO_REUSEADDR)
358 (define-enum-conditionally SO_REUSEPORT)
359 (define-enum-conditionally SO_SNDBUF)
360 (define-enum-conditionally SO_SNDLOWAT)
361 (define-enum-conditionally SO_SNDTIMEO)
362 (define-enum-conditionally SO_TIMESTAMP)
363 (define-enum-conditionally SO_TYPE)
364
365 (define-enum-conditionally SOL_TCP)
366 (define-enum-conditionally TCP_NODELAY)
367 (define-enum-conditionally TCP_MAXSEG)
368 (define-enum-conditionally TCP_CORK)
369
370 (define-enum-conditionally SOL_IP)
371 (define-enum-conditionally IP_OPTIONS)
372 (define-enum-conditionally IP_PKTINFO)
373 (define-enum-conditionally IP_RECVTOS)
374 (define-enum-conditionally IP_RECVTTL)
375 (define-enum-conditionally IP_RECVOPTS)
376 (define-enum-conditionally IP_TOS)
377 (define-enum-conditionally IP_TTL)
378 (define-enum-conditionally IP_HDRINCL)
379 (define-enum-conditionally IP_RECVERR)
380 (define-enum-conditionally IP_MTU_DISCOVER)
381 (define-enum-conditionally IP_MTU)
382 (define-enum-conditionally IP_ROUTER_ALERT)
383 (define-enum-conditionally IP_MULTICAST_TTL)
384 (define-enum-conditionally IP_MULTICAST_LOOP)
385 (define-enum-conditionally IP_ADD_MEMBERSHIP)
386 (define-enum-conditionally IP_DROP_MEMBERSHIP)
387 (define-enum-conditionally IP_MULTICAST_IF)
388
389 ;; network device access
390 ;; this is pretty much Linux-specific.
391
392 (define-cproc socket-ioctl (sock::<socket> request::<integer> data)
393 (return (Scm_SocketIoctl sock (Scm_GetIntegerU request) data)))
394
395 (define-enum-conditionally SIOCGIFNAME)
396 (define-enum-conditionally SIOCSIFNAME)
397 (define-enum-conditionally SIOCGIFINDEX)
398 (define-enum-conditionally SIOCGIFADDR)
399 (define-enum-conditionally SIOCSIFADDR)
400 (define-enum-conditionally SIOCGIFDSTADDR)
401 (define-enum-conditionally SIOCSIFDSTADDR)
402 (define-enum-conditionally SIOCGIFBRDADDR)
403 (define-enum-conditionally SIOCSIFBRDADDR)
404 (define-enum-conditionally SIOCGIFNETMASK)
405 (define-enum-conditionally SIOCSIFNETMASK)
406 (define-enum-conditionally SIOCGIFFLAGS)
407 (define-enum-conditionally SIOCSIFFLAGS)
408 (define-enum-conditionally SIOCGIFMETRIC)
409 (define-enum-conditionally SIOCSIFMETRIC)
410 (define-enum-conditionally SIOCGIFMTU)
411 (define-enum-conditionally SIOCSIFMTU)
412 (define-enum-conditionally SIOCGIFHWADDR)
413 (define-enum-conditionally SIOCSIFHWADDR)
414 (define-enum-conditionally SIOCSIFHWBROADCAST)
415 (define-enum-conditionally SIOCGIFMAP)
416 (define-enum-conditionally SIOCSIFMAP)
417 (define-enum-conditionally SIOCADDMULTI)
418 (define-enum-conditionally SIOCDELMULTI)
419 (define-enum-conditionally SIOGIFTXQLEN)
420 (define-enum-conditionally SIOSIFTXQLEN)
421 (define-enum-conditionally SIOCGIFCONF)
422
423 (define-enum-conditionally IFF_UP)
424 (define-enum-conditionally IFF_BROADCAST)
425 (define-enum-conditionally IFF_DEBUG)
426 (define-enum-conditionally IFF_LOOPBACK)
427 (define-enum-conditionally IFF_POINTTOPOINT)
428 (define-enum-conditionally IFF_RUNNING)
429 (define-enum-conditionally IFF_NOARP)
430 (define-enum-conditionally IFF_PROMISC)
431 (define-enum-conditionally IFF_NOTRAILERS)
432 (define-enum-conditionally IFF_ALLMULTI)
433 (define-enum-conditionally IFF_MASTER)
434 (define-enum-conditionally IFF_SLAVE)
435 (define-enum-conditionally IFF_MULTICAST)
436 (define-enum-conditionally IFF_PORTSEL)
437 (define-enum-conditionally IFF_AUTOMEDIA)
438 (define-enum-conditionally IFF_DYNAMIC)
439
440 ;;----------------------------------------------------------
441 ;; netdb routines
442
443 (define-cproc sys-gethostbyname (name::<const-cstring>)
444 Scm_GetHostByName)
445
446 (define-cproc sys-gethostbyaddr (addr::<const-cstring> type::<fixnum>)
447 Scm_GetHostByAddr)
448
449 (define-cproc sys-getprotobyname (name::<const-cstring>)
450 Scm_GetProtoByName)
451
452 (define-cproc sys-getprotobynumber (number::<fixnum>)
453 Scm_GetProtoByNumber)
454
455 (define-cproc sys-getservbyname (name::<const-cstring> proto::<const-cstring>)
456 Scm_GetServByName)
457
458 (define-cproc sys-getservbyport (port::<fixnum> proto::<const-cstring>)
459 Scm_GetServByPort)
460
461 (define-cproc sys-ntohl (x::<uint32>) ::<uint32> ntohl)
462 (define-cproc sys-ntohs (x::<uint16>) ::<uint16> ntohs)
463 (define-cproc sys-htonl (x::<uint32>) ::<uint32> htonl)
464 (define-cproc sys-htons (x::<uint16>) ::<uint16> htons)
465
466 ;;----------------------------------------------------------
467 ;; IPv6 routines
468
469 (inline-stub
470 (declare-cfn addrinfo_allocate (klass::ScmClass* intargs))
471
472 (.if (defined HAVE_IPV6)
473 (begin
474 (define-cclass <sys-addrinfo>
475 "ScmSysAddrinfo*" "Scm_SysAddrinfoClass"
476 ()
477 ((flags :type <int>)
478 (family :type <int>)
479 (socktype :type <int>)
480 (protocol :type <int>)
481 (addrlen :type <uint32>)
482 (canonname :type <string>)
483 (addr :setter " if (!SCM_SOCKADDRP(value)) Scm_Error(\"ScmSockAddr* required, but got %S\", value);
484 obj->addr = SCM_SOCKADDR(value);"))
485 (allocator (c "addrinfo_allocate")))
486
487 (define-cproc sys-getaddrinfo (nodename::<const-cstring>?
488 servname::<const-cstring>?
489 hints)
490 (let* ([ai::(struct addrinfo)])
491 (unless (or (SCM_SYS_ADDRINFO_P hints) (SCM_FALSEP hints))
492 (SCM_TYPE_ERROR hints "<sys-addrinfo> or #f"))
493 (unless (SCM_FALSEP hints)
494 (memset (& ai) 0 (sizeof ai))
495 (set! (ref ai ai_flags) (-> (SCM_SYS_ADDRINFO hints) flags)
496 (ref ai ai_family) (-> (SCM_SYS_ADDRINFO hints) family)
497 (ref ai ai_socktype) (-> (SCM_SYS_ADDRINFO hints) socktype)
498 (ref ai ai_protocol) (-> (SCM_SYS_ADDRINFO hints) protocol)))
499 (return (Scm_GetAddrinfo nodename servname
500 (?: (SCM_FALSEP hints) NULL (& ai))))))
501
502 (define-cproc sys-getnameinfo
503 (addr::<socket-address> :optional flags::<fixnum>)
504 Scm_GetNameinfo)
505 ))
506 )
507
508 (define-enum-conditionally AF_INET6)
509 (define-enum-conditionally PF_INET6)
510
511 (define-enum-conditionally IPPROTO_IPV6)
512 (define-enum-conditionally IPV6_UNICAST_HOPS)
513 (define-enum-conditionally IPV6_MULTICAST_IF)
514 (define-enum-conditionally IPV6_MULTICAST_HOPS)
515 (define-enum-conditionally IPV6_MULTICAST_LOOP)
516 (define-enum-conditionally IPV6_JOIN_GROUP)
517 (define-enum-conditionally IPV6_LEAVE_GROUP)
518 (define-enum-conditionally IPV6_V6ONLY)
519
520 (define-enum-conditionally AI_PASSIVE)
521 (define-enum-conditionally AI_CANONNAME)
522 (define-enum-conditionally AI_NUMERICHOST)
523 (define-enum-conditionally AI_NUMERICSERV)
524 (define-enum-conditionally AI_V4MAPPED)
525 (define-enum-conditionally AI_ALL)
526 (define-enum-conditionally AI_ADDRCONFIG)
527
528 (define-enum-conditionally NI_NOFQDN)
529 (define-enum-conditionally NI_NUMERICHOST)
530 (define-enum-conditionally NI_NAMEREQD)
531 (define-enum-conditionally NI_NUMERICSERV)
532 (define-enum-conditionally NI_DGRAM)
533
534 ;;----------------------------------------------------------
535 ;; Conditionally export symbols
536 ;;
537 ;; We can't simply use export-if-defined, for it checks binding at
538 ;; macro-expansion time. In our case, symbols are defined by the
539 ;; C initialization routine, which is after macros are expanded.
540
541 (inline-stub
542 (define-cise-stmt export-conditionally
543 [(_ . syms)
544 `(let* ([mod::ScmModule* (Scm_CurrentModule)])
545 ,@(map (^[sym]
546 `(unless (SCM_UNBOUNDP (Scm_GlobalVariableRef mod
547 (SCM_SYMBOL ',sym)
548 0))
549 (Scm_ExportSymbols mod (list ',sym))))
550 syms))])
551
552 (define-cfn export-bindings () ::void :static
553 (export-conditionally
554 IPPROTO_IP IPPROTO_ICMP IPPROTO_TCP
555 IPPROTO_UDP IPPROTO_IPV6 IPPROTO_ICMPV6 SOL_SOCKET SOMAXCONN
556 SO_ACCEPTCONN SO_BINDTODEVICE SO_BROADCAST SO_DEBUG
557 SO_DONTROUTE SO_ERROR SO_KEEPALIVE SO_LINGER SO_OOBINLINE
558 SO_PASSCRED SO_PEERCRED SO_PRIORITY SO_RCVBUF SO_RCVLOWAT
559 SO_RCVTIMEO SO_REUSEADDR SO_REUSEPORT SO_SNDBUF SO_SNDLOWAT
560 SO_SNDTIMEO SO_TIMESTAMP SO_TYPE
561 SOL_TCP TCP_NODELAY TCP_MAXSEG TCP_CORK
562 SOL_IP IP_OPTIONS
563 IP_PKTINFO IP_RECVTOS IP_RECVTTL IP_RECVOPTS IP_TOS
564 IP_TTL IP_HDRINCL IP_RECVERR IP_MTU_DISCOVER IP_MTU
565 IP_ROUTER_ALERT IP_MULTICAST_TTL IP_MULTICAST_LOOP
566 IP_ADD_MEMBERSHIP IP_DROP_MEMBERSHIP IP_MULTICAST_IF
567 MSG_CTRUNC MSG_DONTROUTE MSG_EOR MSG_OOB MSG_PEEK MSG_TRUNC
568 MSG_WAITALL
569
570 ;; Netdevice control. OS specific.
571 SIOCGIFNAME SIOCSIFNAME SIOCGIFINDEX SIOCGIFFLAGS SIOCSIFFLAGS
572 SIOCGIFMETRIC SIOCSIFMETRIC SIOCGIFMTU SIOCSIFMTU
573 SIOCGIFHWADDR SIOCSIFHWADDR SIOCSIFHWBROADCAST
574 SIOCGIFMAP SIOCSIFMAP SIOCADDMULTI SIOCDELMULTI
575 SIOGIFTXQLEN SIOSIFTXQLEN SIOCGIFCONF
576 SIOCGIFADDR SIOCSIFADDR SIOCGIFDSTADDR SIOCSIFDSTADDR
577 SIOCGIFBRDADDR SIOCSIFBRDADDR SIOCGIFNETMASK SIOCSIFNETMASK
578
579 IFF_UP IFF_BROADCAST IFF_DEBUG IFF_LOOPBACK IFF_POINTTOPOINT
580 IFF_RUNNING IFF_NOARP IFF_PROMISC IFF_NOTRAILERS IFF_ALLMULTI
581 IFF_MASTER IFF_SLAVE IFF_MULTICAST IFF_PORTSEL IFF_AUTOMEDIA
582 IFF_DYNAMIC
583
584 ;; if ipv6 is supported, these symbols are defined in the C routine.
585 PF_INET6 AF_INET6
586 <sockaddr-in6> <sys-addrinfo> sys-getaddrinfo make-sys-addrinfo
587 AI_PASSIVE AI_CANONNAME AI_NUMERICHOST AI_NUMERICSERV
588 AI_V4MAPPED AI_ALL AI_ADDRCONFIG
589 IPV6_UNICAST_HOPS IPV6_MULTICAST_IF IPV6_MULTICAST_HOPS
590 IPV6_MULTICAST_LOOP IPV6_JOIN_GROUP IPV6_LEAVE_GROUP IPV6_V6ONLY
591 sys-getnameinfo
592 NI_NOFQDN NI_NUMERICHOST NI_NAMEREQD NI_NUMERICSERV NI_DGRAM)
593 )
594
595 (initcode "export_bindings();"))
596
597 ;;----------------------------------------------------------
598 ;; Internet checksum (RFC1071)
599
600 ;; NB: This checksum routine, a bit of modification from RFC1071,
601 ;; seems widely used. In ordinary C programs you don't need to worry
602 ;; about endianness, since even if the machine is little-endian,
603 ;; the swapping happens twice (once when you fetch each 16-bit word,
604 ;; and once when you store the result) so the result becomes
605 ;; the same as big-endian calculation. In our case we take over
606 ;; the result into Scheme world, so we adjust the result to the
607 ;; network byte order (big-endian).
608 (define-cproc inet-checksum (buf::<uvector> size::<int>) ::<uint>
609 (let* ([wp::uint16_t* (cast uint16_t* (SCM_UVECTOR_ELEMENTS buf))]
610 [sum::u_long 0]
611 [result::uint16_t])
612 (when (> size (Scm_UVectorSizeInBytes buf))
613 (Scm_Error "uniform vector buffer too short: %S" buf))
614 (for [() (> size 0) (-= size 2)]
615 (when (== size 1)
616 (.if WORDS_BIGENDIAN
617 (+= sum (<< (* (cast u_char* wp)) 8))
618 (+= sum (* (cast u_char* wp))))
619 (break))
620 (+= sum (* (post++ wp))))
621 (set! sum (+ (>> sum 16) (logand sum #xffff)))
622 (+= sum (>> sum 16))
623 (set! result (cast uint16_t (lognot sum))) ;truncate to 16bit
624 (.unless WORDS_BIGENDIAN
625 (set! result (logior (>> result 8) (<< result 8))))
626 (return result)))
627
628 ;; socket addresses
629 (define-cproc inet-string->address (s::<const-cstring>) ::(<top> <top>)
630 (let* ([proto::int] [r (Scm_InetStringToAddress s (& proto) NULL)])
631 (if (SCM_FALSEP r)
632 (return SCM_FALSE SCM_FALSE)
633 (return r (SCM_MAKE_INT proto)))))
634
635 (define-cproc inet-string->address! (s::<const-cstring> buf::<uvector>)
636 (let* ([proto::int] [r (Scm_InetStringToAddress s (& proto) buf)])
637 (if (SCM_FALSEP r) (return SCM_FALSE) (return (SCM_MAKE_INT proto)))))
638
639 (define-cproc inet-address->string (addr proto::<int>) Scm_InetAddressToString)
640
641 ;; default backlog value for socket-listen
642 (define-constant DEFAULT_BACKLOG 5)
643
644 ;; NB: we can't use (cond-expand (gauche.net.ipv6 ...) ) here, since
645 ;; cond-expand is expanded when netaux.scm is compiled, but at that time
646 ;; the feature 'gauche.net.ipv6' is not available since the gauche.net module
647 ;; is not yet built. So we use a bit of kludge here.
648 (define ipv6-capable (module-binds? 'gauche.net 'sys-getaddrinfo))
649
650 ;; NB: ipv4 preference setting for the compatibility to old windows installer.
651 ;; if #t, make-sockaddrs returns ipv4 socket addresses before ipv6 ones.
652 (define ipv4-preferred (cond-expand [gauche.os.windows #t] [else #f]))
653
654 ;; API
655 (define (make-sys-addrinfo :key (flags 0) (family AF_UNSPEC)
656 (socktype 0) (protocol 0))
657 (if ipv6-capable
658 (make <sys-addrinfo>
659 :flags (if (list? flags) (apply logior flags) flags)
660 :family family :socktype socktype :protocol protocol)
661 (error "make-sys-addrinfo is available on IPv6-enabled platform")))
662
663 ;; Utility
664 (define (address->protocol-family addr)
665 (case (sockaddr-family addr)
666 [(unix) PF_UNIX]
667 [(inet) PF_INET]
668 [(inet6) PF_INET6] ;;this can't happen if !ipv6-capable
669 [else (error "unknown family of socket address" addr)]))
670
671 ;; API
672 ;; High-level interface. We need some hardcoded heuristics here.
673 (define (make-client-socket proto . args)
674 (cond [(eq? proto 'unix)
675 (let-optionals* args ([path #f])
676 (unless (string? path)
677 (error "unix socket requires pathname, but got" path))
678 (make-client-socket-unix path))]
679 [(eq? proto 'inet)
680 (let-optionals* args ([host #f] [port #f])
681 (unless (and (string? host) (or (integer? port) (string? port)))
682 (errorf "inet socket requires host name and port, but got ~s and ~s"
683 host port))
684 (make-client-socket-inet host port))]
685 [(is-a? proto <sockaddr>)
686 ;; caller provided sockaddr
687 (make-client-socket-from-addr proto)]
688 [(and (string? proto)
689 (pair? args)
690 (integer? (car args)))
691 ;; STk compatibility
692 (make-client-socket-inet proto (car args))]
693 [else
694 (error "unsupported protocol:" proto)]))
695
696 (define (make-client-socket-from-addr addr)
697 (rlet1 socket (make-socket (address->protocol-family addr) SOCK_STREAM)
698 (socket-connect socket addr)))
699
700 (define (make-client-socket-unix path)
701 (rlet1 socket (make-socket PF_UNIX SOCK_STREAM)
702 (socket-connect socket (make <sockaddr-un> :path path))))
703
704 (define (make-client-socket-inet host port)
705 (let1 err #f
706 (define (try-connect address)
707 (guard (e [else (set! err e) #f])
708 (rlet1 socket (make-socket (address->protocol-family address)
709 SOCK_STREAM)
710 (socket-connect socket address))))
711 (rlet1 socket (any try-connect (make-sockaddrs host port))
712 (unless socket (raise err)))))
713
714 ;; API
715 (define (make-server-socket proto . args)
716 (cond [(eq? proto 'unix)
717 (let-optionals* args ([path #f])
718 (unless (string? path)
719 (error "unix socket requires pathname, but got" path))
720 (apply make-server-socket-unix path (cdr args)))]
721 [(eq? proto 'inet)
722 (let-optionals* args ([port #f])
723 (define (err)
724 (error "inet socket requires integer port number or \
725 string service name, or a list of them, but got:" port))
726 (cond [(list? port)
727 (unless (every (any-pred integer? string?) port) (err))
728 (apply make-server-socket-inet* port (cdr args))]
729 [(or (integer? port) (string? port))
730 (apply make-server-socket-inet port (cdr args))]
731 [else (err)]))]
732 [(is-a? proto <sockaddr>)
733 ;; caller provided sockaddr
734 (apply make-server-socket-from-addr proto args)]
735 [(integer? proto)
736 ;; STk compatibility
737 (apply make-server-socket-inet proto args)]
738 [else
739 (error "unsupported protocol:" proto)]))
740
741 (define (make-server-socket-from-addr addr :key (reuse-addr? #f)
742 (sock-init #f)
743 (backlog DEFAULT_BACKLOG))
744 (rlet1 socket (make-socket (address->protocol-family addr) SOCK_STREAM)
745 (when (procedure? sock-init)
746 (sock-init socket addr))
747 (when reuse-addr?
748 (socket-setsockopt socket SOL_SOCKET SO_REUSEADDR 1))
749 (socket-bind socket addr)
750 (socket-listen socket backlog)))
751
752
753 (define (make-server-socket-unix path :key (backlog DEFAULT_BACKLOG))
754 (rlet1 socket (make-socket PF_UNIX SOCK_STREAM)
755 (socket-bind socket (make <sockaddr-un> :path path))
756 (socket-listen socket backlog)))
757
758 (define (make-server-socket-inet port . args)
759 (apply make-server-socket-from-addr (car (make-sockaddrs #f port)) args))
760
761 (define (make-server-socket-inet* ports . args) ; taking multiple ports
762 (let1 err #f
763 (define (try-bind address)
764 (guard (e [else (set! err e) #f])
765 (apply make-server-socket-from-addr address args)))
766 (rlet1 socket (any try-bind ($ append-map
767 (cut make-sockaddrs #f <>)
768 ports))
769 (unless socket (raise err)))))
770
771 ;; API
772 ;; Listen both v4 and v6 sockets, unless the system supports dual-stack
773 ;; socket.
774 ;; Heuristics - if we have both v4 and v6 sockets, we *may* need
775 ;; only v6 sockets if the system defaults to dual-stack socket.
776 ;; Unfortunately the behavior is system dependent. So we try to
777 ;; open both (first v6, then v4) and if the latter fails to bind
778 ;; we assume v6 socket listens both.
779 (define (make-server-sockets host port . args)
780 (define (v4addrs ss)
781 (filter (^s (eq? (sockaddr-family s) 'inet)) ss))
782 (define (v6addrs ss)
783 (filter (^s (eq? (sockaddr-family s) 'inet6)) ss))
784
785 ;; Kludge: These may not be bound on certain platforms,
786 ;; so we look them up at runtime.
787 (define EADDRINUSE
788 (module-binding-ref 'gauche 'EADDRINUSE #f))
789 (define EADDRNOTAVAIL
790 (module-binding-ref 'gauche 'EADDRNOTAVAIL #f))
791 (define <sockaddr-in6>
792 (module-binding-ref 'gauche.net '<sockaddr-in6> #f))
793
794 (define (bind-failed? e)
795 (and (<system-error> e)
796 (memv (~ e'errno) `(,EADDRINUSE ,EADDRNOTAVAIL))))
797
798 ;; try binding v4 socket with the same port of opened v6 socket S6.
799 ;; Returns (S6 S4) on success, or (S6) on failure.
800 ;; NB: It is possible that v4's port is taken by another process,
801 ;; instead of dual-stack S6 socket.
802 (define (try-v4 s6 addrs)
803 ;; If the original port argument is 0, we take port number from
804 ;; the opened v6 socket.
805 (let1 a4s (if (zero? port)
806 ($ v4addrs $ make-sockaddrs host
807 $ sockaddr-port $ socket-address s6)
808 (v4addrs addrs))
809 (guard (e [(bind-failed? e) (list s6)]
810 [else (raise e)])
811 (cons s6 (filter-map (cut apply make-server-socket <> args) a4s)))))
812
813 ;; try binding v6 socket on addr. If actual-port is not #f, reallocate
814 ;; addr with the given port. It is for the case that the given port is 0.
815 (define (try-v6 addr actual-port)
816 (let1 addr (if actual-port
817 (make <sockaddr-in6>
818 :host (sockaddr-addr addr) :port actual-port)
819 addr)
820 (guard (e [(bind-failed? e) (values #f actual-port)])
821 (let1 s6 (apply make-server-socket addr args)
822 (values s6
823 (if (zero? port)
824 (sockaddr-port (socket-address s6))
825 #f))))))
826
827 ;; Bind multiple v6 sockaddrs.
828 ;; If PORT is zero, we have to use the actual port number of the first
829 ;; socket we can bind. So it's more involved than simply mapping
830 ;; make-server-socket.
831 (define (make-v6socks a6s)
832 (let loop ([port #f] [addrs a6s] [sockets '()])
833 (if (null? addrs)
834 (reverse sockets)
835 (receive (sock port) (try-v6 (car addrs) port)
836 (loop port (cdr addrs) (if sock (cons sock sockets) sockets))))))
837
838 (let* ([ss (make-sockaddrs host port)]
839 [a6s (v6addrs ss)])
840 ;; NB: Mingw doesn't have EADDRINUSE. it's likely not to have ipv6 either,
841 ;; so we just use the default. NB: we can't switch here with
842 ;; gauche.sys.ipv6; see the comment on ipv6-capable definition above.
843 (if (or (null? a6s)
844 (not EADDRINUSE)
845 (not <sockaddr-in6>))
846 (map (cut apply make-server-socket <> args) ss)
847 (append-map (cut try-v4 <> ss) (make-v6socks (v6addrs ss))))))
848
849 ;; API
850 (define (make-sockaddrs host port :optional (proto 'tcp))
851 (if ipv6-capable
852 (let* ([socktype (case proto
853 [(tcp) SOCK_STREAM]
854 [(udp) SOCK_DGRAM]
855 [else (error "unsupported protocol:" proto)])]
856 [port (x->string port)]
857 [hints (make-sys-addrinfo :flags AI_PASSIVE :socktype socktype)]
858 [ss (map (cut slot-ref <> 'addr) (sys-getaddrinfo host port hints))])
859 (if ipv4-preferred
860 (append (filter (^s (eq? (sockaddr-family s) 'inet)) ss)
861 (remove (^s (eq? (sockaddr-family s) 'inet)) ss))
862 ss))
863 (let1 port (cond [(number? port) port]
864 [(sys-getservbyname port (symbol->string proto))
865 => (cut slot-ref <> 'port)]
866 [else
867 (error "couldn't find a port number of service:" port)])
868 (if host
869 (let1 hh (sys-gethostbyname host)
870 (unless hh (error "couldn't find host: " host))
871 (map (cut make <sockaddr-in> :host <> :port port)
872 (slot-ref hh 'addresses)))
873 (list (make <sockaddr-in> :host :any :port port))))))
874
875 ;; API
876 (define (call-with-client-socket socket proc
877 :key (input-buffering #f) (output-buffering #f))
878 (unwind-protect
879 (proc (if input-buffering
880 (socket-input-port socket :buffering input-buffering)
881 (socket-input-port socket))
882 (if output-buffering
883 (socket-output-port socket :buffering output-buffering)
884 (socket-output-port socket)))
885 (socket-close socket)))
886
887 ;; Local variables:
888 ;; mode: scheme
889 ;; end: