PageRenderTime 62ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/socket.wiki

https://bitbucket.org/ursetto/rfc2553
Unknown | 969 lines | 750 code | 219 blank | 0 comment | 0 complexity | f62a93eb9d968ac82af55b0f8dc3383f MD5 | raw file
  1. [[tags:egg net]]
  2. == socket
  3. '''socket''' provides an interface to the BSD socket API. For a somewhat higher-level interface, see the [[/egg/tcp6|tcp6]] and [[/egg/udp6|udp6]] extensions.
  4. == Overview
  5. This extension provides a comprehensive interface to BSD sockets,
  6. including socket creation, client and server setup, data transfer, i/o
  7. ports, forward and reverse address resolution, socket options, and
  8. socket-related integer constants. It supports both IPv4 and IPv6,
  9. as well as UNIX sockets.
  10. All socket operations block only the calling thread; other threads can
  11. continue to run, even on Windows platforms.
  12. [[toc:]]
  13. == Socket interface
  14. === Socket creation
  15. <record>socket</record><br>
  16. <procedure>(socket family type #!optional (protocol 0))</procedure><br>
  17. <procedure>(socket? so)</procedure><br>
  18. <procedure>(socket-fileno so)</procedure><br>
  19. <procedure>(socket-family so)</procedure><br>
  20. <procedure>(socket-type so)</procedure><br>
  21. <procedure>(socket-protocol so)</procedure><br>
  22. Socket objects. You construct a socket using the {{socket}} procedure,
  23. passing an address family {{af/*}} constant for FAMILY (IPv4, IPv6) and a
  24. socket type {{sock/*}} constant for socket TYPE (TCP, UDP). PROTOCOL
  25. should almost always be zero, unless you are creating raw sockets; it is
  26. implicit in the socket type. Sockets take up a file descriptor in the
  27. system until closed, which may or may not happen automatically on error.
  28. All sockets are created in non-blocking mode.
  29. Accessors:
  30. ; {{fileno}} : The socket's file descriptor.
  31. ; {{family}} : The socket family, an integer constant.
  32. ; {{type}} : The socket type, an integer constant.
  33. ; {{protocol}} : The socket protocol, an integer constant.
  34. Note that sockets are also implicitly created by {{socket-connect/ai}}
  35. and {{socket-accept}}.
  36. Example:
  37. (socket af/inet sock/stream)
  38. ; => #<socket fd:19 af/inet sock/stream>
  39. (socket af/inet6 sock/dgram)
  40. ; => #<socket fd:20 af/inet6 sock/dgram>
  41. <constant>af/inet</constant><br>
  42. <constant>af/inet6</constant><br>
  43. <constant>af/unix</constant><br>
  44. <constant>af/unspec</constant><br>
  45. <procedure>(integer->address-family int)</procedure>
  46. <procedure>(address-family->integer sym)</procedure>
  47. Address family constants for socket creation. It is possible to
  48. convert between integer constants and symbols using the provided
  49. procedures, but this is just for debugging convenience; the API
  50. requires integer constants.
  51. <constant>sock/stream</constant><br>
  52. <constant>sock/dgram</constant><br>
  53. <constant>sock/raw</constant><br>
  54. <procedure>(integer->socket-type int)</procedure>
  55. <procedure>(socket-type->integer sym)</procedure>
  56. Socket type constants for socket creation.
  57. <constant>ipproto/tcp</constant><br>
  58. <constant>ipproto/udp</constant><br>
  59. <procedure>(integer->protocol-type int)</procedure>
  60. <procedure>(protocol-type->integer sym)</procedure>
  61. Protocol constants for socket creation.
  62. === Socket addresses
  63. <record>sockaddr</record><br>
  64. <procedure>(sockaddr? sa)</procedure><br>
  65. <procedure>(sockaddr-family sa)</procedure><br>
  66. <procedure>(sockaddr-address sa)</procedure><br>
  67. <procedure>(sockaddr-port sa)</procedure><br>
  68. <procedure>(sockaddr-path sa)</procedure><br>
  69. <procedure>(sockaddr->string sa)</procedure><br>
  70. The socket address object. {{sockaddr}} is used throughout
  71. the BSD sockets API to represent the address of a local or remote
  72. socket endpoint.
  73. The most convenient constructor for Internet socket addresses is
  74. {{inet-address}}. The fundamental Internet socket address constructor
  75. is {{address-information}}, which is more powerful but also more
  76. complex to use. For UNIX sockets, use {{unix-address}}.
  77. Socket address object accessors are:
  78. ; {{family}} : returns the socket address family as an integer constant, e.g. {{af/inet}}.
  79. ; {{address}} : returns the address of a socket as a string (for Internet sockets, this is the IP address).
  80. ; {{port}} : returns the socket port for Internet sockets; it is an error to call it on another type of socket.
  81. ; {{path}} : returns the pathname for UNIX sockets, or an error for other socket types.
  82. ; {{->string}} : returns a compact representation of the socket address as a string. For Internet sockets, it returns "address" when port is 0; otherwise, it returns "address:port" for IPv4 addresses and "[address]:port" for IPv6 addresses.
  83. <procedure>(inet-address addr port)</procedure>
  84. Returns a {{sockaddr}} object constructed from IP address ADDR (a
  85. string) and port PORT (a number or numeric string). If the address
  86. or port input is invalid, an error is raised.
  87. If ADDR is {{#f}}, the unspecified address is used ("::" or "0.0.0.0").
  88. If PORT is {{#f}}, the unspecified port is used (integer 0).
  89. It is an error for both ADDR and PORT to be unspecified.
  90. Note that when IPv6 is preferred on your system, the unspecified
  91. address {{#f}} is typically "::" and the resulting object will be of
  92. family {{af/inet6}}. This may not be what you want, so it is a good
  93. idea to specify which unspecified address (yes, really) you mean --
  94. "::" or "0.0.0.0" -- in lieu of {{#f}}.
  95. <procedure>(unix-address PATH)</procedure>
  96. Returns a {{sockaddr}} object constructed from the pathname PATH,
  97. suitable for use with a socket in address family {{af/unix}}.
  98. Throws an error if UNIX sockets are not supported on your platform.
  99. === Address resolution
  100. <procedure>(address-information node service #!key family (type sock/stream) protocol flags)</procedure><br>
  101. <constant>ai/numerichost</constant><br>
  102. <constant>ai/passive</constant><br>
  103. <constant>ai/canonname</constant><br>
  104. Looks up node name and service name and translates them to numeric
  105. values. Returns a list of {{addrinfo}} objects, each of which contains
  106. a socket address ({{sockaddr}} object) suitable for use in socket calls
  107. such as {{socket-bind}} and {{socket-connect}}.
  108. NODE is either a node name (string) or IP address (string).
  109. SERVICE may be a string representing a service name or port number, or
  110. an integer. If NODE is {{#f}}, it is treated as the loopback address;
  111. however, if {{ai/passive}} is set it is treated as the unspecified
  112. address. If SERVICE is {{#f}}, it is treated as unspecified (0).
  113. Keyword arguments accept numeric constants and restrict the returned addresses accordingly:
  114. ; {{family:}} : Address family, either {{af/inet}} or {{af/inet6}}, defaulting to {{#f}}. If {{#f}}, both IPv6 and IPv4 addresses may be returned, depending on your system's configuration and IP stack.
  115. ; {{type:}} : Socket type; usually {{sock/stream}} or {{sock/dgram}}, defaulting to {{sock/stream}}. Can be {{#f}}, but results may vary between systems, so it is safer to specify one. See examples.
  116. ; {{protocol:}} : Protocol type, usually {{#f}}. Can also be {{ipproto/tcp}} or {{ipproto/udp}}; however, some systems (such as Windows) do not construct a proper socket address when {{type:}} is unspecified, so it is safer to just provide a value for {{type:}} and leave this as {{#f}}.
  117. The behavior of {{address-information}} can be influenced by the value
  118. of {{flags:}}, which should be the {{bitwise-ior}} (or simply {{+}}) of any
  119. of the following constants:
  120. ; {{ai/numerichost}} : The host is an IP address string; do not attempt to resolve it.
  121. ; {{ai/passive}} : The socket address is intended to be used in a call to bind(). The only difference is that an address of {{#f}} is translated into the unspecified address "::" or "0.0.0.0", rather than the loopback address.
  122. ; {{ai/canonname}} : Include the canonical (usually FQDN) hostname in the {{addrinfo}} object. If not provided, that field will be {{#f}}.
  123. Examples:
  124. (address-information "localhost" "http")
  125. ; => (#<addrinfo "[::1]:80" af/inet6 sock/stream ipproto/tcp>
  126. #<addrinfo "[fe80::1%lo0]:80" af/inet6 sock/stream ipproto/tcp>
  127. #<addrinfo "127.0.0.1:80" af/inet sock/stream ipproto/tcp>)
  128. (address-information "127.0.0.1" 53 type: sock/dgram)
  129. ; => (#<addrinfo "127.0.0.1:53" af/inet sock/stream ipproto/udp>)
  130. (address-information "he.net" 80)
  131. ; => (#<addrinfo "[2001:470:0:76::2]:80" af/inet6 sock/stream ipproto/tcp>
  132. #<addrinfo "216.218.186.2:80" af/inet sock/stream ipproto/tcp>)
  133. (address-information "he.net" 80 type: #f)
  134. ; Possible response on UNIX -- return both TCP and UDP addresses.
  135. ; Might also just return TCP.
  136. ; => (#<addrinfo "[2001:470:0:76::2]:80" af/inet6 sock/dgram ipproto/udp>
  137. #<addrinfo "[2001:470:0:76::2]:80" af/inet6 sock/stream ipproto/tcp>
  138. #<addrinfo "216.218.186.2:80" af/inet sock/dgram ipproto/udp>
  139. #<addrinfo "216.218.186.2:80" af/inet sock/stream ipproto/tcp>)
  140. ; Possible response on Windows -- socket addresses are not valid for use
  141. ; => (#<addrinfo "[2001:470:0:76::2]:80" af/inet6 0 0>
  142. #<addrinfo "216.218.186.2:80" af/inet 0 0>)
  143. (address-information #f "http")
  144. ; => (#<addrinfo "[::1]:80" af/inet6 sock/stream ipproto/tcp>
  145. #<addrinfo "127.0.0.1:80" af/inet sock/stream ipproto/tcp>)
  146. (address-information #f "http" flags: ai/passive)
  147. ; => (#<addrinfo "[::]:80" af/inet6 sock/stream ipproto/tcp>
  148. #<addrinfo "0.0.0.0:80" af/inet sock/stream ipproto/tcp>)
  149. ; As an example of inconsistent per-platform behavior, note that
  150. ; recent Ubuntu among others returns the above in reverse order.
  151. (address-information "allie" 0 flags: ai/canonname)
  152. ; => (#<addrinfo "192.168.1.7" af/inet sock/stream ipproto/tcp
  153. canonical: "allie.xorinia.dim">)
  154. (address-information #f #f)
  155. ; => ()
  156. <record>addrinfo</record>
  157. <procedure>(addrinfo? ai)</procedure>
  158. <procedure>(addrinfo-family ai)</procedure>
  159. <procedure>(addrinfo-socktype ai)</procedure>
  160. <procedure>(addrinfo-protocol ai)</procedure>
  161. <procedure>(addrinfo-address ai)</procedure>
  162. <procedure>(addrinfo-canonname ai)</procedure>
  163. <procedure>(addrinfo-flags ai)</procedure>
  164. Address information record returned by {{address-information}}.
  165. * {{address}} is the {{sockaddr}} socket address object;
  166. * {{family}}, {{socktype}} and {{protocol}} are numeric constants in the {{af/}}, {{sock/}} and {{ipproto/}} families respectively;
  167. * {{canonname}} is the canonical (FQDN) name of this host and is present only if the {{ai/canonname}} flag was used; otherwise {{#f}};
  168. * {{flags}} is the bitwise OR of {{ai/}} flags used when constructing this object. The system may set certain flags itself so this is probably not reliably useful.
  169. <procedure>(name-information saddr #!optional (flags 0))</procedure><br>
  170. <constant>ni/numerichost</constant><br>
  171. <constant>ni/numericserv</constant><br>
  172. <constant>ni/dgram</constant><br>
  173. <constant>ni/namereqd</constant><br>
  174. <constant>ni/nofqdn</constant><br>
  175. Given a socket address object SADDR, performs a reverse-lookup to
  176. obtain the node and service names, returning them as the pair
  177. {{("node" . "service")}}. If hostname lookup fails, the numeric
  178. representation of the address is returned as a string. If service
  179. number lookup fails, it is returned as an integer.
  180. The socket address object is usually constructed with {{inet-address}}
  181. or obtained from a socket call, e.g. {{socket-peer-name}}. As a
  182. convenience in socket 0.2.1 and later, if {{SADDR}} is a string, it is
  183. converted to a socket address object with {{(inet-address SADDR #f)}}.
  184. The behavior of {{name-information}} can be influenced by FLAGS. FLAGS
  185. may be the {{bitwise-ior}} (or simply {{+}}) of the following
  186. constants:
  187. ; {{ni/numerichost}} : Do not resolve the node address to a name; instead, return the canonical string representation of the address, as in {{inet_ntop()}}. {{(sockaddr-address saddr)}} returns the same representation.
  188. ; {{ni/numericserv}} : Do not attempt to resolve the service number to a name.
  189. ; {{ni/namereqd}} : If hostname lookup fails, raise an error.
  190. ; {{ni/nofqdn}} : Return only the local part of the hostname for local hosts.
  191. ; {{ni/dgram}} : Look up the service as a datagram service. A few service names may differ between TCP and UDP.
  192. Examples:
  193. (name-information (inet-address "127.0.0.1" 80))
  194. ; => ("localhost" . "http")
  195. (name-information (inet-address "::1" 80))
  196. ; => ("localhost" . "http")
  197. (name-information (inet-address "::1" #f))
  198. ; => ("localhost" . 0)
  199. (name-information "::1")
  200. ; => ("localhost" . 0)
  201. (name-information (inet-address "::1" 80) ni/numerichost)
  202. ; => ("::1" . "http")
  203. (name-information (inet-address "::1" 80) (+ ni/numerichost ni/numericserv))
  204. ; => ("::1" . 80)
  205. (name-information (inet-address "127.0.0.2" 80))
  206. ; => ("127.0.0.2" . "http")
  207. (name-information (inet-address "127.0.0.2" 80) ni/namereqd)
  208. ; => error: nodename nor servname provided, or not known
  209. (name-information (inet-address "2001:470:0:64::2" 80) ni/numericserv)
  210. ; => ("ipv6.he.net" . 80)
  211. (name-information (socket-peer-name s)) ;; s being an accept()ed socket
  212. ; => ("taco.universe12.dim" . 31828)
  213. === Setup and teardown
  214. <procedure>(socket-connect so saddr)</procedure><br>
  215. <procedure>(socket-connect/ai ais)</procedure><br>
  216. {{socket-connect}} connects to the remote socket address SADDR over
  217. the socket SO. Upon completion, SO will be connected; on connection
  218. failure an error is thrown. The return value is unspecified. This is
  219. a non-blocking operation; other SRFI-18 threads can continue to run.
  220. If connection fails due to refusal, network down, unreachable host or
  221. system enforced timeout, it raises a "transient" error of type {{(exn
  222. i/o net transient)}}, signalling the connection can be retried later
  223. if desired. A connection may also raise an {{(exn i/o net timeout)}}
  224. error after {{(socket-connect-timeout)}} milliseconds. If a fatal error
  225. occurs, it raises an error of type {{(exn i/o net)}}, like all other
  226. socket procedures.
  227. {{socket-connect/ai}} connects to the addresses in the {{addrinfo}}
  228. list AIS sequentially until the connection succeeds or there are no
  229. more addresses. If a fatal error occurs while connecting, it aborts
  230. immediately; but transient or timeout errors cause it to try the next
  231. address. If all attempts fail, the error raised is that of the last
  232. attempt. On success, the return value is a fresh connected socket of
  233. the appropriate family and type.
  234. Examples:
  235. ;; Connect to localhost:22 over IPv4.
  236. (define so (socket af/inet sock/stream))
  237. (socket-connect so (inet-address "127.0.0.1" 22))
  238. ;; Connect to localhost:22 over IPv6.
  239. (define so (socket af/inet6 sock/stream))
  240. (socket-connect so (inet-address "::1" 22))
  241. ;; Connect to localhost:22 over IPv4 and return the connected socket.
  242. (socket-connect/ai
  243. (address-information "localhost" 22 family: af/inet))
  244. ; => #<socket fd:8 af/inet sock/stream>
  245. ;; Try to connect to localhost:ssh via any address family.
  246. ;; In this case, address-information may return the IPv6 loopback
  247. ;; address "::1" and perhaps "fe80::1", along with the usual
  248. ;; IPv4 "127.0.0.1". socket-connect/ai will try them all in order
  249. ;; and return a new connected socket. For illustrative purposes
  250. ;; we use socket-peer-name to show where we connected.
  251. (socket-peer-name
  252. (socket-connect/ai (address-information "localhost" "ssh")))
  253. ; => #<sockaddr "[::1]:22"> ;; If ssh listening on ::1
  254. ; => #<sockaddr "[fe80::1%lo0]:22"> ;; If listening on link-local loopback
  255. ; => #<sockaddr "127.0.0.1:22"> ;; If listening on 127.0.0.1 only
  256. ; => error: connection refused ;; If ssh isn't running
  257. <procedure>(socket-bind so saddr)</procedure>
  258. Binds socket SO to socket address SADDR. The return value is unspecified.
  259. ; Bind to the IPv4 unspecified address on port 8000.
  260. (define so (socket af/inet sock/stream))
  261. (socket-bind so (inet-address "0.0.0.0" 8000))
  262. ; Bind to the IPv6 unspecified address on port 8000. This may also
  263. ; allow IPv4 connections, depending on your system settings.
  264. (define so (socket af/inet6 sock/stream))
  265. (socket-bind so (inet-address "::" 8000))
  266. ; Bind to the IPv6 unspecified address on port 8000, limiting
  267. ; connections to IPv6 only.
  268. (define so (socket af/inet6 sock/stream))
  269. (set! (ipv6-v6-only? so) #t)
  270. (socket-bind so (inet-address "::" 8000))
  271. <procedure>(socket-listen so backlog)</procedure>
  272. Listen for incoming connections on socket SO, with a connection queue
  273. of integer length BACKLOG. This call is only valid for
  274. connection-oriented (stream) sockets.
  275. <procedure>(socket-accept so)</procedure>
  276. <procedure>(socket-accept-ready? so)</procedure>
  277. {{socket-accept}} accepts a connection on listening socket SO,
  278. returning a new connected {{socket}} object. The address of the peer
  279. can be obtained by calling {{socket-peer-name}} on the socket.
  280. This is a non-blocking operation; other SRFI-18 threads can continue
  281. to run in the meantime, although this one will block. If the accept
  282. does not complete within {{(socket-accept-timeout)}} milliseconds, a
  283. timeout error is raised.
  284. {{socket-accept-ready?}} tests whether there is a connection waiting
  285. to be accepted, so you can avoid blocking the current thread.
  286. However, if a peer resets his connection between your testing and
  287. accepting, the accept may block nonetheless.
  288. <procedure>(socket-shutdown so how)</procedure>
  289. <constant>shut/rd</constant>
  290. <constant>shut/wr</constant>
  291. <constant>shut/rdwr</constant>
  292. Shutdown the full-duplex connection on socket SO in the manner of HOW:
  293. ; {{shut/rd}} : disallow further receiving
  294. ; {{shut/wr}} : disallow further sending
  295. ; {{shut/rdwr}} : disallow further receiving and sending
  296. The system normally shuts down the connection itself when closing,
  297. so calling this manually is not often necessary. One usage example
  298. is using {{shut/wr}} to inform a server you have finished transmitting,
  299. while allowing it to continue sending to you.
  300. <procedure>(socket-close so)</procedure>
  301. Close socket SO. If a connection was established,
  302. the socket is shut down gracefully.
  303. {{socket-close}} throws an error if the {{close()}} fails.
  304. <procedure>(socket-close* so)</procedure>
  305. Same as {{socket-close}}, except that {{socket-close*}} does ''not''
  306. throw an error if the {{close()}} fails.
  307. This could be useful in certain lowlevel code, such as after a network
  308. error, but you should not use this unless you know what you're doing.
  309. This might go away or change semantics in the future.
  310. === Status
  311. <procedure>(socket-name so)</procedure>
  312. Return a {{sockaddr}} object representing the address of the local
  313. endpoint of socket SO. If the socket has not been bound, it
  314. returns {{#f}}.
  315. The procedure name is derived from getsockname(), hence the use of "name"
  316. to describe a socket address.
  317. <procedure>(socket-peer-name so)</procedure>
  318. Return a {{sockaddr}} object representing the address of the remote
  319. endpoint of socket SO. If no connection exists, returns {{#f}}. This
  320. can be used after {{socket-connect}} or on a socket returned by
  321. {{socket-accept}}. Note that this also works with UDP "connections"
  322. made with {{socket-connect}}.
  323. The procedure name is derived from getpeername(), hence the use of "name"
  324. to describe a socket address.
  325. === Data transfer
  326. ==== Receiving data
  327. <procedure>(socket-receive! so buf #!optional (start 0) (end #f) (flags 0))</procedure>
  328. <procedure>(socket-receive-ready? so)</procedure>
  329. Receives data from socket SO and writes it into BUF, which may be a
  330. string or a blob. START and END are optional offsets into BUF; the
  331. call attempts to read END - START = LEN bytes. If END is {{#f}}, it
  332. is interpreted as the end of the blob or string.
  333. This call will block until data is available, but other threads can
  334. proceed. If the receive does not complete within
  335. {{(socket-receive-timeout)}} milliseconds, a timeout error is raised.
  336. To avoid blocking the current thread, you can check if data is ready
  337. via {{socket-receive-ready?}}.
  338. Returns the number of bytes actually received (and updates BUF as
  339. a side effect).
  340. For datagram sockets, if LEN is smaller than the amount of data in
  341. the next datagram, the rest of the data is irrevocably lost.
  342. <procedure>(socket-receive so len #!optional (flags 0))</procedure>
  343. Receives up to LEN bytes from data from socket SO and returns it
  344. in a string (sized to fit the returned data). Otherwise, it behaves
  345. like {{socket-receive!}}.
  346. <procedure>(socket-receive-from! so buf #!optional (start 0) (end #f) (flags 0))</procedure>
  347. Like {{socket-receive!}}, but receives data on a connectionless
  348. datagram socket, returning 2 values: the number of bytes read, and a
  349. {{sockaddr}} object representing the source.
  350. <procedure>(socket-receive-from so len #!optional (flags 0))</procedure>
  351. Receives up to LEN bytes from data from socket SO and returns two
  352. values: a string (sized to fit the returned data), and a {{sockaddr}}
  353. object representing the source. Otherwise, it behaves like
  354. {{socket-receive-from!}}.
  355. ==== Sending data
  356. <procedure>(socket-send so buf #!optional (start 0) (end #f) (flags 0))</procedure>
  357. Sends data to socket SO from the buffer BUF, which may be a
  358. string or a blob. START and END are optional offsets into BUF; the
  359. call attempts to write END - START = LEN bytes. If END is {{#f}}, it
  360. is interpreted as the end of the blob or string.
  361. This call will block until at least some data is sent, but other
  362. threads can proceed. If the send does not complete within
  363. {{(socket-send-timeout)}} milliseconds, a timeout error is raised.
  364. Returns the number of bytes actually sent.
  365. <procedure>(socket-send-to so buf saddr #!optional (start 0) (end #f) (flags 0))</procedure>
  366. Like {{socket-send}}, but sends data over a connectionless datagram
  367. socket to {{sockaddr}} SADDR, returning the number of bytes actually
  368. sent.
  369. <procedure>(socket-send-all so buf #!optional (start 0) (end #f) (flags 0))</procedure>
  370. Sends all data between START and END in BUF over connected socket SO
  371. by calling {{socket-send}} multiple times until all data is sent.
  372. Data is sent in chunks of size {{(socket-send-size)}}; the last chunk
  373. sent may be smaller than this. A {{#f}} value for
  374. {{socket-send-size}} will attempt to send all remaining data with each
  375. call to send(). Note that this chunking works for connected datagram
  376. sockets as well as stream sockets; you can use it to send a large
  377. buffer divided into, say, 512-byte datagrams.
  378. === I/O ports
  379. <procedure>(socket-i/o-ports so)</procedure>
  380. Constructs an input port I and an output port O associated with
  381. the connected socket SO, returning {{(values I O)}}. This procedure
  382. works on both stream and datagram sockets.
  383. To enable output buffering on stream socket ports, see the parameter
  384. {{socket-send-buffer-size}}. Setting it to a value of 1024 bytes is
  385. reasonable.
  386. Below is a fairly involved explanation of input and output buffering
  387. and chunking, as well as recommendations for use with datagrams.
  388. {{socket-i/o-ports}} is normally used with stream sockets. Input data
  389. is always buffered in a buffer of size {{(socket-receive-buffer-size)}}.
  390. Whenever the buffer is empty, {{socket-receive!}} is called once to read
  391. up to that many bytes. Output data is sent with {{socket-send-all}},
  392. so it may be divided into chunks of size {{(socket-send-size)}}. If
  393. output is unbuffered, {{socket-send-all}} is called as soon as data
  394. is written to the port.
  395. If output is buffered by setting {{(socket-send-buffer-size)}} to N,
  396. then N characters are buffered before sending the data. Note that
  397. only multiples of the buffer size are sent (any overage is kept in the
  398. buffer). For example, if the buffer can hold 512 bytes and contains
  399. 500 bytes, writing 526 more bytes brings the total unsent size to 1026
  400. bytes. 1024 bytes (2 blocks) are written out in a single call to
  401. {{socket-send-all}} and the last 2 bytes are retained in the buffer.
  402. When the output buffer size and chunk size are both set, it is
  403. recommended to make the chunk size a multiple of the buffer size; for
  404. example, buffer size = 1024, chunk size = 8192. If not aligned,
  405. extraneous small packets may be sent. Buffer size is almost always
  406. less than or equal to chunk size. If greater, it should be a multiple
  407. of the chunk size. Using powers of 2 for both satisfies all cases.
  408. Note that {{socket-i/o-ports}} can also be used to create ports on
  409. connected datagram sockets. Input is always buffered and a single
  410. chunk of up to size {{(socket-receive-buffer-size)}} is read into the
  411. buffer whenever the buffer is empty. (If the datagram is smaller than
  412. the buffer, repeated reads are not performed; rather, the buffer is
  413. used until exhausted again. Any datagram exceeding the buffer size
  414. will be truncated.) Output is divided into chunks of size
  415. {{(socket-send-size)}}, as in {{socket-send-all}} -- this is useful
  416. for placing a maximum cap on datagram size transmitted. Finally,
  417. output buffering may be enabled, which behaves the same as with TCP
  418. ports; characters are buffered and sent in blocks of
  419. {{(socket-send-buffer-size)}} bytes. Again, to avoid excessive
  420. transmission, the chunk size should be a multiple of the buffer
  421. size or vice versa.
  422. For example, to accept up to 4K datagrams, buffer 128 characters
  423. at a time and send 128-, 256-, 384- or 512-byte datagrams at a time:
  424. (parameterize ((socket-receive-buffer-size 4096)
  425. (socket-send-buffer-size 128)
  426. (socket-send-size 512))
  427. (define so (socket-connect/ai
  428. (address-information host port type: sock/dgram)))
  429. (define-values (i o) (socket-i/o-ports so))
  430. ;; a useful example would be nice
  431. ...)
  432. <procedure>(socket-i/o-port->socket p)</procedure>
  433. Returns the socket object assocated with input or output port P. From
  434. there you can obtain a file descriptor with {{socket-fileno}}.
  435. Alternatively, {{port->fileno}} from [[/man/4/Unit posix|posix]] is
  436. supported to obtain a file descriptor. (Also see [[#Bugs and limitations]].)
  437. <procedure>(socket-abandon-port p)</procedure>
  438. Marks the socket input or output port P as abandoned. Normally, when
  439. an socket input port is closed the read side of the connection is shut
  440. down; similarly closing the output port shuts down the write side.
  441. Marking a port as abandoned skips this shutdown. This is useful to
  442. ensure a connection stays open after the port is closed.
  443. The socket is still closed after both ports are closed, regardless of
  444. their abandoned status.
  445. === Parameters
  446. <parameter>(socket-connect-timeout ms) [default: #f]</parameter><br>
  447. <parameter>(socket-accept-timeout ms) [default: #f]</parameter><br>
  448. <parameter>(socket-receive-timeout ms) [default: 1 minute]</parameter><br>
  449. <parameter>(socket-send-timeout ms) [default: 1 minute]</parameter><br>
  450. Timeouts in milliseconds for connect, receive, send and accept
  451. operations. If these timeout are exceeded, the error {{(exn i/o net timeout)}}
  452. is raised. If {{#f}}, the operation never times out (unless
  453. the system forces it to).
  454. <parameter>(socket-send-buffer-size n) [default: #f]</parameter>
  455. <parameter>(socket-send-size n) [default: 16384]</parameter>
  456. <parameter>(socket-receive-buffer-size n) [default: 4096]</parameter>
  457. These parameters are used mostly to adjust the behavior of socket ports,
  458. and take effect when the ports are created.
  459. {{(socket-send-buffer-size)}} is the buffer size used by socket output
  460. ports. If {{#f}}, no buffering is done. A power of 2, such as 1K or 4K,
  461. is an appropriate value.
  462. {{(socket-send-size)}} is used by socket output ports, and is the size
  463. used in a single call to {{socket-send}} by {{socket-send-all}}. It
  464. can be {{#f}}, meaning infinite, so that any remaining data is sent at
  465. each call. When set, it should usually be a multiple of
  466. {{(socket-send-buffer-size)}}, assuming buffering is also enabled. A
  467. power of 2 is an appropriate value, such as 8K or 16K.
  468. {{(socket-receive-buffer-size)}} is the size used for the input buffer
  469. in socket input ports. A power of 2, such as 4K, is appropriate.
  470. Input buffering can not be disabled.
  471. == Socket option interface
  472. BSD socket option values are of substantially differing types: boolean flags
  473. (TCP_NODELAY), integers (SO_SNDBUF), structures (SO_LINGER), and so on. Still, we want a
  474. consistent interface and an element of type-safety as well. So for each option, we
  475. provide a unique getter / setter procedure which does the type-checking and marshals
  476. (or unmarshals) the data as needed.
  477. Each getter / setter takes a socket argument. The "socket" is either
  478. a file descriptor number, as returned by a socket() call, or a socket object
  479. as provided in this extension. SRFI-17 generalized set! is used on the
  480. getters to set socket options.
  481. (tcp-no-delay? s) ; => #t or #f
  482. (set! (tcp-no-delay s) #t)
  483. An error is thrown if the socket call fails, if the value passed is of
  484. incorrect type, or if you try to set a read-only option.
  485. An error of {{(exn i/o net unsupported)}} is thrown if you try to use
  486. a socket option that is not defined at all on the platform, or that is
  487. defined but not supported by the operating system. Note that some
  488. platforms, particularly Windows, may return a false positive for
  489. "unsupported option" when it really indicates a usage error (wrong
  490. socket type or option value).
  491. === Socket option accessors
  492. Below is a list of option procedures and their value type. The procedure names are
  493. verbose variants of their associated constant names. For example, {{SO_REUSEADDR}} becomes
  494. {{so-reuse-address}}.
  495. Only booleans and integers and their read-only variants are currently supported. The
  496. intention is to additionally support timevals, linger, ip_mreq structs and ipoptions, at
  497. least. There is an example of linger support in the low-level interface below.
  498. <procedure>(so-reuse-address? s) [so/reuseaddr] </procedure><br>
  499. <procedure>(so-debug? s) [so/debug] </procedure><br>
  500. <procedure>(so-keep-alive? s) [so/keepalive] </procedure><br>
  501. <procedure>(so-dont-route? s) [so/dontroute] </procedure><br>
  502. <procedure>(so-broadcast? s) [so/broadcast] </procedure><br>
  503. <procedure>(so-oob-inline? s) [so/oobinline] </procedure><br>
  504. <procedure>(so-accept-connections? s) [so/acceptconn] (r/o)</procedure><br>
  505. <procedure>(so-send-buffer s) [so/sndbuf] </procedure><br>
  506. <procedure>(so-receive-buffer s) [so/rcvbuf] </procedure><br>
  507. <procedure>(so-send-low-water s) [so/sndlowat] </procedure><br>
  508. <procedure>(so-receive-low-water s) [so/rcvlowat] </procedure><br>
  509. <procedure>(so-error s) [so/error] (r/o)</procedure><br>
  510. <procedure>(so-type s) [so/type] (r/o)</procedure><br>
  511. Getters / setters for boolean and integer socket-level options, where S is a
  512. ''socket'' object or an integer file descriptor. To set an option, use SRFI-17
  513. generalized set:
  514. (set! (so-reuse-address? s) #t)
  515. "(r/o)" indicates the option is read-only; an error will be raised if
  516. you attempt to set it.
  517. As a special note on {{so-reuse-address?}}, on Windows platforms it
  518. will first attempt to use option {{so/exclusiveaddruse}} because this
  519. option matches UNIX semantics. If this fails it will fall back to
  520. {{so/reuseaddr}}, which allows any processes to rebind a previously
  521. bound address and port.
  522. <procedure>(tcp-no-delay? s) [tcp/nodelay]</procedure><br>
  523. <procedure>(tcp-no-push? s) [tcp/nopush]</procedure><br>
  524. <procedure>(tcp-no-options? s) [tcp/noopt]</procedure><br>
  525. <procedure>(tcp-keep-alive s) [tcp/keepalive]</procedure><br>
  526. <procedure>(tcp-max-segment-size s) [tcp/maxseg]</procedure><br>
  527. Getters / setters for TCP-level socket options ({{ipproto/tcp}}). S is
  528. a ''socket'' object or an integer file descriptor.
  529. <procedure>(ip-header-included? s) [ip/hdrincl]</procedure><br>
  530. <procedure>(ip-type-of-service s) [ip/tos]</procedure><br>
  531. <procedure>(ip-time-to-live s) [ip/ttl]</procedure><br>
  532. Getters / setters for IP-level socket options ({{ipproto/ip}}). S is
  533. a ''socket'' object or an integer file descriptor.
  534. <procedure>(ipv6-v6-only? s) [ipv6/v6only] </procedure><br>
  535. Getters / setters for IPv6-level socket options ({{ipproto/ipv6}}). S is
  536. a ''socket'' object or an integer file descriptor.
  537. === Low-level socket option interface
  538. A low-level socket option interface is also provided. This is
  539. intended to let you use the constants defined above (or your own) when
  540. there is no high-level interface implemented. This interface can get
  541. or set arbitrary option contents; you're not limited to predefined
  542. types such as integer or boolean. No checking is done that the passed
  543. option value is appropriate, as that's the job of the high-level
  544. interface.
  545. <procedure>(set-socket-option s level name val)</procedure>
  546. Set the value of option {{NAME}} at socket level {{LEVEL}} on socket {{S}} to {{VAL}}.
  547. {{VAL}} may be a fixnum or a boolean. It may also be a blob or a string; if so, the raw
  548. contents are passed to the option, which is useful when a structure is required. The return value is unspecified.
  549. If an unsupported option or level is requested, a condition of type
  550. {{(exn i/o net unsupported)}} is raised.
  551. Note: due to the vagaries of structure member alignment (and 32 vs. 64-bit sizes), it's
  552. not generally safe to pack raw data yourself into a blob or a SRFI-4 vector. Instead, you
  553. should treat the blob contents as a C struct. See the longer example down the page
  554. for more.
  555. (set-socket-option S ipproto/tcp tcp/nodelay 1)
  556. (set-socket-option S ipproto/tcp tcp/nodelay (make-string 4 #\x0))
  557. (set-socket-option S sol/socket so/rcvlowat (u32vector->blob/shared (u32vector #x01020304)))
  558. <procedure>(get-socket-option s level name #!optional (len #f))</procedure>
  559. Get the value of option {{NAME}} at socket level {{LEVEL}} on socket
  560. {{S}}. If {{LEN}} is {{#f}}, the default, we interpret the option
  561. value as an integer and return that. Otherwise, temporary storage of
  562. length {{LEN}} is allocated to receive the binary option data; after
  563. the call it is resized to fit the data, and returned. If LEN is too
  564. small to hold the returned data, the result is undefined.
  565. If an unsupported option or level is requested, a condition of type
  566. {{(exn i/o net unsupported)}} is raised.
  567. This procedure does not convert integers to boolean values---if you
  568. expect a boolean flag, assume zero means {{#f}} and non-zero means
  569. {{#t}}. Don't be surprised if boolean flags return different non-zero
  570. integer values from those you put in; that's an implementation detail.
  571. You can only rely on true being some non-zero value.
  572. (get-socket-option S ipproto/tcp tcp/nodelay) ; => 8, perhaps, meaning #t
  573. (get-socket-option S ipproto/tcp tcp/nodelay 64) ; => #${08000000}
  574. (get-socket-option S ipproto/tcp tcp/nodelay 4) ; => #${08000000}
  575. === Socket option constants
  576. Integer constants are provided for socket levels, socket types, and
  577. socket options. They are renamed slightly, and consistently, to
  578. achieve a more Schemely appearance: for example, C's {{SO_REUSEADDR}}
  579. becomes {{so/reuseaddr}}.
  580. Some platforms do not define all the constants we provide. If a
  581. constant is undefined, its value is {{#f}} and attempting to get or
  582. set it will raise an error. Note that a platform may define a
  583. constant but not support it (for example, {{ipv6/v6only}} on Windows
  584. prior to Vista); this will not be known until you try to get or set
  585. it.
  586. ==== Socket-level constants
  587. <constant>so/reuseaddr</constant><br>
  588. <constant>so/debug</constant><br>
  589. <constant>so/acceptconn</constant><br>
  590. <constant>so/keepalive</constant><br>
  591. <constant>so/dontroute</constant><br>
  592. <constant>so/broadcast</constant><br>
  593. <constant>so/linger</constant><br>
  594. <constant>so/oobinline</constant><br>
  595. <constant>so/sndbuf</constant><br>
  596. <constant>so/rcvbuf</constant><br>
  597. <constant>so/sndlowat</constant><br>
  598. <constant>so/rcvlowat</constant><br>
  599. <constant>so/sndtimeo</constant><br>
  600. <constant>so/rcvtimeo</constant><br>
  601. <constant>so/error</constant><br>
  602. <constant>so/type</constant><br>
  603. <constant>so/useloopback</constant><br>
  604. <constant>so/reuseport</constant><br>
  605. <constant>so/timestamp</constant><br>
  606. <constant>so/exclusiveaddruse</constant><br>
  607. Socket-level socket options for use with {{set-socket-option}} and
  608. {{get-socket-option}} at level {{sol/socket}}.
  609. ==== TCP-level constants
  610. <constant>tcp/nodelay</constant><br>
  611. <constant>tcp/nopush</constant><br>
  612. <constant>tcp/noopt</constant><br>
  613. <constant>tcp/keepalive</constant><br>
  614. <constant>tcp/maxseg</constant><br>
  615. TCP-level socket options for use with {{set-socket-option}} and
  616. {{get-socket-option}} at level {{ipproto/tcp}}.
  617. ==== IP-level constants
  618. <constant>ip/options</constant><br>
  619. <constant>ip/hdrincl</constant><br>
  620. <constant>ip/tos</constant><br>
  621. <constant>ip/ttl</constant><br>
  622. <constant>ip/mtu</constant><br>
  623. <constant>ip/mtu-discover</constant><br>
  624. <constant>ip/pktinfo</constant><br>
  625. <constant>ip/recverr</constant><br>
  626. <constant>ip/recvtos</constant><br>
  627. <constant>ip/recvttl</constant><br>
  628. <constant>ip/router-alert</constant><br>
  629. <constant>ip/recvopts</constant><br>
  630. <constant>ip/recvretopts</constant><br>
  631. <constant>ip/retopts</constant><br>
  632. <constant>ip/recvdstaddr</constant><br>
  633. <constant>ip/multicast-if</constant><br>
  634. <constant>ip/multicast-ttl</constant><br>
  635. <constant>ip/multicast-loop</constant><br>
  636. <constant>ip/add-membership</constant><br>
  637. <constant>ip/drop-membership</constant><br>
  638. IP-level socket options for use with {{set-socket-option}} and
  639. {{get-socket-option}} at level {{ipproto/ip}}.
  640. ==== Socket and protocol levels
  641. <constant>sol/socket</constant><br>
  642. <constant>ipproto/ip</constant><br>
  643. <constant>ipproto/ipv6</constant><br>
  644. <constant>ipproto/tcp</constant><br>
  645. <constant>ipproto/icmp</constant><br>
  646. <constant>ipproto/udp</constant><br>
  647. Socket level constants, for use with {{set-socket-option}} and {{get-socket-option}}.
  648. === SO_LINGER lowlevel example
  649. This is a pretty hairy example of getting and setting the {{so/linger}} option, which does
  650. not currently have a high-level equivalent. {{so/linger}} usually takes and returns a
  651. {{struct linger}} value which consists of an on/off flag and a linger timeout in seconds.
  652. (But not always!)
  653. The approach below encases the {{struct linger}} in an
  654. appropriately-sized blob and creates an encoder and decoder for this
  655. structure. Any useful option taking a structure value should ideally
  656. have a high-level interface created for it instead.
  657. (define _linger_size (foreign-value "sizeof(struct linger)" int))
  658. (define (encode-linger-option state time)
  659. (let ((blob (make-blob _linger_size)))
  660. ((foreign-lambda* void ((scheme-pointer ptr) (bool onoff) (int linger))
  661. "struct linger *p = ptr;"
  662. "p->l_onoff = onoff; p->l_linger = linger;")
  663. blob state time)
  664. blob))
  665. (define (decode-linger-option blob)
  666. ; sanity checking on parameter recommended here
  667. (list ((foreign-lambda* bool ((scheme-pointer p))
  668. "return(((struct linger *)p)->l_onoff);") blob)
  669. ((foreign-lambda* int ((scheme-pointer p))
  670. "return(((struct linger *)p)->l_linger);") blob)))
  671. (set-socket-option S sol/socket so/linger (encode-linger-option #t 100))
  672. (decode-linger-option
  673. (get-socket-option S sol/socket so/linger _linger_size))
  674. ; => (#t 100)
  675. == Examples
  676. === Client-server examples
  677. For a simple example of client-server communication over a unix socket, see
  678. [[/Communicating over a unix socket, using the socket egg|here]].
  679. A TCP/IP example is still to be written.
  680. === Disable Nagle's Algorithm on TCP listener socket
  681. The [[/man/4/Unit tcp|tcp unit]] does not support setting arbitrary socket
  682. options on sockets it creates. However, you can obtain a listener's
  683. socket file descriptor after the fact.
  684. (define L (tcp-listen 8080))
  685. (define S (tcp-listener-fileno L))
  686. (set! (tcp-no-delay? S) #t)
  687. === Set socket options on HTTP server
  688. This is similar to the above. HTTP servers may see some performance
  689. gain when Nagle's algorithm is disabled. This is generally the
  690. default on Linux, but not Solaris or OS X.
  691. (This needs to be updated for spiffy / intarweb.)
  692. (parameterize ((http:listen-procedure
  693. (lambda (port backlog host)
  694. (let ((L (tcp-listen port backlog host)))
  695. (set! (tcp-no-delay? (tcp-listener-fileno L) #t))
  696. L))))
  697. ((http:make-server ...)))
  698. == Bugs and limitations
  699. * If IPv6 support is totally unavailable on your platform (not simply disabled)
  700. then building this extension will fail. This should be fixed in a future
  701. release.
  702. * In order to support {{port->fileno}}, socket ports are
  703. backwardly-compatible with core tcp ports to the extent that
  704. port-related procedures from [[/man/4/Unit tcp|Unit tcp]] will
  705. erroneously accept socket ports as well. These procedures are
  706. {{tcp-abandon-port}}, {{tcp-addresses}}, and {{tcp-port-numbers}}.
  707. Using them with socket ports has an undefined result. The other way
  708. around is safe: procedures in this extension will throw an error if
  709. used with core tcp ports.
  710. == About this egg
  711. === Author
  712. [[http://3e8.org|Jim Ursetto]]
  713. Some code was derived from the core [[/man/4/Unit tcp|tcp]]
  714. unit by Felix Winkelmann and the rest of the Chicken team.
  715. === Version history
  716. ; 0.2.5 : socket-accept: Handle select failure. Patch by Jonathan Chan.
  717. ; 0.2.4 : {{SO_EXCLUSIVEADDR}} fix for Cygwin
  718. ; 0.2.3 : Set connectionless sockets to nonblocking
  719. ; 0.2.2 : Fix segfault in {{socket-receive}}, {{socket-send}} and friends when socket argument was not a socket (reported by hypnocat)
  720. ; 0.2.1 : Treat string {{addr}} arg to {{name-information}} as {{(inet-address addr #f)}}
  721. ; 0.2 : Add UNIX socket support; eliminate much dead code and runtime support checks.
  722. ; 0.1 : Initial release for Chicken 4.
  723. === Portability
  724. * socket 0.1 has been successfully built and tested on Mac OS X 10.5,
  725. Ubuntu 10.10, Windows XP SP3 and NetBSD 5.1.
  726. === License
  727. Copyright (c) 2011-2014, Jim Ursetto. All rights reserved.
  728. Copyright (c) 2008-2011, The Chicken Team
  729. Copyright (c) 2000-2007, Felix L. Winkelmann
  730. Redistribution and use in source and binary forms, with or without
  731. modification, are permitted provided that the following conditions are met:
  732. Redistributions of source code must retain the above copyright notice,
  733. this list of conditions and the following disclaimer. Redistributions in
  734. binary form must reproduce the above copyright notice, this list of
  735. conditions and the following disclaimer in the documentation and/or
  736. other materials provided with the distribution. Neither the name of the
  737. author nor the names of its contributors may be used to endorse or
  738. promote products derived from this software without specific prior
  739. written permission.
  740. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  741. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  742. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  743. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
  744. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  745. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  746. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  747. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  748. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  749. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  750. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.