web.texi 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 2010, 2011, 2012 Free Software Foundation, Inc.
  4. @c See the file guile.texi for copying conditions.
  5. @node Web
  6. @section @acronym{HTTP}, the Web, and All That
  7. @cindex Web
  8. @cindex WWW
  9. @cindex HTTP
  10. It has always been possible to connect computers together and share
  11. information between them, but the rise of the World-Wide Web over the
  12. last couple of decades has made it much easier to do so. The result is
  13. a richly connected network of computation, in which Guile forms a part.
  14. By ``the web'', we mean the HTTP protocol@footnote{Yes, the P is for
  15. protocol, but this phrase appears repeatedly in RFC 2616.} as handled by
  16. servers, clients, proxies, caches, and the various kinds of messages and
  17. message components that can be sent and received by that protocol,
  18. notably HTML.
  19. On one level, the web is text in motion: the protocols themselves are
  20. textual (though the payload may be binary), and it's possible to create
  21. a socket and speak text to the web. But such an approach is obviously
  22. primitive. This section details the higher-level data types and
  23. operations provided by Guile: URIs, HTTP request and response records,
  24. and a conventional web server implementation.
  25. The material in this section is arranged in ascending order, in which
  26. later concepts build on previous ones. If you prefer to start with the
  27. highest-level perspective, @pxref{Web Examples}, and work your way
  28. back.
  29. @menu
  30. * Types and the Web:: Types prevent bugs and security problems.
  31. * URIs:: Universal Resource Identifiers.
  32. * HTTP:: The Hyper-Text Transfer Protocol.
  33. * HTTP Headers:: How Guile represents specific header values.
  34. * Requests:: HTTP requests.
  35. * Responses:: HTTP responses.
  36. * Web Client:: Accessing web resources over HTTP.
  37. * Web Server:: Serving HTTP to the internet.
  38. * Web Examples:: How to use this thing.
  39. @end menu
  40. @node Types and the Web
  41. @subsection Types and the Web
  42. It is a truth universally acknowledged, that a program with good use of
  43. data types, will be free from many common bugs. Unfortunately, the
  44. common practice in web programming seems to ignore this maxim. This
  45. subsection makes the case for expressive data types in web programming.
  46. By ``expressive data types'', we mean that the data types @emph{say}
  47. something about how a program solves a problem. For example, if we
  48. choose to represent dates using SRFI 19 date records (@pxref{SRFI-19}),
  49. this indicates that there is a part of the program that will always have
  50. valid dates. Error handling for a number of basic cases, like invalid
  51. dates, occurs on the boundary in which we produce a SRFI 19 date record
  52. from other types, like strings.
  53. With regards to the web, data types are helpful in the two broad phases
  54. of HTTP messages: parsing and generation.
  55. Consider a server, which has to parse a request, and produce a response.
  56. Guile will parse the request into an HTTP request object
  57. (@pxref{Requests}), with each header parsed into an appropriate Scheme
  58. data type. This transition from an incoming stream of characters to
  59. typed data is a state change in a program---the strings might parse, or
  60. they might not, and something has to happen if they do not. (Guile
  61. throws an error in this case.) But after you have the parsed request,
  62. ``client'' code (code built on top of the Guile web framework) will not
  63. have to check for syntactic validity. The types already make this
  64. information manifest.
  65. This state change on the parsing boundary makes programs more robust,
  66. as they themselves are freed from the need to do a number of common
  67. error checks, and they can use normal Scheme procedures to handle a
  68. request instead of ad-hoc string parsers.
  69. The need for types on the response generation side (in a server) is more
  70. subtle, though not less important. Consider the example of a POST
  71. handler, which prints out the text that a user submits from a form.
  72. Such a handler might include a procedure like this:
  73. @example
  74. ;; First, a helper procedure
  75. (define (para . contents)
  76. (string-append "<p>" (string-concatenate contents) "</p>"))
  77. ;; Now the meat of our simple web application
  78. (define (you-said text)
  79. (para "You said: " text))
  80. (display (you-said "Hi!"))
  81. @print{} <p>You said: Hi!</p>
  82. @end example
  83. This is a perfectly valid implementation, provided that the incoming
  84. text does not contain the special HTML characters @samp{<}, @samp{>}, or
  85. @samp{&}. But this provision of a restricted character set is not
  86. reflected anywhere in the program itself: we must @emph{assume} that the
  87. programmer understands this, and performs the check elsewhere.
  88. Unfortunately, the short history of the practice of programming does not
  89. bear out this assumption. A @dfn{cross-site scripting} (@acronym{XSS})
  90. vulnerability is just such a common error in which unfiltered user input
  91. is allowed into the output. A user could submit a crafted comment to
  92. your web site which results in visitors running malicious Javascript,
  93. within the security context of your domain:
  94. @example
  95. (display (you-said "<script src=\"http://bad.com/nasty.js\" />"))
  96. @print{} <p>You said: <script src="http://bad.com/nasty.js" /></p>
  97. @end example
  98. The fundamental problem here is that both user data and the program
  99. template are represented using strings. This identity means that types
  100. can't help the programmer to make a distinction between these two, so
  101. they get confused.
  102. There are a number of possible solutions, but perhaps the best is to
  103. treat HTML not as strings, but as native s-expressions: as SXML. The
  104. basic idea is that HTML is either text, represented by a string, or an
  105. element, represented as a tagged list. So @samp{foo} becomes
  106. @samp{"foo"}, and @samp{<b>foo</b>} becomes @samp{(b "foo")}.
  107. Attributes, if present, go in a tagged list headed by @samp{@@}, like
  108. @samp{(img (@@ (src "http://example.com/foo.png")))}. @xref{sxml
  109. simple}, for more information.
  110. The good thing about SXML is that HTML elements cannot be confused with
  111. text. Let's make a new definition of @code{para}:
  112. @example
  113. (define (para . contents)
  114. `(p ,@@contents))
  115. (use-modules (sxml simple))
  116. (sxml->xml (you-said "Hi!"))
  117. @print{} <p>You said: Hi!</p>
  118. (sxml->xml (you-said "<i>Rats, foiled again!</i>"))
  119. @print{} <p>You said: &lt;i&gt;Rats, foiled again!&lt;/i&gt;</p>
  120. @end example
  121. So we see in the second example that HTML elements cannot be unwittingly
  122. introduced into the output. However it is now perfectly acceptable to
  123. pass SXML to @code{you-said}; in fact, that is the big advantage of SXML
  124. over everything-as-a-string.
  125. @example
  126. (sxml->xml (you-said (you-said "<Hi!>")))
  127. @print{} <p>You said: <p>You said: &lt;Hi!&gt;</p></p>
  128. @end example
  129. The SXML types allow procedures to @emph{compose}. The types make
  130. manifest which parts are HTML elements, and which are text. So you
  131. needn't worry about escaping user input; the type transition back to a
  132. string handles that for you. @acronym{XSS} vulnerabilities are a thing
  133. of the past.
  134. Well. That's all very nice and opinionated and such, but how do I use
  135. the thing? Read on!
  136. @node URIs
  137. @subsection Universal Resource Identifiers
  138. Guile provides a standard data type for Universal Resource Identifiers
  139. (URIs), as defined in RFC 3986.
  140. The generic URI syntax is as follows:
  141. @example
  142. URI := scheme ":" ["//" [userinfo "@@"] host [":" port]] path \
  143. [ "?" query ] [ "#" fragment ]
  144. @end example
  145. For example, in the URI, @indicateurl{http://www.gnu.org/help/}, the
  146. scheme is @code{http}, the host is @code{www.gnu.org}, the path is
  147. @code{/help/}, and there is no userinfo, port, query, or path. All URIs
  148. have a scheme and a path (though the path might be empty). Some URIs
  149. have a host, and some of those have ports and userinfo. Any URI might
  150. have a query part or a fragment.
  151. Userinfo is something of an abstraction, as some legacy URI schemes
  152. allowed userinfo of the form @code{@var{username}:@var{passwd}}. But
  153. since passwords do not belong in URIs, the RFC does not want to condone
  154. this practice, so it calls anything before the @code{@@} sign
  155. @dfn{userinfo}.
  156. Properly speaking, a fragment is not part of a URI. For example, when a
  157. web browser follows a link to @indicateurl{http://example.com/#foo}, it
  158. sends a request for @indicateurl{http://example.com/}, then looks in the
  159. resulting page for the fragment identified @code{foo} reference. A
  160. fragment identifies a part of a resource, not the resource itself. But
  161. it is useful to have a fragment field in the URI record itself, so we
  162. hope you will forgive the inconsistency.
  163. @example
  164. (use-modules (web uri))
  165. @end example
  166. The following procedures can be found in the @code{(web uri)}
  167. module. Load it into your Guile, using a form like the above, to have
  168. access to them.
  169. @deffn {Scheme Procedure} build-uri scheme [#:userinfo=@code{#f}] [#:host=@code{#f}] @
  170. [#:port=@code{#f}] [#:path=@code{""}] [#:query=@code{#f}] @
  171. [#:fragment=@code{#f}] [#:validate?=@code{#t}]
  172. Construct a URI object. @var{scheme} should be a symbol, and the rest
  173. of the fields are either strings or @code{#f}. If @var{validate?} is
  174. true, also run some consistency checks to make sure that the constructed
  175. URI is valid.
  176. @end deffn
  177. @deffn {Scheme Procedure} uri? x
  178. @deffnx {Scheme Procedure} uri-scheme uri
  179. @deffnx {Scheme Procedure} uri-userinfo uri
  180. @deffnx {Scheme Procedure} uri-host uri
  181. @deffnx {Scheme Procedure} uri-port uri
  182. @deffnx {Scheme Procedure} uri-path uri
  183. @deffnx {Scheme Procedure} uri-query uri
  184. @deffnx {Scheme Procedure} uri-fragment uri
  185. A predicate and field accessors for the URI record type. The URI scheme
  186. will be a symbol, and the rest either strings or @code{#f} if not
  187. present.
  188. @end deffn
  189. @deffn {Scheme Procedure} string->uri string
  190. Parse @var{string} into a URI object. Return @code{#f} if the string
  191. could not be parsed.
  192. @end deffn
  193. @deffn {Scheme Procedure} uri->string uri
  194. Serialize @var{uri} to a string. If the URI has a port that is the
  195. default port for its scheme, the port is not included in the
  196. serialization.
  197. @end deffn
  198. @deffn {Scheme Procedure} declare-default-port! scheme port
  199. Declare a default port for the given URI scheme.
  200. @end deffn
  201. @deffn {Scheme Procedure} uri-decode str [#:encoding=@code{"utf-8"}]
  202. Percent-decode the given @var{str}, according to @var{encoding}, which
  203. should be the name of a character encoding.
  204. Note that this function should not generally be applied to a full URI
  205. string. For paths, use split-and-decode-uri-path instead. For query
  206. strings, split the query on @code{&} and @code{=} boundaries, and decode
  207. the components separately.
  208. Note also that percent-encoded strings encode @emph{bytes}, not
  209. characters. There is no guarantee that a given byte sequence is a valid
  210. string encoding. Therefore this routine may signal an error if the
  211. decoded bytes are not valid for the given encoding. Pass @code{#f} for
  212. @var{encoding} if you want decoded bytes as a bytevector directly.
  213. @xref{Ports, @code{set-port-encoding!}}, for more information on
  214. character encodings.
  215. Returns a string of the decoded characters, or a bytevector if
  216. @var{encoding} was @code{#f}.
  217. @end deffn
  218. Fixme: clarify return type. indicate default values. type of
  219. unescaped-chars.
  220. @deffn {Scheme Procedure} uri-encode str [#:encoding=@code{"utf-8"}] [#:unescaped-chars]
  221. Percent-encode any character not in the character set,
  222. @var{unescaped-chars}.
  223. The default character set includes alphanumerics from ASCII, as well as
  224. the special characters @samp{-}, @samp{.}, @samp{_}, and @samp{~}. Any
  225. other character will be percent-encoded, by writing out the character to
  226. a bytevector within the given @var{encoding}, then encoding each byte as
  227. @code{%@var{HH}}, where @var{HH} is the hexadecimal representation of
  228. the byte.
  229. @end deffn
  230. @deffn {Scheme Procedure} split-and-decode-uri-path path
  231. Split @var{path} into its components, and decode each component,
  232. removing empty components.
  233. For example, @code{"/foo/bar%20baz/"} decodes to the two-element list,
  234. @code{("foo" "bar baz")}.
  235. @end deffn
  236. @deffn {Scheme Procedure} encode-and-join-uri-path parts
  237. URI-encode each element of @var{parts}, which should be a list of
  238. strings, and join the parts together with @code{/} as a delimiter.
  239. For example, the list @code{("scrambled eggs" "biscuits&gravy")} encodes
  240. as @code{"scrambled%20eggs/biscuits%26gravy"}.
  241. @end deffn
  242. @node HTTP
  243. @subsection The Hyper-Text Transfer Protocol
  244. The initial motivation for including web functionality in Guile, rather
  245. than rely on an external package, was to establish a standard base on
  246. which people can share code. To that end, we continue the focus on data
  247. types by providing a number of low-level parsers and unparsers for
  248. elements of the HTTP protocol.
  249. If you are want to skip the low-level details for now and move on to web
  250. pages, @pxref{Web Client}, and @pxref{Web Server}. Otherwise, load the
  251. HTTP module, and read on.
  252. @example
  253. (use-modules (web http))
  254. @end example
  255. The focus of the @code{(web http)} module is to parse and unparse
  256. standard HTTP headers, representing them to Guile as native data
  257. structures. For example, a @code{Date:} header will be represented as a
  258. SRFI-19 date record (@pxref{SRFI-19}), rather than as a string.
  259. Guile tries to follow RFCs fairly strictly---the road to perdition being
  260. paved with compatibility hacks---though some allowances are made for
  261. not-too-divergent texts.
  262. Header names are represented as lower-case symbols.
  263. @deffn {Scheme Procedure} string->header name
  264. Parse @var{name} to a symbolic header name.
  265. @end deffn
  266. @deffn {Scheme Procedure} header->string sym
  267. Return the string form for the header named @var{sym}.
  268. @end deffn
  269. For example:
  270. @example
  271. (string->header "Content-Length")
  272. @result{} content-length
  273. (header->string 'content-length)
  274. @result{} "Content-Length"
  275. (string->header "FOO")
  276. @result{} foo
  277. (header->string 'foo)
  278. @result{} "Foo"
  279. @end example
  280. Guile keeps a registry of known headers, their string names, and some
  281. parsing and serialization procedures. If a header is unknown, its
  282. string name is simply its symbol name in title-case.
  283. @deffn {Scheme Procedure} known-header? sym
  284. Return @code{#t} iff @var{sym} is a known header, with associated
  285. parsers and serialization procedures.
  286. @end deffn
  287. @deffn {Scheme Procedure} header-parser sym
  288. Return the value parser for headers named @var{sym}. The result is a
  289. procedure that takes one argument, a string, and returns the parsed
  290. value. If the header isn't known to Guile, a default parser is returned
  291. that passes through the string unchanged.
  292. @end deffn
  293. @deffn {Scheme Procedure} header-validator sym
  294. Return a predicate which returns @code{#t} if the given value is valid
  295. for headers named @var{sym}. The default validator for unknown headers
  296. is @code{string?}.
  297. @end deffn
  298. @deffn {Scheme Procedure} header-writer sym
  299. Return a procedure that writes values for headers named @var{sym} to a
  300. port. The resulting procedure takes two arguments: a value and a port.
  301. The default writer is @code{display}.
  302. @end deffn
  303. For more on the set of headers that Guile knows about out of the box,
  304. @pxref{HTTP Headers}. To add your own, use the @code{declare-header!}
  305. procedure:
  306. @deffn {Scheme Procedure} declare-header! name parser validator writer [#:multiple?=@code{#f}]
  307. Declare a parser, validator, and writer for a given header.
  308. @end deffn
  309. For example, let's say you are running a web server behind some sort of
  310. proxy, and your proxy adds an @code{X-Client-Address} header, indicating
  311. the IPv4 address of the original client. You would like for the HTTP
  312. request record to parse out this header to a Scheme value, instead of
  313. leaving it as a string. You could register this header with Guile's
  314. HTTP stack like this:
  315. @example
  316. (declare-header! "X-Client-Address"
  317. (lambda (str)
  318. (inet-aton str))
  319. (lambda (ip)
  320. (and (integer? ip) (exact? ip) (<= 0 ip #xffffffff)))
  321. (lambda (ip port)
  322. (display (inet-ntoa ip) port)))
  323. @end example
  324. @deffn {Scheme Procedure} valid-header? sym val
  325. Return a true value iff @var{val} is a valid Scheme value for the header
  326. with name @var{sym}.
  327. @end deffn
  328. Now that we have a generic interface for reading and writing headers, we
  329. do just that.
  330. @deffn {Scheme Procedure} read-header port
  331. Read one HTTP header from @var{port}. Return two values: the header
  332. name and the parsed Scheme value. May raise an exception if the header
  333. was known but the value was invalid.
  334. Returns the end-of-file object for both values if the end of the message
  335. body was reached (i.e., a blank line).
  336. @end deffn
  337. @deffn {Scheme Procedure} parse-header name val
  338. Parse @var{val}, a string, with the parser for the header named
  339. @var{name}. Returns the parsed value.
  340. @end deffn
  341. @deffn {Scheme Procedure} write-header name val port
  342. Write the given header name and value to @var{port}, using the writer
  343. from @code{header-writer}.
  344. @end deffn
  345. @deffn {Scheme Procedure} read-headers port
  346. Read the headers of an HTTP message from @var{port}, returning the
  347. headers as an ordered alist.
  348. @end deffn
  349. @deffn {Scheme Procedure} write-headers headers port
  350. Write the given header alist to @var{port}. Doesn't write the final
  351. @samp{\r\n}, as the user might want to add another header.
  352. @end deffn
  353. The @code{(web http)} module also has some utility procedures to read
  354. and write request and response lines.
  355. @deffn {Scheme Procedure} parse-http-method str [start] [end]
  356. Parse an HTTP method from @var{str}. The result is an upper-case symbol,
  357. like @code{GET}.
  358. @end deffn
  359. @deffn {Scheme Procedure} parse-http-version str [start] [end]
  360. Parse an HTTP version from @var{str}, returning it as a major-minor
  361. pair. For example, @code{HTTP/1.1} parses as the pair of integers,
  362. @code{(1 . 1)}.
  363. @end deffn
  364. @deffn {Scheme Procedure} parse-request-uri str [start] [end]
  365. Parse a URI from an HTTP request line. Note that URIs in requests do not
  366. have to have a scheme or host name. The result is a URI object.
  367. @end deffn
  368. @deffn {Scheme Procedure} read-request-line port
  369. Read the first line of an HTTP request from @var{port}, returning three
  370. values: the method, the URI, and the version.
  371. @end deffn
  372. @deffn {Scheme Procedure} write-request-line method uri version port
  373. Write the first line of an HTTP request to @var{port}.
  374. @end deffn
  375. @deffn {Scheme Procedure} read-response-line port
  376. Read the first line of an HTTP response from @var{port}, returning three
  377. values: the HTTP version, the response code, and the "reason phrase".
  378. @end deffn
  379. @deffn {Scheme Procedure} write-response-line version code reason-phrase port
  380. Write the first line of an HTTP response to @var{port}.
  381. @end deffn
  382. @node HTTP Headers
  383. @subsection HTTP Headers
  384. In addition to defining the infrastructure to parse headers, the
  385. @code{(web http)} module defines specific parsers and unparsers for all
  386. headers defined in the HTTP/1.1 standard.
  387. For example, if you receive a header named @samp{Accept-Language} with a
  388. value @samp{en, es;q=0.8}, Guile parses it as a quality list (defined
  389. below):
  390. @example
  391. (parse-header 'accept-language "en, es;q=0.8")
  392. @result{} ((1000 . "en") (800 . "es"))
  393. @end example
  394. The format of the value for @samp{Accept-Language} headers is defined
  395. below, along with all other headers defined in the HTTP standard. (If
  396. the header were unknown, the value would have been returned as a
  397. string.)
  398. For brevity, the header definitions below are given in the form,
  399. @var{Type} @code{@var{name}}, indicating that values for the header
  400. @code{@var{name}} will be of the given @var{Type}. Since Guile
  401. internally treats header names in lower case, in this document we give
  402. types title-cased names. A short description of the each header's
  403. purpose and an example follow.
  404. For full details on the meanings of all of these headers, see the HTTP
  405. 1.1 standard, RFC 2616.
  406. @subsubsection HTTP Header Types
  407. Here we define the types that are used below, when defining headers.
  408. @deftp {HTTP Header Type} Date
  409. A SRFI-19 date.
  410. @end deftp
  411. @deftp {HTTP Header Type} KVList
  412. A list whose elements are keys or key-value pairs. Keys are parsed to
  413. symbols. Values are strings by default. Non-string values are the
  414. exception, and are mentioned explicitly below, as appropriate.
  415. @end deftp
  416. @deftp {HTTP Header Type} SList
  417. A list of strings.
  418. @end deftp
  419. @deftp {HTTP Header Type} Quality
  420. An exact integer between 0 and 1000. Qualities are used to express
  421. preference, given multiple options. An option with a quality of 870,
  422. for example, is preferred over an option with quality 500.
  423. (Qualities are written out over the wire as numbers between 0.0 and
  424. 1.0, but since the standard only allows three digits after the decimal,
  425. it's equivalent to integers between 0 and 1000, so that's what Guile
  426. uses.)
  427. @end deftp
  428. @deftp {HTTP Header Type} QList
  429. A quality list: a list of pairs, the car of which is a quality, and the
  430. cdr a string. Used to express a list of options, along with their
  431. qualities.
  432. @end deftp
  433. @deftp {HTTP Header Type} ETag
  434. An entity tag, represented as a pair. The car of the pair is an opaque
  435. string, and the cdr is @code{#t} if the entity tag is a ``strong'' entity
  436. tag, and @code{#f} otherwise.
  437. @end deftp
  438. @subsubsection General Headers
  439. General HTTP headers may be present in any HTTP message.
  440. @deftypevr {HTTP Header} KVList cache-control
  441. A key-value list of cache-control directives. See RFC 2616, for more
  442. details.
  443. If present, parameters to @code{max-age}, @code{max-stale},
  444. @code{min-fresh}, and @code{s-maxage} are all parsed as non-negative
  445. integers.
  446. If present, parameters to @code{private} and @code{no-cache} are parsed
  447. as lists of header names, as symbols.
  448. @example
  449. (parse-header 'cache-control "no-cache,no-store"
  450. @result{} (no-cache no-store)
  451. (parse-header 'cache-control "no-cache=\"Authorization,Date\",no-store"
  452. @result{} ((no-cache . (authorization date)) no-store)
  453. (parse-header 'cache-control "no-cache=\"Authorization,Date\",max-age=10"
  454. @result{} ((no-cache . (authorization date)) (max-age . 10))
  455. @end example
  456. @end deftypevr
  457. @deftypevr {HTTP Header} List connection
  458. A list of header names that apply only to this HTTP connection, as
  459. symbols. Additionally, the symbol @samp{close} may be present, to
  460. indicate that the server should close the connection after responding to
  461. the request.
  462. @example
  463. (parse-header 'connection "close")
  464. @result{} (close)
  465. @end example
  466. @end deftypevr
  467. @deftypevr {HTTP Header} Date date
  468. The date that a given HTTP message was originated.
  469. @example
  470. (parse-header 'date "Tue, 15 Nov 1994 08:12:31 GMT")
  471. @result{} #<date ...>
  472. @end example
  473. @end deftypevr
  474. @deftypevr {HTTP Header} KVList pragma
  475. A key-value list of implementation-specific directives.
  476. @example
  477. (parse-header 'pragma "no-cache, broccoli=tasty")
  478. @result{} (no-cache (broccoli . "tasty"))
  479. @end example
  480. @end deftypevr
  481. @deftypevr {HTTP Header} List trailer
  482. A list of header names which will appear after the message body, instead
  483. of with the message headers.
  484. @example
  485. (parse-header 'trailer "ETag")
  486. @result{} (etag)
  487. @end example
  488. @end deftypevr
  489. @deftypevr {HTTP Header} List transfer-encoding
  490. A list of transfer codings, expressed as key-value lists. The only
  491. transfer coding defined by the specification is @code{chunked}.
  492. @example
  493. (parse-header 'transfer-encoding "chunked")
  494. @result{} ((chunked))
  495. @end example
  496. @end deftypevr
  497. @deftypevr {HTTP Header} List upgrade
  498. A list of strings, indicating additional protocols that a server could use
  499. in response to a request.
  500. @example
  501. (parse-header 'upgrade "WebSocket")
  502. @result{} ("WebSocket")
  503. @end example
  504. @end deftypevr
  505. FIXME: parse out more fully?
  506. @deftypevr {HTTP Header} List via
  507. A list of strings, indicating the protocol versions and hosts of
  508. intermediate servers and proxies. There may be multiple @code{via}
  509. headers in one message.
  510. @example
  511. (parse-header 'via "1.0 venus, 1.1 mars")
  512. @result{} ("1.0 venus" "1.1 mars")
  513. @end example
  514. @end deftypevr
  515. @deftypevr {HTTP Header} List warning
  516. A list of warnings given by a server or intermediate proxy. Each
  517. warning is a itself a list of four elements: a code, as an exact integer
  518. between 0 and 1000, a host as a string, the warning text as a string,
  519. and either @code{#f} or a SRFI-19 date.
  520. There may be multiple @code{warning} headers in one message.
  521. @example
  522. (parse-header 'warning "123 foo \"core breach imminent\"")
  523. @result{} ((123 "foo" "core-breach imminent" #f))
  524. @end example
  525. @end deftypevr
  526. @subsubsection Entity Headers
  527. Entity headers may be present in any HTTP message, and refer to the
  528. resource referenced in the HTTP request or response.
  529. @deftypevr {HTTP Header} List allow
  530. A list of allowed methods on a given resource, as symbols.
  531. @example
  532. (parse-header 'allow "GET, HEAD")
  533. @result{} (GET HEAD)
  534. @end example
  535. @end deftypevr
  536. @deftypevr {HTTP Header} List content-encoding
  537. A list of content codings, as symbols.
  538. @example
  539. (parse-header 'content-encoding "gzip")
  540. @result{} (GET HEAD)
  541. @end example
  542. @end deftypevr
  543. @deftypevr {HTTP Header} List content-language
  544. The languages that a resource is in, as strings.
  545. @example
  546. (parse-header 'content-language "en")
  547. @result{} ("en")
  548. @end example
  549. @end deftypevr
  550. @deftypevr {HTTP Header} UInt content-length
  551. The number of bytes in a resource, as an exact, non-negative integer.
  552. @example
  553. (parse-header 'content-length "300")
  554. @result{} 300
  555. @end example
  556. @end deftypevr
  557. @deftypevr {HTTP Header} URI content-location
  558. The canonical URI for a resource, in the case that it is also accessible
  559. from a different URI.
  560. @example
  561. (parse-header 'content-location "http://example.com/foo")
  562. @result{} #<<uri> ...>
  563. @end example
  564. @end deftypevr
  565. @deftypevr {HTTP Header} String content-md5
  566. The MD5 digest of a resource.
  567. @example
  568. (parse-header 'content-md5 "ffaea1a79810785575e29e2bd45e2fa5")
  569. @result{} "ffaea1a79810785575e29e2bd45e2fa5"
  570. @end example
  571. @end deftypevr
  572. @deftypevr {HTTP Header} List content-range
  573. A range specification, as a list of three elements: the symbol
  574. @code{bytes}, either the symbol @code{*} or a pair of integers,
  575. indicating the byte rage, and either @code{*} or an integer, for the
  576. instance length. Used to indicate that a response only includes part of
  577. a resource.
  578. @example
  579. (parse-header 'content-range "bytes 10-20/*")
  580. @result{} (bytes (10 . 20) *)
  581. @end example
  582. @end deftypevr
  583. @deftypevr {HTTP Header} List content-type
  584. The MIME type of a resource, as a symbol, along with any parameters.
  585. @example
  586. (parse-header 'content-length "text/plain")
  587. @result{} (text/plain)
  588. (parse-header 'content-length "text/plain;charset=utf-8")
  589. @result{} (text/plain (charset . "utf-8"))
  590. @end example
  591. Note that the @code{charset} parameter is something is a misnomer, and
  592. the HTTP specification admits this. It specifies the @emph{encoding} of
  593. the characters, not the character set.
  594. @end deftypevr
  595. @deftypevr {HTTP Header} Date expires
  596. The date/time after which the resource given in a response is considered
  597. stale.
  598. @example
  599. (parse-header 'expires "Tue, 15 Nov 1994 08:12:31 GMT")
  600. @result{} #<date ...>
  601. @end example
  602. @end deftypevr
  603. @deftypevr {HTTP Header} Date last-modified
  604. The date/time on which the resource given in a response was last
  605. modified.
  606. @example
  607. (parse-header 'expires "Tue, 15 Nov 1994 08:12:31 GMT")
  608. @result{} #<date ...>
  609. @end example
  610. @end deftypevr
  611. @subsubsection Request Headers
  612. Request headers may only appear in an HTTP request, not in a response.
  613. @deftypevr {HTTP Header} List accept
  614. A list of preferred media types for a response. Each element of the
  615. list is itself a list, in the same format as @code{content-type}.
  616. @example
  617. (parse-header 'accept "text/html,text/plain;charset=utf-8")
  618. @result{} ((text/html) (text/plain (charset . "utf-8")))
  619. @end example
  620. Preference is expressed with quality values:
  621. @example
  622. (parse-header 'accept "text/html;q=0.8,text/plain;q=0.6")
  623. @result{} ((text/html (q . 800)) (text/plain (q . 600)))
  624. @end example
  625. @end deftypevr
  626. @deftypevr {HTTP Header} QList accept-charset
  627. A quality list of acceptable charsets. Note again that what HTTP calls
  628. a ``charset'' is what Guile calls a ``character encoding''.
  629. @example
  630. (parse-header 'accept-charset "iso-8859-5, unicode-1-1;q=0.8")
  631. @result{} ((1000 . "iso-8859-5") (800 . "unicode-1-1"))
  632. @end example
  633. @end deftypevr
  634. @deftypevr {HTTP Header} QList accept-encoding
  635. A quality list of acceptable content codings.
  636. @example
  637. (parse-header 'accept-encoding "gzip,identity=0.8")
  638. @result{} ((1000 . "gzip") (800 . "identity"))
  639. @end example
  640. @end deftypevr
  641. @deftypevr {HTTP Header} QList accept-language
  642. A quality list of acceptable languages.
  643. @example
  644. (parse-header 'accept-language "cn,en=0.75")
  645. @result{} ((1000 . "cn") (750 . "en"))
  646. @end example
  647. @end deftypevr
  648. @deftypevr {HTTP Header} Pair authorization
  649. Authorization credentials. The car of the pair indicates the
  650. authentication scheme, like @code{basic}. For basic authentication, the
  651. cdr of the pair will be the base64-encoded @samp{@var{user}:@var{pass}}
  652. string. For other authentication schemes, like @code{digest}, the cdr
  653. will be a key-value list of credentials.
  654. @example
  655. (parse-header 'authorization "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
  656. @result{} (basic . "QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
  657. @end example
  658. @end deftypevr
  659. @deftypevr {HTTP Header} List expect
  660. A list of expectations that a client has of a server. The expectations
  661. are key-value lists.
  662. @example
  663. (parse-header 'expect "100-continue")
  664. @result{} ((100-continue))
  665. @end example
  666. @end deftypevr
  667. @deftypevr {HTTP Header} String from
  668. The email address of a user making an HTTP request.
  669. @example
  670. (parse-header 'from "bob@@example.com")
  671. @result{} "bob@@example.com"
  672. @end example
  673. @end deftypevr
  674. @deftypevr {HTTP Header} Pair host
  675. The host for the resource being requested, as a hostname-port pair. If
  676. no port is given, the port is @code{#f}.
  677. @example
  678. (parse-header 'host "gnu.org:80")
  679. @result{} ("gnu.org" . 80)
  680. (parse-header 'host "gnu.org")
  681. @result{} ("gnu.org" . #f)
  682. @end example
  683. @end deftypevr
  684. @deftypevr {HTTP Header} *|List if-match
  685. A set of etags, indicating that the request should proceed if and only
  686. if the etag of the resource is in that set. Either the symbol @code{*},
  687. indicating any etag, or a list of entity tags.
  688. @example
  689. (parse-header 'if-match "*")
  690. @result{} *
  691. (parse-header 'if-match "asdfadf")
  692. @result{} (("asdfadf" . #t))
  693. (parse-header 'if-match W/"asdfadf")
  694. @result{} (("asdfadf" . #f))
  695. @end example
  696. @end deftypevr
  697. @deftypevr {HTTP Header} Date if-modified-since
  698. Indicates that a response should proceed if and only if the resource has
  699. been modified since the given date.
  700. @example
  701. (parse-header 'if-modified-since "Tue, 15 Nov 1994 08:12:31 GMT")
  702. @result{} #<date ...>
  703. @end example
  704. @end deftypevr
  705. @deftypevr {HTTP Header} *|List if-none-match
  706. A set of etags, indicating that the request should proceed if and only
  707. if the etag of the resource is not in the set. Either the symbol
  708. @code{*}, indicating any etag, or a list of entity tags.
  709. @example
  710. (parse-header 'if-none-match "*")
  711. @result{} *
  712. @end example
  713. @end deftypevr
  714. @deftypevr {HTTP Header} ETag|Date if-range
  715. Indicates that the range request should proceed if and only if the
  716. resource matches a modification date or an etag. Either an entity tag,
  717. or a SRFI-19 date.
  718. @example
  719. (parse-header 'if-range "\"original-etag\"")
  720. @result{} ("original-etag" . #t)
  721. @end example
  722. @end deftypevr
  723. @deftypevr {HTTP Header} Date if-unmodified-since
  724. Indicates that a response should proceed if and only if the resource has
  725. not been modified since the given date.
  726. @example
  727. (parse-header 'if-not-modified-since "Tue, 15 Nov 1994 08:12:31 GMT")
  728. @result{} #<date ...>
  729. @end example
  730. @end deftypevr
  731. @deftypevr {HTTP Header} UInt max-forwards
  732. The maximum number of proxy or gateway hops that a request should be
  733. subject to.
  734. @example
  735. (parse-header 'max-forwards "10")
  736. @result{} 10
  737. @end example
  738. @end deftypevr
  739. @deftypevr {HTTP Header} Pair proxy-authorization
  740. Authorization credentials for a proxy connection. See the documentation
  741. for @code{authorization} above for more information on the format.
  742. @example
  743. (parse-header 'proxy-authorization "Digest foo=bar,baz=qux"
  744. @result{} (digest (foo . "bar") (baz . "qux"))
  745. @end example
  746. @end deftypevr
  747. @deftypevr {HTTP Header} Pair range
  748. A range request, indicating that the client wants only part of a
  749. resource. The car of the pair is the symbol @code{bytes}, and the cdr
  750. is a list of pairs. Each element of the cdr indicates a range; the car
  751. is the first byte position and the cdr is the last byte position, as
  752. integers, or @code{#f} if not given.
  753. @example
  754. (parse-header 'range "bytes=10-30,50-")
  755. @result{} (bytes (10 . 30) (50 . #f))
  756. @end example
  757. @end deftypevr
  758. @deftypevr {HTTP Header} URI referer
  759. The URI of the resource that referred the user to this resource. The
  760. name of the header is a misspelling, but we are stuck with it.
  761. @example
  762. (parse-header 'referer "http://www.gnu.org/")
  763. @result{} #<uri ...>
  764. @end example
  765. @end deftypevr
  766. @deftypevr {HTTP Header} List te
  767. A list of transfer codings, expressed as key-value lists. A common
  768. transfer coding is @code{trailers}.
  769. @example
  770. (parse-header 'te "trailers")
  771. @result{} ((trailers))
  772. @end example
  773. @end deftypevr
  774. @deftypevr {HTTP Header} String user-agent
  775. A string indicating the user agent making the request. The
  776. specification defines a structured format for this header, but it is
  777. widely disregarded, so Guile does not attempt to parse strictly.
  778. @example
  779. (parse-header 'user-agent "Mozilla/5.0")
  780. @result{} "Mozilla/5.0"
  781. @end example
  782. @end deftypevr
  783. @subsubsection Response Headers
  784. @deftypevr {HTTP Header} List accept-ranges
  785. A list of range units that the server supports, as symbols.
  786. @example
  787. (parse-header 'accept-ranges "bytes")
  788. @result{} (bytes)
  789. @end example
  790. @end deftypevr
  791. @deftypevr {HTTP Header} UInt age
  792. The age of a cached response, in seconds.
  793. @example
  794. (parse-header 'age "3600")
  795. @result{} 3600
  796. @end example
  797. @end deftypevr
  798. @deftypevr {HTTP Header} ETag etag
  799. The entity-tag of the resource.
  800. @example
  801. (parse-header 'etag "\"foo\"")
  802. @result{} ("foo" . #t)
  803. @end example
  804. @end deftypevr
  805. @deftypevr {HTTP Header} URI location
  806. A URI on which a request may be completed. Used in combination with a
  807. redirecting status code to perform client-side redirection.
  808. @example
  809. (parse-header 'location "http://example.com/other")
  810. @result{} #<uri ...>
  811. @end example
  812. @end deftypevr
  813. @deftypevr {HTTP Header} List proxy-authenticate
  814. A list of challenges to a proxy, indicating the need for authentication.
  815. @example
  816. (parse-header 'proxy-authenticate "Basic realm=\"foo\"")
  817. @result{} ((basic (realm . "foo")))
  818. @end example
  819. @end deftypevr
  820. @deftypevr {HTTP Header} UInt|Date retry-after
  821. Used in combination with a server-busy status code, like 503, to
  822. indicate that a client should retry later. Either a number of seconds,
  823. or a date.
  824. @example
  825. (parse-header 'retry-after "60")
  826. @result{} 60
  827. @end example
  828. @end deftypevr
  829. @deftypevr {HTTP Header} String server
  830. A string identifying the server.
  831. @example
  832. (parse-header 'server "My first web server")
  833. @result{} "My first web server"
  834. @end example
  835. @end deftypevr
  836. @deftypevr {HTTP Header} *|List vary
  837. A set of request headers that were used in computing this response.
  838. Used to indicate that server-side content negotiation was performed, for
  839. example in response to the @code{accept-language} header. Can also be
  840. the symbol @code{*}, indicating that all headers were considered.
  841. @example
  842. (parse-header 'vary "Accept-Language, Accept")
  843. @result{} (accept-language accept)
  844. @end example
  845. @end deftypevr
  846. @deftypevr {HTTP Header} List www-authenticate
  847. A list of challenges to a user, indicating the need for authentication.
  848. @example
  849. (parse-header 'www-authenticate "Basic realm=\"foo\"")
  850. @result{} ((basic (realm . "foo")))
  851. @end example
  852. @end deftypevr
  853. @node Requests
  854. @subsection HTTP Requests
  855. @example
  856. (use-modules (web request))
  857. @end example
  858. The request module contains a data type for HTTP requests.
  859. @subsubsection An Important Note on Character Sets
  860. HTTP requests consist of two parts: the request proper, consisting of a
  861. request line and a set of headers, and (optionally) a body. The body
  862. might have a binary content-type, and even in the textual case its
  863. length is specified in bytes, not characters.
  864. Therefore, HTTP is a fundamentally binary protocol. However the request
  865. line and headers are specified to be in a subset of ASCII, so they can
  866. be treated as text, provided that the port's encoding is set to an
  867. ASCII-compatible one-byte-per-character encoding. ISO-8859-1 (latin-1)
  868. is just such an encoding, and happens to be very efficient for Guile.
  869. So what Guile does when reading requests from the wire, or writing them
  870. out, is to set the port's encoding to latin-1, and treating the request
  871. headers as text.
  872. The request body is another issue. For binary data, the data is
  873. probably in a bytevector, so we use the R6RS binary output procedures to
  874. write out the binary payload. Textual data usually has to be written
  875. out to some character encoding, usually UTF-8, and then the resulting
  876. bytevector is written out to the port.
  877. In summary, Guile reads and writes HTTP over latin-1 sockets, without
  878. any loss of generality.
  879. @subsubsection Request API
  880. @deffn {Scheme Procedure} request?
  881. @deffnx {Scheme Procedure} request-method
  882. @deffnx {Scheme Procedure} request-uri
  883. @deffnx {Scheme Procedure} request-version
  884. @deffnx {Scheme Procedure} request-headers
  885. @deffnx {Scheme Procedure} request-meta
  886. @deffnx {Scheme Procedure} request-port
  887. A predicate and field accessors for the request type. The fields are as
  888. follows:
  889. @table @code
  890. @item method
  891. The HTTP method, for example, @code{GET}.
  892. @item uri
  893. The URI as a URI record.
  894. @item version
  895. The HTTP version pair, like @code{(1 . 1)}.
  896. @item headers
  897. The request headers, as an alist of parsed values.
  898. @item meta
  899. An arbitrary alist of other data, for example information returned in
  900. the @code{sockaddr} from @code{accept} (@pxref{Network Sockets and
  901. Communication}).
  902. @item port
  903. The port on which to read or write a request body, if any.
  904. @end table
  905. @end deffn
  906. @deffn {Scheme Procedure} read-request port [meta='()]
  907. Read an HTTP request from @var{port}, optionally attaching the given
  908. metadata, @var{meta}.
  909. As a side effect, sets the encoding on @var{port} to ISO-8859-1
  910. (latin-1), so that reading one character reads one byte. See the
  911. discussion of character sets above, for more information.
  912. Note that the body is not part of the request. Once you have read a
  913. request, you may read the body separately, and likewise for writing
  914. requests.
  915. @end deffn
  916. @deffn {Scheme Procedure} build-request uri [#:method='GET] [#:version='(1 . 1)] [#:headers='()] [#:port=#f] [#:meta='()] [#:validate-headers?=#t]
  917. Construct an HTTP request object. If @var{validate-headers?} is true,
  918. the headers are each run through their respective validators.
  919. @end deffn
  920. @deffn {Scheme Procedure} write-request r port
  921. Write the given HTTP request to @var{port}.
  922. Return a new request, whose @code{request-port} will continue writing
  923. on @var{port}, perhaps using some transfer encoding.
  924. @end deffn
  925. @deffn {Scheme Procedure} read-request-body r
  926. Reads the request body from @var{r}, as a bytevector. Return @code{#f}
  927. if there was no request body.
  928. @end deffn
  929. @deffn {Scheme Procedure} write-request-body r bv
  930. Write @var{bv}, a bytevector, to the port corresponding to the HTTP
  931. request @var{r}.
  932. @end deffn
  933. The various headers that are typically associated with HTTP requests may
  934. be accessed with these dedicated accessors. @xref{HTTP Headers}, for
  935. more information on the format of parsed headers.
  936. @deffn {Scheme Procedure} request-accept request [default='()]
  937. @deffnx {Scheme Procedure} request-accept-charset request [default='()]
  938. @deffnx {Scheme Procedure} request-accept-encoding request [default='()]
  939. @deffnx {Scheme Procedure} request-accept-language request [default='()]
  940. @deffnx {Scheme Procedure} request-allow request [default='()]
  941. @deffnx {Scheme Procedure} request-authorization request [default=#f]
  942. @deffnx {Scheme Procedure} request-cache-control request [default='()]
  943. @deffnx {Scheme Procedure} request-connection request [default='()]
  944. @deffnx {Scheme Procedure} request-content-encoding request [default='()]
  945. @deffnx {Scheme Procedure} request-content-language request [default='()]
  946. @deffnx {Scheme Procedure} request-content-length request [default=#f]
  947. @deffnx {Scheme Procedure} request-content-location request [default=#f]
  948. @deffnx {Scheme Procedure} request-content-md5 request [default=#f]
  949. @deffnx {Scheme Procedure} request-content-range request [default=#f]
  950. @deffnx {Scheme Procedure} request-content-type request [default=#f]
  951. @deffnx {Scheme Procedure} request-date request [default=#f]
  952. @deffnx {Scheme Procedure} request-expect request [default='()]
  953. @deffnx {Scheme Procedure} request-expires request [default=#f]
  954. @deffnx {Scheme Procedure} request-from request [default=#f]
  955. @deffnx {Scheme Procedure} request-host request [default=#f]
  956. @deffnx {Scheme Procedure} request-if-match request [default=#f]
  957. @deffnx {Scheme Procedure} request-if-modified-since request [default=#f]
  958. @deffnx {Scheme Procedure} request-if-none-match request [default=#f]
  959. @deffnx {Scheme Procedure} request-if-range request [default=#f]
  960. @deffnx {Scheme Procedure} request-if-unmodified-since request [default=#f]
  961. @deffnx {Scheme Procedure} request-last-modified request [default=#f]
  962. @deffnx {Scheme Procedure} request-max-forwards request [default=#f]
  963. @deffnx {Scheme Procedure} request-pragma request [default='()]
  964. @deffnx {Scheme Procedure} request-proxy-authorization request [default=#f]
  965. @deffnx {Scheme Procedure} request-range request [default=#f]
  966. @deffnx {Scheme Procedure} request-referer request [default=#f]
  967. @deffnx {Scheme Procedure} request-te request [default=#f]
  968. @deffnx {Scheme Procedure} request-trailer request [default='()]
  969. @deffnx {Scheme Procedure} request-transfer-encoding request [default='()]
  970. @deffnx {Scheme Procedure} request-upgrade request [default='()]
  971. @deffnx {Scheme Procedure} request-user-agent request [default=#f]
  972. @deffnx {Scheme Procedure} request-via request [default='()]
  973. @deffnx {Scheme Procedure} request-warning request [default='()]
  974. Return the given request header, or @var{default} if none was present.
  975. @end deffn
  976. @deffn {Scheme Procedure} request-absolute-uri r [default-host=#f] [default-port=#f]
  977. A helper routine to determine the absolute URI of a request, using the
  978. @code{host} header and the default host and port.
  979. @end deffn
  980. @node Responses
  981. @subsection HTTP Responses
  982. @example
  983. (use-modules (web response))
  984. @end example
  985. As with requests (@pxref{Requests}), Guile offers a data type for HTTP
  986. responses. Again, the body is represented separately from the request.
  987. @deffn {Scheme Procedure} response?
  988. @deffnx {Scheme Procedure} response-version
  989. @deffnx {Scheme Procedure} response-code
  990. @deffnx {Scheme Procedure} response-reason-phrase response
  991. @deffnx {Scheme Procedure} response-headers
  992. @deffnx {Scheme Procedure} response-port
  993. A predicate and field accessors for the response type. The fields are as
  994. follows:
  995. @table @code
  996. @item version
  997. The HTTP version pair, like @code{(1 . 1)}.
  998. @item code
  999. The HTTP response code, like @code{200}.
  1000. @item reason-phrase
  1001. The reason phrase, or the standard reason phrase for the response's
  1002. code.
  1003. @item headers
  1004. The response headers, as an alist of parsed values.
  1005. @item port
  1006. The port on which to read or write a response body, if any.
  1007. @end table
  1008. @end deffn
  1009. @deffn {Scheme Procedure} read-response port
  1010. Read an HTTP response from @var{port}.
  1011. As a side effect, sets the encoding on @var{port} to ISO-8859-1
  1012. (latin-1), so that reading one character reads one byte. See the
  1013. discussion of character sets in @ref{Responses}, for more information.
  1014. @end deffn
  1015. @deffn {Scheme Procedure} build-response [#:version='(1 . 1)] [#:code=200] [#:reason-phrase=#f] [#:headers='()] [#:port=#f] [#:validate-headers?=#t]
  1016. Construct an HTTP response object. If @var{validate-headers?} is true,
  1017. the headers are each run through their respective validators.
  1018. @end deffn
  1019. @deffn {Scheme Procedure} adapt-response-version response version
  1020. Adapt the given response to a different HTTP version. Return a new HTTP
  1021. response.
  1022. The idea is that many applications might just build a response for the
  1023. default HTTP version, and this method could handle a number of
  1024. programmatic transformations to respond to older HTTP versions (0.9 and
  1025. 1.0). But currently this function is a bit heavy-handed, just updating
  1026. the version field.
  1027. @end deffn
  1028. @deffn {Scheme Procedure} write-response r port
  1029. Write the given HTTP response to @var{port}.
  1030. Return a new response, whose @code{response-port} will continue writing
  1031. on @var{port}, perhaps using some transfer encoding.
  1032. @end deffn
  1033. @deffn {Scheme Procedure} response-must-not-include-body? r
  1034. Some responses, like those with status code 304, are specified as never
  1035. having bodies. This predicate returns @code{#t} for those responses.
  1036. Note also, though, that responses to @code{HEAD} requests must also not
  1037. have a body.
  1038. @end deffn
  1039. @deffn {Scheme Procedure} read-response-body r
  1040. Read the response body from @var{r}, as a bytevector. Returns @code{#f}
  1041. if there was no response body.
  1042. @end deffn
  1043. @deffn {Scheme Procedure} write-response-body r bv
  1044. Write @var{bv}, a bytevector, to the port corresponding to the HTTP
  1045. response @var{r}.
  1046. @end deffn
  1047. As with requests, the various headers that are typically associated with
  1048. HTTP responses may be accessed with these dedicated accessors.
  1049. @xref{HTTP Headers}, for more information on the format of parsed
  1050. headers.
  1051. @deffn {Scheme Procedure} response-accept-ranges response [default=#f]
  1052. @deffnx {Scheme Procedure} response-age response [default='()]
  1053. @deffnx {Scheme Procedure} response-allow response [default='()]
  1054. @deffnx {Scheme Procedure} response-cache-control response [default='()]
  1055. @deffnx {Scheme Procedure} response-connection response [default='()]
  1056. @deffnx {Scheme Procedure} response-content-encoding response [default='()]
  1057. @deffnx {Scheme Procedure} response-content-language response [default='()]
  1058. @deffnx {Scheme Procedure} response-content-length response [default=#f]
  1059. @deffnx {Scheme Procedure} response-content-location response [default=#f]
  1060. @deffnx {Scheme Procedure} response-content-md5 response [default=#f]
  1061. @deffnx {Scheme Procedure} response-content-range response [default=#f]
  1062. @deffnx {Scheme Procedure} response-content-type response [default=#f]
  1063. @deffnx {Scheme Procedure} response-date response [default=#f]
  1064. @deffnx {Scheme Procedure} response-etag response [default=#f]
  1065. @deffnx {Scheme Procedure} response-expires response [default=#f]
  1066. @deffnx {Scheme Procedure} response-last-modified response [default=#f]
  1067. @deffnx {Scheme Procedure} response-location response [default=#f]
  1068. @deffnx {Scheme Procedure} response-pragma response [default='()]
  1069. @deffnx {Scheme Procedure} response-proxy-authenticate response [default=#f]
  1070. @deffnx {Scheme Procedure} response-retry-after response [default=#f]
  1071. @deffnx {Scheme Procedure} response-server response [default=#f]
  1072. @deffnx {Scheme Procedure} response-trailer response [default='()]
  1073. @deffnx {Scheme Procedure} response-transfer-encoding response [default='()]
  1074. @deffnx {Scheme Procedure} response-upgrade response [default='()]
  1075. @deffnx {Scheme Procedure} response-vary response [default='()]
  1076. @deffnx {Scheme Procedure} response-via response [default='()]
  1077. @deffnx {Scheme Procedure} response-warning response [default='()]
  1078. @deffnx {Scheme Procedure} response-www-authenticate response [default=#f]
  1079. Return the given response header, or @var{default} if none was present.
  1080. @end deffn
  1081. @node Web Client
  1082. @subsection Web Client
  1083. @code{(web client)} provides a simple, synchronous HTTP client, built on
  1084. the lower-level HTTP, request, and response modules.
  1085. @deffn {Scheme Procedure} open-socket-for-uri uri
  1086. @end deffn
  1087. @deffn {Scheme Procedure} http-get uri [#:port=(open-socket-for-uri uri)] [#:version='(1 . 1)] [#:keep-alive?=#f] [#:extra-headers='()] [#:decode-body?=#t]
  1088. Connect to the server corresponding to @var{uri} and ask for the
  1089. resource, using the @code{GET} method. If you already have a port open,
  1090. pass it as @var{port}. The port will be closed at the end of the
  1091. request unless @var{keep-alive?} is true. Any extra headers in the
  1092. alist @var{extra-headers} will be added to the request.
  1093. If @var{decode-body?} is true, as is the default, the body of the
  1094. response will be decoded to string, if it is a textual content-type.
  1095. Otherwise it will be returned as a bytevector.
  1096. @end deffn
  1097. @code{http-get} is useful for making one-off requests to web sites. If
  1098. you are writing a web spider or some other client that needs to handle a
  1099. number of requests in parallel, it's better to build an event-driven URL
  1100. fetcher, similar in structure to the web server (@pxref{Web Server}).
  1101. Another option, good but not as performant, would be to use threads,
  1102. possibly via par-map or futures.
  1103. More helper procedures for the other common HTTP verbs would be a good
  1104. addition to this module. Send your code to
  1105. @email{guile-user@@gnu.org}.
  1106. @node Web Server
  1107. @subsection Web Server
  1108. @code{(web server)} is a generic web server interface, along with a main
  1109. loop implementation for web servers controlled by Guile.
  1110. @example
  1111. (use-modules (web server))
  1112. @end example
  1113. The lowest layer is the @code{<server-impl>} object, which defines a set
  1114. of hooks to open a server, read a request from a client, write a
  1115. response to a client, and close a server. These hooks -- @code{open},
  1116. @code{read}, @code{write}, and @code{close}, respectively -- are bound
  1117. together in a @code{<server-impl>} object. Procedures in this module take a
  1118. @code{<server-impl>} object, if needed.
  1119. A @code{<server-impl>} may also be looked up by name. If you pass the
  1120. @code{http} symbol to @code{run-server}, Guile looks for a variable
  1121. named @code{http} in the @code{(web server http)} module, which should
  1122. be bound to a @code{<server-impl>} object. Such a binding is made by
  1123. instantiation of the @code{define-server-impl} syntax. In this way the
  1124. run-server loop can automatically load other backends if available.
  1125. The life cycle of a server goes as follows:
  1126. @enumerate
  1127. @item
  1128. The @code{open} hook is called, to open the server. @code{open} takes 0 or
  1129. more arguments, depending on the backend, and returns an opaque
  1130. server socket object, or signals an error.
  1131. @item
  1132. The @code{read} hook is called, to read a request from a new client.
  1133. The @code{read} hook takes one argument, the server socket. It should
  1134. return three values: an opaque client socket, the request, and the
  1135. request body. The request should be a @code{<request>} object, from
  1136. @code{(web request)}. The body should be a string or a bytevector, or
  1137. @code{#f} if there is no body.
  1138. If the read failed, the @code{read} hook may return #f for the client
  1139. socket, request, and body.
  1140. @item
  1141. A user-provided handler procedure is called, with the request and body
  1142. as its arguments. The handler should return two values: the response,
  1143. as a @code{<response>} record from @code{(web response)}, and the
  1144. response body as bytevector, or @code{#f} if not present.
  1145. The respose and response body are run through @code{sanitize-response},
  1146. documented below. This allows the handler writer to take some
  1147. convenient shortcuts: for example, instead of a @code{<response>}, the
  1148. handler can simply return an alist of headers, in which case a default
  1149. response object is constructed with those headers. Instead of a
  1150. bytevector for the body, the handler can return a string, which will be
  1151. serialized into an appropriate encoding; or it can return a procedure,
  1152. which will be called on a port to write out the data. See the
  1153. @code{sanitize-response} documentation, for more.
  1154. @item
  1155. The @code{write} hook is called with three arguments: the client
  1156. socket, the response, and the body. The @code{write} hook returns no
  1157. values.
  1158. @item
  1159. At this point the request handling is complete. For a loop, we
  1160. loop back and try to read a new request.
  1161. @item
  1162. If the user interrupts the loop, the @code{close} hook is called on
  1163. the server socket.
  1164. @end enumerate
  1165. A user may define a server implementation with the following form:
  1166. @deffn {Scheme Procedure} define-server-impl name open read write close
  1167. Make a @code{<server-impl>} object with the hooks @var{open},
  1168. @var{read}, @var{write}, and @var{close}, and bind it to the symbol
  1169. @var{name} in the current module.
  1170. @end deffn
  1171. @deffn {Scheme Procedure} lookup-server-impl impl
  1172. Look up a server implementation. If @var{impl} is a server
  1173. implementation already, it is returned directly. If it is a symbol, the
  1174. binding named @var{impl} in the @code{(web server @var{impl})} module is
  1175. looked up. Otherwise an error is signaled.
  1176. Currently a server implementation is a somewhat opaque type, useful only
  1177. for passing to other procedures in this module, like @code{read-client}.
  1178. @end deffn
  1179. The @code{(web server)} module defines a number of routines that use
  1180. @code{<server-impl>} objects to implement parts of a web server. Given
  1181. that we don't expose the accessors for the various fields of a
  1182. @code{<server-impl>}, indeed these routines are the only procedures with
  1183. any access to the impl objects.
  1184. @deffn {Scheme Procedure} open-server impl open-params
  1185. Open a server for the given implementation. Return one value, the new
  1186. server object. The implementation's @code{open} procedure is applied to
  1187. @var{open-params}, which should be a list.
  1188. @end deffn
  1189. @deffn {Scheme Procedure} read-client impl server
  1190. Read a new client from @var{server}, by applying the implementation's
  1191. @code{read} procedure to the server. If successful, return three
  1192. values: an object corresponding to the client, a request object, and the
  1193. request body. If any exception occurs, return @code{#f} for all three
  1194. values.
  1195. @end deffn
  1196. @deffn {Scheme Procedure} handle-request handler request body state
  1197. Handle a given request, returning the response and body.
  1198. The response and response body are produced by calling the given
  1199. @var{handler} with @var{request} and @var{body} as arguments.
  1200. The elements of @var{state} are also passed to @var{handler} as
  1201. arguments, and may be returned as additional values. The new
  1202. @var{state}, collected from the @var{handler}'s return values, is then
  1203. returned as a list. The idea is that a server loop receives a handler
  1204. from the user, along with whatever state values the user is interested
  1205. in, allowing the user's handler to explicitly manage its state.
  1206. @end deffn
  1207. @deffn {Scheme Procedure} sanitize-response request response body
  1208. "Sanitize" the given response and body, making them appropriate for the
  1209. given request.
  1210. As a convenience to web handler authors, @var{response} may be given as
  1211. an alist of headers, in which case it is used to construct a default
  1212. response. Ensures that the response version corresponds to the request
  1213. version. If @var{body} is a string, encodes the string to a bytevector,
  1214. in an encoding appropriate for @var{response}. Adds a
  1215. @code{content-length} and @code{content-type} header, as necessary.
  1216. If @var{body} is a procedure, it is called with a port as an argument,
  1217. and the output collected as a bytevector. In the future we might try to
  1218. instead use a compressing, chunk-encoded port, and call this procedure
  1219. later, in the write-client procedure. Authors are advised not to rely on
  1220. the procedure being called at any particular time.
  1221. @end deffn
  1222. @deffn {Scheme Procedure} write-client impl server client response body
  1223. Write an HTTP response and body to @var{client}. If the server and
  1224. client support persistent connections, it is the implementation's
  1225. responsibility to keep track of the client thereafter, presumably by
  1226. attaching it to the @var{server} argument somehow.
  1227. @end deffn
  1228. @deffn {Scheme Procedure} close-server impl server
  1229. Release resources allocated by a previous invocation of
  1230. @code{open-server}.
  1231. @end deffn
  1232. Given the procedures above, it is a small matter to make a web server:
  1233. @deffn {Scheme Procedure} serve-one-client handler impl server state
  1234. Read one request from @var{server}, call @var{handler} on the request
  1235. and body, and write the response to the client. Return the new state
  1236. produced by the handler procedure.
  1237. @end deffn
  1238. @deffn {Scheme Procedure} run-server handler [impl='http] [open-params='()] . state
  1239. Run Guile's built-in web server.
  1240. @var{handler} should be a procedure that takes two or more arguments,
  1241. the HTTP request and request body, and returns two or more values, the
  1242. response and response body.
  1243. For examples, skip ahead to the next section, @ref{Web Examples}.
  1244. The response and body will be run through @code{sanitize-response}
  1245. before sending back to the client.
  1246. Additional arguments to @var{handler} are taken from @var{state}.
  1247. Additional return values are accumulated into a new @var{state}, which
  1248. will be used for subsequent requests. In this way a handler can
  1249. explicitly manage its state.
  1250. @end deffn
  1251. The default web server implementation is @code{http}, which binds to a
  1252. socket, listening for request on that port.
  1253. @deffn {HTTP Implementation} http [#:host=#f] [#:family=AF_INET] [#:addr=INADDR_LOOPBACK] [#:port 8080] [#:socket]
  1254. The default HTTP implementation. We document it as a function with
  1255. keyword arguments, because that is precisely the way that it is -- all
  1256. of the @var{open-params} to @code{run-server} get passed to the
  1257. implementation's open function.
  1258. @example
  1259. ;; The defaults: localhost:8080
  1260. (run-server handler)
  1261. ;; Same thing
  1262. (run-server handler 'http '())
  1263. ;; On a different port
  1264. (run-server handler 'http '(#:port 8081))
  1265. ;; IPv6
  1266. (run-server handler 'http '(#:family AF_INET6 #:port 8081))
  1267. ;; Custom socket
  1268. (run-server handler 'http `(#:socket ,(sudo-make-me-a-socket)))
  1269. @end example
  1270. @end deffn
  1271. @node Web Examples
  1272. @subsection Web Examples
  1273. Well, enough about the tedious internals. Let's make a web application!
  1274. @subsubsection Hello, World!
  1275. The first program we have to write, of course, is ``Hello, World!''.
  1276. This means that we have to implement a web handler that does what we
  1277. want.
  1278. Now we define a handler, a function of two arguments and two return
  1279. values:
  1280. @example
  1281. (define (handler request request-body)
  1282. (values @var{response} @var{response-body}))
  1283. @end example
  1284. In this first example, we take advantage of a short-cut, returning an
  1285. alist of headers instead of a proper response object. The response body
  1286. is our payload:
  1287. @example
  1288. (define (hello-world-handler request request-body)
  1289. (values '((content-type . (text/plain)))
  1290. "Hello World!"))
  1291. @end example
  1292. Now let's test it, by running a server with this handler. Load up the
  1293. web server module if you haven't yet done so, and run a server with this
  1294. handler:
  1295. @example
  1296. (use-modules (web server))
  1297. (run-server hello-world-handler)
  1298. @end example
  1299. By default, the web server listens for requests on
  1300. @code{localhost:8080}. Visit that address in your web browser to
  1301. test. If you see the string, @code{Hello World!}, sweet!
  1302. @subsubsection Inspecting the Request
  1303. The Hello World program above is a general greeter, responding to all
  1304. URIs. To make a more exclusive greeter, we need to inspect the request
  1305. object, and conditionally produce different results. So let's load up
  1306. the request, response, and URI modules, and do just that.
  1307. @example
  1308. (use-modules (web server)) ; you probably did this already
  1309. (use-modules (web request)
  1310. (web response)
  1311. (web uri))
  1312. (define (request-path-components request)
  1313. (split-and-decode-uri-path (uri-path (request-uri request))))
  1314. (define (hello-hacker-handler request body)
  1315. (if (equal? (request-path-components request)
  1316. '("hacker"))
  1317. (values '((content-type . (text/plain)))
  1318. "Hello hacker!")
  1319. (not-found request)))
  1320. (run-server hello-hacker-handler)
  1321. @end example
  1322. Here we see that we have defined a helper to return the components of
  1323. the URI path as a list of strings, and used that to check for a request
  1324. to @code{/hacker/}. Then the success case is just as before -- visit
  1325. @code{http://localhost:8080/hacker/} in your browser to check.
  1326. You should always match against URI path components as decoded by
  1327. @code{split-and-decode-uri-path}. The above example will work for
  1328. @code{/hacker/}, @code{//hacker///}, and @code{/h%61ck%65r}.
  1329. But we forgot to define @code{not-found}! If you are pasting these
  1330. examples into a REPL, accessing any other URI in your web browser will
  1331. drop your Guile console into the debugger:
  1332. @example
  1333. <unnamed port>:38:7: In procedure module-lookup:
  1334. <unnamed port>:38:7: Unbound variable: not-found
  1335. Entering a new prompt. Type `,bt' for a backtrace or `,q' to continue.
  1336. scheme@@(guile-user) [1]>
  1337. @end example
  1338. So let's define the function, right there in the debugger. As you
  1339. probably know, we'll want to return a 404 response.
  1340. @example
  1341. ;; Paste this in your REPL
  1342. (define (not-found request)
  1343. (values (build-response #:code 404)
  1344. (string-append "Resource not found: "
  1345. (uri->string (request-uri request)))))
  1346. ;; Now paste this to let the web server keep going:
  1347. ,continue
  1348. @end example
  1349. Now if you access @code{http://localhost/foo/}, you get this error
  1350. message. (Note that some popular web browsers won't show
  1351. server-generated 404 messages, showing their own instead, unless the 404
  1352. message body is long enough.)
  1353. @subsubsection Higher-Level Interfaces
  1354. The web handler interface is a common baseline that all kinds of Guile
  1355. web applications can use. You will usually want to build something on
  1356. top of it, however, especially when producing HTML. Here is a simple
  1357. example that builds up HTML output using SXML (@pxref{sxml simple}).
  1358. First, load up the modules:
  1359. @example
  1360. (use-modules (web server)
  1361. (web request)
  1362. (web response)
  1363. (sxml simple))
  1364. @end example
  1365. Now we define a simple templating function that takes a list of HTML
  1366. body elements, as SXML, and puts them in our super template:
  1367. @example
  1368. (define (templatize title body)
  1369. `(html (head (title ,title))
  1370. (body ,@@body)))
  1371. @end example
  1372. For example, the simplest Hello HTML can be produced like this:
  1373. @example
  1374. (sxml->xml (templatize "Hello!" '((b "Hi!"))))
  1375. @print{}
  1376. <html><head><title>Hello!</title></head><body><b>Hi!</b></body></html>
  1377. @end example
  1378. Much better to work with Scheme data types than to work with HTML as
  1379. strings. Now we define a little response helper:
  1380. @example
  1381. (define* (respond #:optional body #:key
  1382. (status 200)
  1383. (title "Hello hello!")
  1384. (doctype "<!DOCTYPE html>\n")
  1385. (content-type-params '((charset . "utf-8")))
  1386. (content-type 'text/html)
  1387. (extra-headers '())
  1388. (sxml (and body (templatize title body))))
  1389. (values (build-response
  1390. #:code status
  1391. #:headers `((content-type
  1392. . (,content-type ,@@content-type-params))
  1393. ,@@extra-headers))
  1394. (lambda (port)
  1395. (if sxml
  1396. (begin
  1397. (if doctype (display doctype port))
  1398. (sxml->xml sxml port))))))
  1399. @end example
  1400. Here we see the power of keyword arguments with default initializers. By
  1401. the time the arguments are fully parsed, the @code{sxml} local variable
  1402. will hold the templated SXML, ready for sending out to the client.
  1403. Also, instead of returning the body as a string, @code{respond} gives a
  1404. procedure, which will be called by the web server to write out the
  1405. response to the client.
  1406. Now, a simple example using this responder, which lays out the incoming
  1407. headers in an HTML table.
  1408. @example
  1409. (define (debug-page request body)
  1410. (respond
  1411. `((h1 "hello world!")
  1412. (table
  1413. (tr (th "header") (th "value"))
  1414. ,@@(map (lambda (pair)
  1415. `(tr (td (tt ,(with-output-to-string
  1416. (lambda () (display (car pair))))))
  1417. (td (tt ,(with-output-to-string
  1418. (lambda ()
  1419. (write (cdr pair))))))))
  1420. (request-headers request))))))
  1421. (run-server debug-page)
  1422. @end example
  1423. Now if you visit any local address in your web browser, we actually see
  1424. some HTML, finally.
  1425. @subsubsection Conclusion
  1426. Well, this is about as far as Guile's built-in web support goes, for
  1427. now. There are many ways to make a web application, but hopefully by
  1428. standardizing the most fundamental data types, users will be able to
  1429. choose the approach that suits them best, while also being able to
  1430. switch between implementations of the server. This is a relatively new
  1431. part of Guile, so if you have feedback, let us know, and we can take it
  1432. into account. Happy hacking on the web!
  1433. @c Local Variables:
  1434. @c TeX-master: "guile.texi"
  1435. @c End: