aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md276
-rw-r--r--ROADMAP.md22
-rw-r--r--examples/echo_get/src/toppage_handler.erl2
-rw-r--r--examples/echo_post/src/toppage_handler.erl2
-rw-r--r--src/cowboy_clock.erl46
-rw-r--r--src/cowboy_cookies.erl416
-rw-r--r--src/cowboy_http.erl165
-rw-r--r--src/cowboy_req.erl32
-rw-r--r--src/cowboy_websocket.erl10
9 files changed, 354 insertions, 617 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4545ff1..2f4fc12 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,25 +4,28 @@ CHANGELOG
next
----
-* This release drops R14 compatibility
+ * This release drops R14 compatibility
-* Add CONTRIBUTING.md file
+ * Add CONTRIBUTING.md file
-* Use Ranch for connection handling
+ * Use Ranch for connection handling
To start listeners you can now use cowboy:start_http/4 for HTTP,
and cowboy:start_https/4 for HTTPS. The proper transport and
protocol modules will be used.
-* Shorten the name of many modules
+ * Add a dependency on crypto
- * cowboy_http_protocol becomes cowboy_protocol.
- * cowboy_http_req becomes cowboy_req.
- * cowboy_http_rest becomes cowboy_rest.
- * cowboy_http_static becomes cowboy_static.
- * cowboy_http_websocket becomes cowboy_websocket.
+ * Remove implicit dependency on inets
-* Introduce the cowboy_req:req() opaque type
+ * Shorten the name of many modules
+ * cowboy_http_protocol becomes cowboy_protocol
+ * cowboy_http_req becomes cowboy_req
+ * cowboy_http_rest becomes cowboy_rest
+ * cowboy_http_static becomes cowboy_static
+ * cowboy_http_websocket becomes cowboy_websocket
+
+ * Introduce the cowboy_req:req() opaque type
The include/http.hrl file was removed. Users are expected to use
the cowboy_req API to access or modify the Req object.
@@ -30,84 +33,95 @@ next
This required a lot of changes so cleanup and optimization were
performed where possible.
-* Add many cowboy_req functions
-
- * cowboy_req:delete_resp_header/2 deletes a previously set resp header.
- * cowboy_req:set_meta/3 sets metadata in the Req object.
- * cowboy_req:to_list/1 converts the Req object to a list of key/values.
- * cowboy_req:fragment/1 returns the request URL fragment.
- * cowboy_req:host_url/1 returns the request URL without the path or qs.
- * cowboy_req:url/1 returns the full request URL.
+ * Add many cowboy_req functions
+ * cowboy_req:delete_resp_header/2 deletes a previously set resp header
+ * cowboy_req:set_meta/3 sets metadata in the Req object
+ * cowboy_req:to_list/1 converts the Req object to a list of key/values
+ * cowboy_req:fragment/1 returns the request URL fragment
+ * cowboy_req:host_url/1 returns the request URL without the path or qs
+ * cowboy_req:url/1 returns the full request URL
+
+ * Rename or drop many cowboy_req functions
+ * Replace cowboy_req:host/1 with cowboy_req:raw_host/1
+ * Replace cowboy_req:path/1 with cowboy_req:raw_path/1
+ * cowboy_req:raw_qs/1 becomes cowboy_req:qs/1
+
+ * Change the signature of many cowboy_req functions
+ * parse_header now returns {ok, any(), Req} instead of {any(), Req}
+ * body_qs now returns {ok, QsVals, Req} instead of {QsVals, Req}
+ * multipart_data now returns {headers, Headers, Req} instead of
+ {{headers, Headers}, Req} and {body, Body, Req} instead of
+ {{body, Body}, Req}
+ * set_resp_* functions now return Req instead of {ok, Req}
-* Rename or drop many cowboy_req functions
+ * Fix consistency issues caused by erlang:decode_packet/3
+ * The method is now always a case sensitive binary string
+ * Note that standard method names are uppercase (e.g. <<"GET">>)
+ * Header names are now always lowercase binary string
- * Replace cowboy_req:host/1 with cowboy_req:raw_host/1.
- * Replace cowboy_req:path/1 with cowboy_req:raw_path/1.
- * cowboy_req:raw_qs/1 becomes cowboy_req:qs/1.
+ * The max_line_length cowboy_protocol option was replaced by 3 new options:
+ * max_request_line_length, defaults to 4096 bytes
+ * max_header_name_length, defaults to 64 bytes
+ * max_header_value_length, defaults to 4096 bytes
-* Change the signature of many cowboy_req functions
+ * Add max_headers option, limiting the number of headers; defaults to 100
- * parse_header now returns {ok, any(), Req} instead of {any(), Req}.
- * body_qs now returns {ok, QsVals, Req} instead of {QsVals, Req}.
- * multipart_data now returns {headers, Headers, Req} instead of
- {{headers, Headers}, Req} and {body, Body, Req} instead of
- {{body, Body}, Req}.
- * set_resp_* functions now return Req instead of {ok, Req}.
+ * Enhance the websocket API
+ * Change a websocket error from {error, protocol} to {error, badframe}
+ * Allow websocket handlers to reply more than one frame
+ * Check for errors when calling Transport:send/2 to avoid crashes
+ * Add close, {close, Payload}, ping, pong frame types for replies
-* Fix consistency issues caused by erlang:decode_packet/3
+ * Use -callback in behaviours
- * The method is now always a case sensitive binary string.
- * Note that standard method names are uppercase (e.g. <<"GET">>).
- * Header names are now always lowercase binary string.
+ * Add cowboy_protocol:onrequest_fun/0 and :onresponse_fun/0 types
-* The max_line_length cowboy_protocol option was replaced by 3 new options:
+ * Add the body data to onresponse_fun/0 callback
- * max_request_line_length, defaults to 4096 bytes
- * max_header_name_length, defaults to 64 bytes
- * max_header_value_length, defaults to 4096 bytes
+ * Remove the urldecode cowboy_protocol option
-* Add max_headers option, limiting the number of headers; defaults to 100
+ * Isolate multipart from body reading to fix an issue
-* Use -callback in behaviours
+ * Avoid a duplicate HTTP reply in cowboy_websocket:upgrade_error/1
-* Add cowboy_protocol:onrequest_fun/0 and :onresponse_fun/0 types
+ * Fix use of the Vary header, was named Variances in the previous code
-* Add the body data to onresponse_fun/0 callback
+ * Improve returned status code for HTTP and REST
-* Remove the urldecode cowboy_protocol option
+ * Fix charsets_provided return value
-* Isolate multipart from body reading to fix an issue
+ * Allow passing {M, F} for the mimetype function to cowboy_static
-* Change a websocket error from {error, protocol} to {error, badframe}
+ * Can now upgrade protocols with {upgrade, protocol, P, Req, Opts}
-* Avoid a duplicate HTTP reply in cowboy_websocket:upgrade_error/1
+ * Cowboy now only expects universal time, never local time
-* Many, many optimizations for the most critical code path
+ * Many, many optimizations for the most critical code path
0.6.1
-----
-* Add hello_world, rest_hello_world, chunked_hello_world,
+ * Add hello_world, rest_hello_world, chunked_hello_world,
echo_get, echo_post and static examples.
-* Add support for the "Expect: 100-continue" header.
+ * Add support for the "Expect: 100-continue" header.
-* Keep the original 'Host' header value instead of modifying it.
+ * Keep the original 'Host' header value instead of modifying it.
-* Fix use of parsed headers cache.
+ * Fix use of parsed headers cache.
-* REST: fix the matching of charsets.
+ * REST: fix the matching of charsets.
-* REST: allow <<"type/subtype">> format for content_types_accepted.
+ * REST: allow <<"type/subtype">> format for content_types_accepted.
-* Improve typespecs.
+ * Improve typespecs.
0.6.0
-----
-* Add multipart support
+ * Add multipart support
-* Add chunked transfer decoding support
+ * Add chunked transfer decoding support
Done by reworking the body reading API. Now all the body
reading goes through the cowboy_http_req:stream_body/1
@@ -115,14 +129,14 @@ next
Transfer-Encoding and the Content-Encoding, returning
properly decoded data ready for consumption.
-* Add fragmented websocket messages support
+ * Add fragmented websocket messages support
Properly tested by the addition of the Autobahn websocket
test suite to our toolbox. All tests pass except a few
related to UTF-8 handling, as Cowboy does no checks on that
end at this point.
-* Add 'onrequest' and 'onresponse' hooks
+ * Add 'onrequest' and 'onresponse' hooks
The first can be used for all the special cases you may have
that can't be dealt with otherwise. It's also pretty good for
@@ -131,76 +145,76 @@ next
The second can be used for logging errors or replacing error
pages, amongst others.
-* Add cowboy:get_protocol_options/1 and cowboy:set_protocol_options/2
+ * Add cowboy:get_protocol_options/1 and cowboy:set_protocol_options/2
These functions allow for retrieving a listener's protocol options,
and for modifying them while the listener is running. This is
most useful to upgrade the dispatch list. The upgrade applies
to all the future connections.
-* Add the sockname/1 function to TCP and SSL transports
+ * Add the sockname/1 function to TCP and SSL transports
-* Improve SSL transport support
+ * Improve SSL transport support
Add support for specifying the ciphers. Add CA support. Make
specifying the password optional.
-* Add new HTTP status codes from RFC 6585
+ * Add new HTTP status codes from RFC 6585
-* Add a 'file' option to cowboy_http_static
+ * Add a 'file' option to cowboy_http_static
This allows for mapping /folder/ paths to a /folder/index.html file.
-* Add the '*' catch all Content-Type for REST
+ * Add the '*' catch all Content-Type for REST
-* Add {halt, Req, State} as a possible return value for REST
+ * Add {halt, Req, State} as a possible return value for REST
-* Add absolute URI support for requests
+ * Add absolute URI support for requests
-* Add cowboy_http:x_www_form_urlencoded/2
+ * Add cowboy_http:x_www_form_urlencoded/2
-* Various REST bug fixes
+ * Various REST bug fixes
-* Do not send chunked replies for HTTP/1.0 connections
+ * Do not send chunked replies for HTTP/1.0 connections
-* Fix a DST bug in the cookies code
+ * Fix a DST bug in the cookies code
-* Fix a bug with setting cookie values containing slashes
+ * Fix a bug with setting cookie values containing slashes
-* Fix a small timer leak when using loop/websocket timeouts
+ * Fix a small timer leak when using loop/websocket timeouts
-* Make charset and media type parsing more relaxed
+ * Make charset and media type parsing more relaxed
This is to accomodate some widely used broken clients.
-* Make error messages more readable
+ * Make error messages more readable
-* Fix and improve type specifications
+ * Fix and improve type specifications
-* Fix a bug preventing documentation from being generated
+ * Fix a bug preventing documentation from being generated
-* Small improvements to the documentation
+ * Small improvements to the documentation
-* Rework the HTTP test suite
+ * Rework the HTTP test suite
The suite now uses an integrated Cowboy HTTP client. The client
is currently experimental and shouldn't be used.
-* Add many many tests.
+ * Add many many tests.
0.4.0
-----
-* Set the cowboy_listener process priority to high
+ * Set the cowboy_listener process priority to high
As it is the central process used by all incoming requests
we need to set its priority to high to avoid timeouts that
would happen otherwise when reaching a huge number of
concurrent requests.
-* Add cowboy:child_spec/6 for embedding in other applications
+ * Add cowboy:child_spec/6 for embedding in other applications
-* Add cowboy_http_rest, an experimental REST protocol support
+ * Add cowboy_http_rest, an experimental REST protocol support
Based on the Webmachine diagram and documentation. It is a
new implementation, not a port, therefore a few changes have
@@ -211,7 +225,7 @@ next
resource documentation and the comments found in cowboy_http_rest,
which itself should be fairly easy to read and understand.
-* Add cowboy_http_static, an experimental static file handler
+ * Add cowboy_http_static, an experimental static file handler
Makes use of the aforementioned REST protocol support to
deliver files with proper content type and cache headers.
@@ -220,22 +234,22 @@ next
appropriate, which currently requires the VM to be started
with the +A option defined, else errors may randomly appear.
-* Add cowboy_bstr module for binary strings related functions
+ * Add cowboy_bstr module for binary strings related functions
-* Add cowboy_http module for HTTP parsing functions
+ * Add cowboy_http module for HTTP parsing functions
This module so far contains various functions for HTTP header
parsing along with URL encoding and decoding.
-* Remove quoted from the default dependencies
+ * Remove quoted from the default dependencies
This should make Cowboy much easier to compile and use by default.
It is of course still possible to use quoted as your URL decoding
library in Cowboy thanks to the newly added urldecode option.
-* Fix supervisor spec for non dynamic modules to allow upgrades to complete
+ * Fix supervisor spec for non dynamic modules to allow upgrades to complete
-* Add cowboy:accept_ack/1 for a cleaner handling of the shoot message
+ * Add cowboy:accept_ack/1 for a cleaner handling of the shoot message
Before, when the listener accepted a connection, the newly created
process was waiting for a message containing the atom 'shoot' before
@@ -245,81 +259,81 @@ next
contents of the message have changed (and could change again in the
distant future).
-* Update binary parsing expressions to avoid hype crashes
+ * Update binary parsing expressions to avoid hype crashes
More specifically, /bits was replaced by /binary.
-* Rename the type cowboy_dispatcher:path_tokens/0 to tokens/0
+ * Rename the type cowboy_dispatcher:path_tokens/0 to tokens/0
-* Remove the cowboy_clock:date/0, time/0 and datetime/0 types
+ * Remove the cowboy_clock:date/0, time/0 and datetime/0 types
The calendar module exports those same types properly since R14B04.
-* Add cacertfile configuration option to cowboy_ssl_transport
+ * Add cacertfile configuration option to cowboy_ssl_transport
-* Add cowboy_protocol behaviour
+ * Add cowboy_protocol behaviour
-* Remove -Wbehaviours dialyzer option unavailable in R15B
+ * Remove -Wbehaviours dialyzer option unavailable in R15B
-* Many tests and specs improvements
+ * Many tests and specs improvements
### cowboy_http_req
-* Fix a crash when reading the request body
+ * Fix a crash when reading the request body
-* Add parse_header/2 and parse_header/3
+ * Add parse_header/2 and parse_header/3
The following headers can now be semantically parsed: Connection, Accept,
Accept-Charset, Accept-Encoding, Accept-Language, Content-Length,
Content-Type, If-Match, If-None-Match, If-Modified-Since,
If-Unmodified-Since, Upgrade
-* Add set_resp_header/3, set_resp_cookie/4 and set_resp_body/2
+ * Add set_resp_header/3, set_resp_cookie/4 and set_resp_body/2
These functions allow handlers to set response headers and body
without having to reply directly.
-* Add set_resp_body_fun/3
+ * Add set_resp_body_fun/3
This function allows handlers to stream the body of the response
using the given fun. The size of the response must be known beforehand.
-* Add transport/1 to obtain the transport and socket for the request
+ * Add transport/1 to obtain the transport and socket for the request
This allows handlers to have low-level socket access in those cases
where they do need it, like when streaming a response body with
set_resp_body_fun/3.
-* Add peer_addr/1
+ * Add peer_addr/1
This function tries to guess the real peer IP based on the HTTP
headers received.
-* Add meta/2 and meta/3 to save useful protocol information
+ * Add meta/2 and meta/3 to save useful protocol information
Currently used to save the Websocket protocol version currently used,
and to save request information in the REST protocol handler.
-* Add reply/2 and reply/3 aliases to reply/4
+ * Add reply/2 and reply/3 aliases to reply/4
-* Add upgrade_reply/3 for protocol upgrades
+ * Add upgrade_reply/3 for protocol upgrades
### cowboy_http_protocol
-* Add the {urldecode, fun urldecode/2} option
+ * Add the {urldecode, fun urldecode/2} option
Added when quoted was removed from the default build. Can be used to
tell Cowboy to use quoted or any other URL decoding routine.
-* Add the max_keepalive option
+ * Add the max_keepalive option
-* Add the max_line_length option
+ * Add the max_line_length option
-* Allow HTTP handlers to stop during init/3
+ * Allow HTTP handlers to stop during init/3
To do so they can return {shutdown, Req, State}.
-* Add loops support in HTTP handlers for proper long-polling support
+ * Add loops support in HTTP handlers for proper long-polling support
A loop can be entered by returning either of {loop, Req, State},
{loop, Req, State, hibernate}, {loop, Req, State, Timeout} or
@@ -341,60 +355,60 @@ next
Like in OTP, you do need to set timeout and hibernate again when
returning from info/3 to enable them until the next call.
-* Fix the sending of 500 errors when handlers crash
+ * Fix the sending of 500 errors when handlers crash
Now we send an error response when no response has been sent,
and do nothing more than close the connection if anything
did get sent.
-* Fix a crash when the server is sent HTTP responses
+ * Fix a crash when the server is sent HTTP responses
-* Fix HTTP timeouts handling when the Request-Line wasn't received
+ * Fix HTTP timeouts handling when the Request-Line wasn't received
-* Fix the handling of the max number of empty lines between requests
+ * Fix the handling of the max number of empty lines between requests
-* Fix the handling of HEAD requests
+ * Fix the handling of HEAD requests
-* Fix HTTP/1.0 Host header handling
+ * Fix HTTP/1.0 Host header handling
-* Reply status 400 if we receive an unexpected value or error for headers
+ * Reply status 400 if we receive an unexpected value or error for headers
-* Properly close when the application sends "Connection: close" header
+ * Properly close when the application sends "Connection: close" header
-* Close HTTP connections on all errors
+ * Close HTTP connections on all errors
-* Improve the error message for HTTP handlers
+ * Improve the error message for HTTP handlers
### cowboy_http_websocket
-* Add websocket support for all versions up to RFC 6455
+ * Add websocket support for all versions up to RFC 6455
Support isn't perfect yet according to the specifications, but
is working against all currently known client implementations.
-* Allow websocket_init/3 to return with the hibernate option set
+ * Allow websocket_init/3 to return with the hibernate option set
-* Add {shutdown, Req} return value to websocket_init/3 to fail an upgrade
+ * Add {shutdown, Req} return value to websocket_init/3 to fail an upgrade
-* Fix websocket timeout handling
+ * Fix websocket timeout handling
-* Fix error messages: wrong callback name was reported on error
+ * Fix error messages: wrong callback name was reported on error
-* Fix byte-by-byte websocket handling
+ * Fix byte-by-byte websocket handling
-* Fix an issue when using hixie-76 with certain proxies
+ * Fix an issue when using hixie-76 with certain proxies
-* Fix a crash in the hixie-76 handshake
+ * Fix a crash in the hixie-76 handshake
-* Fix the handshake when SSL is used on port 443
+ * Fix the handshake when SSL is used on port 443
-* Fix a crash in the handshake when cowboy_http_req:compact/1 is used
+ * Fix a crash in the handshake when cowboy_http_req:compact/1 is used
-* Fix handshake when a query string is present
+ * Fix handshake when a query string is present
-* Fix a crash when the Upgrade header contains more than one token
+ * Fix a crash when the Upgrade header contains more than one token
0.2.0
-----
-* Initial release.
+ * Initial release.
diff --git a/ROADMAP.md b/ROADMAP.md
index a409af0..7dc19af 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -6,7 +6,7 @@ list of planned changes and work to be done on the Cowboy
server. It is non-exhaustive and subject to change. Items
are not ordered.
-* Write more, better examples.
+ * Write more, better examples.
The first step would be to port misultin's examples
to Cowboy. Then these examples could be completed with
@@ -20,12 +20,12 @@ are not ordered.
Examples should be commented. They may or may not be
used for writing the user guides.
-* Write user guides.
+ * Write user guides.
We currently have good API documentation, but no step
by step user guides.
-* Write more, better tests.
+ * Write more, better tests.
Amongst the areas less tested there is protocol upgrades
and the REST handler.
@@ -37,7 +37,7 @@ are not ordered.
While eunit and ct tests are fine, some parts of the
code could benefit from PropEr tests.
-* Continuous performance testing.
+ * Continuous performance testing.
Initially dubbed the Horse project, Cowboy could benefit
from a continuous performance testing tool that would
@@ -49,37 +49,37 @@ are not ordered.
Cowboy to other servers and eventually take ideas from
the servers that outperform Cowboy for the task being tested.
-* Improve HTTP/1.0 support.
+ * Improve HTTP/1.0 support.
Most of the work on Cowboy has been done with HTTP/1.1
in mind. But there is still a need for HTTP/1.0 code in
Cowboy. The server code should be reviewed and tested
to ensure compatibility with remaining HTTP/1.0 products.
-* Complete the work on Websockets.
+ * Complete the work on Websockets.
Now that the Autobahn test suite is available (make inttests),
we have a definite way to know whether Cowboy's implementation
of Websockets is right. The work can thus be completed. The
remaining task is proper UTF8 handling.
-* SPDY support.
+ * SPDY support.
While SPDY probably won't be added directly to Cowboy, work
has been started on making Cowboy use SPDY.
-* Transport upgrades.
+ * Transport upgrades.
Some protocols allow an upgrade from TCP to SSL without
closing the connection. This is currently not possible
through the Cowboy API.
-* Resizing the acceptor pool.
+ * Resizing the acceptor pool.
We should be able to add more acceptors to a pool but also
to remove some of them as needed.
-* Simplified dispatch list.
+ * Simplified dispatch list.
For convenience purposes, the dispatch list should allow
lists instead of binaries. The lists can be converted to
@@ -88,7 +88,7 @@ are not ordered.
There has also been discussion on allowing the dispatch
list to be hierarchical.
-* Add Transport:secure/0.
+ * Add Transport:secure/0.
Currently Cowboy checks if a connection is secure by
checking if its name is 'ssl'. This isn't a very modular
diff --git a/examples/echo_get/src/toppage_handler.erl b/examples/echo_get/src/toppage_handler.erl
index 6d914ec..86433cb 100644
--- a/examples/echo_get/src/toppage_handler.erl
+++ b/examples/echo_get/src/toppage_handler.erl
@@ -20,7 +20,7 @@ echo(<<"GET">>, undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo(<<"GET">>, Echo, Req) ->
cowboy_req:reply(200,
- [{<<"Content-Encoding">>, <<"utf-8">>}], Echo, Req);
+ [{<<"content-encoding">>, <<"utf-8">>}], Echo, Req);
echo(_, _, Req) ->
%% Method not allowed.
cowboy_req:reply(405, Req).
diff --git a/examples/echo_post/src/toppage_handler.erl b/examples/echo_post/src/toppage_handler.erl
index 69aeb9f..808ba8e 100644
--- a/examples/echo_post/src/toppage_handler.erl
+++ b/examples/echo_post/src/toppage_handler.erl
@@ -30,7 +30,7 @@ echo(undefined, Req) ->
cowboy_req:reply(400, [], <<"Missing echo parameter.">>, Req);
echo(Echo, Req) ->
cowboy_req:reply(200,
- [{<<"Content-Encoding">>, <<"utf-8">>}], Echo, Req).
+ [{<<"content-encoding">>, <<"utf-8">>}], Echo, Req).
terminate(_Req, _State) ->
ok.
diff --git a/src/cowboy_clock.erl b/src/cowboy_clock.erl
index f851211..b439bb1 100644
--- a/src/cowboy_clock.erl
+++ b/src/cowboy_clock.erl
@@ -76,39 +76,12 @@ rfc1123(DateTime) ->
%% This format is used in the <em>set-cookie</em> header sent with
%% HTTP responses.
-spec rfc2109(calendar:datetime()) -> binary().
-rfc2109(LocalTime) ->
- {{YYYY,MM,DD},{Hour,Min,Sec}} =
- case calendar:local_time_to_universal_time_dst(LocalTime) of
- [Gmt] -> Gmt;
- [_,Gmt] -> Gmt;
- [] ->
- %% The localtime generated by cowboy_cookies may fall within
- %% the hour that is skipped by daylight savings time. If this
- %% is such a localtime, increment the localtime with one hour
- %% and try again, if this succeeds, subtracting the max_age
- %% from the resulting universaltime and converting to a local
- %% time will yield the original localtime.
- {Date, {Hour1, Min1, Sec1}} = LocalTime,
- LocalTime2 = {Date, {Hour1 + 1, Min1, Sec1}},
- case calendar:local_time_to_universal_time_dst(LocalTime2) of
- [Gmt] -> Gmt;
- [_,Gmt] -> Gmt
- end
- end,
- Wday = calendar:day_of_the_week({YYYY,MM,DD}),
- DayBin = pad_int(DD),
- YearBin = list_to_binary(integer_to_list(YYYY)),
- HourBin = pad_int(Hour),
- MinBin = pad_int(Min),
- SecBin = pad_int(Sec),
- WeekDay = weekday(Wday),
- Month = month(MM),
- <<WeekDay/binary, ", ",
- DayBin/binary, " ", Month/binary, " ",
- YearBin/binary, " ",
- HourBin/binary, ":",
- MinBin/binary, ":",
- SecBin/binary, " GMT">>.
+rfc2109({Date = {Y, Mo, D}, {H, Mi, S}}) ->
+ Wday = calendar:day_of_the_week(Date),
+ << (weekday(Wday))/binary, ", ", (pad_int(D))/binary, "-",
+ (month(Mo))/binary, "-", (list_to_binary(integer_to_list(Y)))/binary,
+ " ", (pad_int(H))/binary, $:, (pad_int(Mi))/binary,
+ $:, (pad_int(S))/binary, " GMT" >>.
%% gen_server.
@@ -219,6 +192,13 @@ month(12) -> <<"Dec">>.
-ifdef(TEST).
+rfc2109_test_() ->
+ Tests = [
+ {<<"Sat, 14-May-2011 14:25:33 GMT">>, {{2011, 5, 14}, {14, 25, 33}}},
+ {<<"Sun, 01-Jan-2012 00:00:00 GMT">>, {{2012, 1, 1}, { 0, 0, 0}}}
+ ],
+ [{R, fun() -> R = rfc2109(D) end} || {R, D} <- Tests].
+
update_rfc1123_test_() ->
Tests = [
{<<"Sat, 14 May 2011 14:25:33 GMT">>, undefined,
diff --git a/src/cowboy_cookies.erl b/src/cowboy_cookies.erl
deleted file mode 100644
index d10c848..0000000
--- a/src/cowboy_cookies.erl
+++ /dev/null
@@ -1,416 +0,0 @@
-%% Copyright 2007 Mochi Media, Inc.
-%% Copyright 2011 Thomas Burdick <[email protected]>
-%%
-%% Permission to use, copy, modify, and/or distribute this software for any
-%% purpose with or without fee is hereby granted, provided that the above
-%% copyright notice and this permission notice appear in all copies.
-%%
-%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-%% @doc HTTP Cookie parsing and generating (RFC 2965).
-
--module(cowboy_cookies).
-
-%% API.
--export([parse_cookie/1]).
--export([cookie/3]).
--export([cookie/2]).
-
-%% Types.
--type kv() :: {Name::binary(), Value::binary()}.
--type kvlist() :: [kv()].
--type cookie_option() :: {max_age, integer()}
- | {local_time, calendar:datetime()}
- | {domain, binary()} | {path, binary()}
- | {secure, true | false} | {http_only, true | false}.
-
--export_type([kv/0]).
--export_type([kvlist/0]).
--export_type([cookie_option/0]).
-
--define(QUOTE, $\").
-
--ifdef(TEST).
--include_lib("eunit/include/eunit.hrl").
--endif.
-
-%% API.
-
-%% @doc Parse the contents of a Cookie header field, ignoring cookie
-%% attributes, and return a simple property list.
--spec parse_cookie(binary()) -> kvlist().
-parse_cookie(<<>>) ->
- [];
-parse_cookie(Cookie) when is_binary(Cookie) ->
- parse_cookie(Cookie, []).
-
-%% @equiv cookie(Key, Value, [])
--spec cookie(binary(), binary()) -> kv().
-cookie(Key, Value) when is_binary(Key) andalso is_binary(Value) ->
- cookie(Key, Value, []).
-
-%% @doc Generate a Set-Cookie header field tuple.
--spec cookie(binary(), binary(), [cookie_option()]) -> kv().
-cookie(Key, Value, Options) when is_binary(Key)
- andalso is_binary(Value) andalso is_list(Options) ->
- Cookie = <<(any_to_binary(Key))/binary, "=",
- (quote(Value))/binary, "; Version=1">>,
- %% Set-Cookie:
- %% Comment, Domain, Max-Age, Path, Secure, Version
- ExpiresPart =
- case proplists:get_value(max_age, Options) of
- undefined ->
- <<"">>;
- RawAge ->
- When = case proplists:get_value(local_time, Options) of
- undefined ->
- calendar:local_time();
- LocalTime ->
- LocalTime
- end,
- Age = case RawAge < 0 of
- true ->
- 0;
- false ->
- RawAge
- end,
- AgeBinary = quote(Age),
- CookieDate = age_to_cookie_date(Age, When),
- <<"; Expires=", CookieDate/binary,
- "; Max-Age=", AgeBinary/binary>>
- end,
- SecurePart =
- case proplists:get_value(secure, Options) of
- true ->
- <<"; Secure">>;
- _ ->
- <<"">>
- end,
- DomainPart =
- case proplists:get_value(domain, Options) of
- undefined ->
- <<"">>;
- Domain ->
- <<"; Domain=", (quote(Domain))/binary>>
- end,
- PathPart =
- case proplists:get_value(path, Options) of
- undefined ->
- <<"">>;
- Path ->
- <<"; Path=", (quote(Path, true))/binary>>
- end,
- HttpOnlyPart =
- case proplists:get_value(http_only, Options) of
- true ->
- <<"; HttpOnly">>;
- _ ->
- <<"">>
- end,
- CookieParts = <<Cookie/binary, ExpiresPart/binary, SecurePart/binary,
- DomainPart/binary, PathPart/binary, HttpOnlyPart/binary>>,
- {<<"Set-Cookie">>, CookieParts}.
-
-%% Internal.
-
-%% @doc Check if a character is a white space character.
--spec is_whitespace(char()) -> boolean().
-is_whitespace($\s) -> true;
-is_whitespace($\t) -> true;
-is_whitespace($\r) -> true;
-is_whitespace($\n) -> true;
-is_whitespace(_) -> false.
-
-%% @doc Check if a character is a separator.
--spec is_separator(char()) -> boolean().
-is_separator(C) when C < 32 -> true;
-is_separator($\s) -> true;
-is_separator($\t) -> true;
-is_separator($() -> true;
-is_separator($)) -> true;
-is_separator($<) -> true;
-is_separator($>) -> true;
-is_separator($@) -> true;
-is_separator($,) -> true;
-is_separator($;) -> true;
-is_separator($:) -> true;
-is_separator($\\) -> true;
-is_separator(?QUOTE) -> true;
-is_separator($/) -> true;
-is_separator($[) -> true;
-is_separator($]) -> true;
-is_separator($?) -> true;
-is_separator($=) -> true;
-is_separator(${) -> true;
-is_separator($}) -> true;
-is_separator(_) -> false.
-
-%% @doc Check if a binary has an ASCII separator character.
--spec has_separator(binary(), boolean()) -> boolean().
-has_separator(<<>>, _) ->
- false;
-has_separator(<<$/, Rest/binary>>, true) ->
- has_separator(Rest, true);
-has_separator(<<C, Rest/binary>>, IgnoreSlash) ->
- case is_separator(C) of
- true ->
- true;
- false ->
- has_separator(Rest, IgnoreSlash)
- end.
-
-%% @doc Convert to a binary and raise an error if quoting is required. Quoting
-%% is broken in different ways for different browsers. Its better to simply
-%% avoiding doing it at all.
-%% @end
--spec quote(term(), boolean()) -> binary().
-quote(V0, IgnoreSlash) ->
- V = any_to_binary(V0),
- case has_separator(V, IgnoreSlash) of
- true ->
- erlang:error({cookie_quoting_required, V});
- false ->
- V
- end.
-
-%% @equiv quote(Bin, false)
--spec quote(term()) -> binary().
-quote(V0) ->
- quote(V0, false).
-
--spec add_seconds(integer(), calendar:datetime()) -> calendar:datetime().
-add_seconds(Secs, LocalTime) ->
- Greg = calendar:datetime_to_gregorian_seconds(LocalTime),
- calendar:gregorian_seconds_to_datetime(Greg + Secs).
-
--spec age_to_cookie_date(integer(), calendar:datetime()) -> binary().
-age_to_cookie_date(Age, LocalTime) ->
- cowboy_clock:rfc2109(add_seconds(Age, LocalTime)).
-
--spec parse_cookie(binary(), kvlist()) -> kvlist().
-parse_cookie(<<>>, Acc) ->
- lists:reverse(Acc);
-parse_cookie(String, Acc) ->
- {{Token, Value}, Rest} = read_pair(String),
- Acc1 = case Token of
- <<"">> ->
- Acc;
- <<"$", _R/binary>> ->
- Acc;
- _ ->
- [{Token, Value} | Acc]
- end,
- parse_cookie(Rest, Acc1).
-
--spec read_pair(binary()) -> {{binary(), binary()}, binary()}.
-read_pair(String) ->
- {Token, Rest} = read_token(skip_whitespace(String)),
- {Value, Rest1} = read_value(skip_whitespace(Rest)),
- {{Token, Value}, skip_past_separator(Rest1)}.
-
--spec read_value(binary()) -> {binary(), binary()}.
-read_value(<<"=", Value/binary>>) ->
- Value1 = skip_whitespace(Value),
- case Value1 of
- <<?QUOTE, _R/binary>> ->
- read_quoted(Value1);
- _ ->
- read_token(Value1)
- end;
-read_value(String) ->
- {<<"">>, String}.
-
--spec read_quoted(binary()) -> {binary(), binary()}.
-read_quoted(<<?QUOTE, String/binary>>) ->
- read_quoted(String, <<"">>).
-
--spec read_quoted(binary(), binary()) -> {binary(), binary()}.
-read_quoted(<<"">>, Acc) ->
- {Acc, <<"">>};
-read_quoted(<<?QUOTE, Rest/binary>>, Acc) ->
- {Acc, Rest};
-read_quoted(<<$\\, Any, Rest/binary>>, Acc) ->
- read_quoted(Rest, <<Acc/binary, Any>>);
-read_quoted(<<C, Rest/binary>>, Acc) ->
- read_quoted(Rest, <<Acc/binary, C>>).
-
-%% @doc Drop characters while a function returns true.
--spec binary_dropwhile(fun((char()) -> boolean()), binary()) -> binary().
-binary_dropwhile(_F, <<"">>) ->
- <<"">>;
-binary_dropwhile(F, String) ->
- <<C, Rest/binary>> = String,
- case F(C) of
- true ->
- binary_dropwhile(F, Rest);
- false ->
- String
- end.
-
-%% @doc Remove leading whitespace.
--spec skip_whitespace(binary()) -> binary().
-skip_whitespace(String) ->
- binary_dropwhile(fun is_whitespace/1, String).
-
-%% @doc Split a binary when the current character causes F to return true.
--spec binary_splitwith(fun((char()) -> boolean()), binary(), binary())
- -> {binary(), binary()}.
-binary_splitwith(_F, Head, <<>>) ->
- {Head, <<>>};
-binary_splitwith(F, Head, Tail) ->
- <<C, NTail/binary>> = Tail,
- case F(C) of
- true ->
- {Head, Tail};
- false ->
- binary_splitwith(F, <<Head/binary, C>>, NTail)
- end.
-
-%% @doc Split a binary with a function returning true or false on each char.
--spec binary_splitwith(fun((char()) -> boolean()), binary())
- -> {binary(), binary()}.
-binary_splitwith(F, String) ->
- binary_splitwith(F, <<>>, String).
-
-%% @doc Split the binary when the next separator is found.
--spec read_token(binary()) -> {binary(), binary()}.
-read_token(String) ->
- binary_splitwith(fun is_separator/1, String).
-
-%% @doc Return string after ; or , characters.
--spec skip_past_separator(binary()) -> binary().
-skip_past_separator(<<"">>) ->
- <<"">>;
-skip_past_separator(<<";", Rest/binary>>) ->
- Rest;
-skip_past_separator(<<",", Rest/binary>>) ->
- Rest;
-skip_past_separator(<<_C, Rest/binary>>) ->
- skip_past_separator(Rest).
-
--spec any_to_binary(binary() | string() | atom() | integer()) -> binary().
-any_to_binary(V) when is_binary(V) ->
- V;
-any_to_binary(V) when is_list(V) ->
- erlang:list_to_binary(V);
-any_to_binary(V) when is_atom(V) ->
- erlang:atom_to_binary(V, latin1);
-any_to_binary(V) when is_integer(V) ->
- list_to_binary(integer_to_list(V)).
-
-%% Tests.
-
--ifdef(TEST).
-
-quote_test() ->
- %% ?assertError eunit macro is not compatible with coverage module
- _ = try quote(<<":wq">>)
- catch error:{cookie_quoting_required, <<":wq">>} -> ok
- end,
- ?assertEqual(<<"foo">>,quote(foo)),
- _ = try quote(<<"/test/slashes/">>)
- catch error:{cookie_quoting_required, <<"/test/slashes/">>} -> ok
- end,
- ok.
-
-parse_cookie_test() ->
- %% RFC example
- C1 = <<"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\";
- Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\";
- Shipping=\"FedEx\"; $Path=\"/acme\"">>,
- ?assertEqual(
- [{<<"Customer">>,<<"WILE_E_COYOTE">>},
- {<<"Part_Number">>,<<"Rocket_Launcher_0001">>},
- {<<"Shipping">>,<<"FedEx">>}],
- parse_cookie(C1)),
- %% Potential edge cases
- ?assertEqual(
- [{<<"foo">>, <<"x">>}],
- parse_cookie(<<"foo=\"\\x\"">>)),
- ?assertEqual(
- [],
- parse_cookie(<<"=">>)),
- ?assertEqual(
- [{<<"foo">>, <<"">>}, {<<"bar">>, <<"">>}],
- parse_cookie(<<" foo ; bar ">>)),
- ?assertEqual(
- [{<<"foo">>, <<"">>}, {<<"bar">>, <<"">>}],
- parse_cookie(<<"foo=;bar=">>)),
- ?assertEqual(
- [{<<"foo">>, <<"\";">>}, {<<"bar">>, <<"">>}],
- parse_cookie(<<"foo = \"\\\";\";bar ">>)),
- ?assertEqual(
- [{<<"foo">>, <<"\";bar">>}],
- parse_cookie(<<"foo=\"\\\";bar">>)),
- ?assertEqual(
- [],
- parse_cookie(<<"">>)),
- ?assertEqual(
- [{<<"foo">>, <<"bar">>}, {<<"baz">>, <<"wibble">>}],
- parse_cookie(<<"foo=bar , baz=wibble ">>)),
- ok.
-
-domain_test() ->
- ?assertEqual(
- {<<"Set-Cookie">>,
- <<"Customer=WILE_E_COYOTE; "
- "Version=1; "
- "Domain=acme.com; "
- "HttpOnly">>},
- cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
- [{http_only, true}, {domain, <<"acme.com">>}])),
- ok.
-
-local_time_test() ->
- {<<"Set-Cookie">>, B} = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
- [{max_age, 111}, {secure, true}]),
-
- ?assertMatch(
- [<<"Customer=WILE_E_COYOTE">>,
- <<" Version=1">>,
- <<" Expires=", _R/binary>>,
- <<" Max-Age=111">>,
- <<" Secure">>],
- binary:split(B, <<";">>, [global])),
- ok.
-
--spec cookie_test() -> no_return(). %% Not actually true, just a bad option.
-cookie_test() ->
- C1 = {<<"Set-Cookie">>,
- <<"Customer=WILE_E_COYOTE; "
- "Version=1; "
- "Path=/acme">>},
- C1 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>, [{path, <<"/acme">>}]),
-
- C1 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
- [{path, <<"/acme">>}, {badoption, <<"negatory">>}]),
-
- {<<"Set-Cookie">>,<<"=NoKey; Version=1">>}
- = cookie(<<"">>, <<"NoKey">>, []),
- {<<"Set-Cookie">>,<<"=NoKey; Version=1">>}
- = cookie(<<"">>, <<"NoKey">>),
- LocalTime = calendar:universal_time_to_local_time(
- {{2007, 5, 15}, {13, 45, 33}}),
- C2 = {<<"Set-Cookie">>,
- <<"Customer=WILE_E_COYOTE; "
- "Version=1; "
- "Expires=Tue, 15 May 2007 13:45:33 GMT; "
- "Max-Age=0">>},
- C2 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
- [{max_age, -111}, {local_time, LocalTime}]),
- C3 = {<<"Set-Cookie">>,
- <<"Customer=WILE_E_COYOTE; "
- "Version=1; "
- "Expires=Wed, 16 May 2007 13:45:50 GMT; "
- "Max-Age=86417">>},
- C3 = cookie(<<"Customer">>, <<"WILE_E_COYOTE">>,
- [{max_age, 86417}, {local_time, LocalTime}]),
- ok.
-
--endif.
diff --git a/src/cowboy_http.erl b/src/cowboy_http.erl
index e0b1632..fb9f21c 100644
--- a/src/cowboy_http.erl
+++ b/src/cowboy_http.erl
@@ -19,6 +19,7 @@
%% Parsing.
-export([list/2]).
-export([nonempty_list/2]).
+-export([cookie_list/1]).
-export([content_type/1]).
-export([media_range/2]).
-export([conneg/2]).
@@ -42,6 +43,7 @@
-export([ce_identity/1]).
%% Interpretation.
+-export([cookie_to_iodata/3]).
-export([version_to_binary/1]).
-export([urldecode/1]).
-export([urldecode/2]).
@@ -100,6 +102,33 @@ list(Data, Fun, Acc) ->
end)
end).
+%% @doc Parse a list of cookies.
+%%
+%% We need a special function for this because we need to support both
+%% $; and $, as separators as per RFC2109.
+-spec cookie_list(binary()) -> [{binary(), binary()}] | {error, badarg}.
+cookie_list(Data) ->
+ case cookie_list(Data, []) of
+ {error, badarg} -> {error, badarg};
+ [] -> {error, badarg};
+ L -> lists:reverse(L)
+ end.
+
+-spec cookie_list(binary(), Acc) -> Acc | {error, badarg}
+ when Acc::[{binary(), binary()}].
+cookie_list(Data, Acc) ->
+ whitespace(Data,
+ fun (<<>>) -> Acc;
+ (<< $,, Rest/binary >>) -> cookie_list(Rest, Acc);
+ (<< $;, Rest/binary >>) -> cookie_list(Rest, Acc);
+ (Rest) -> param(Rest,
+ fun (Rest2, << $$, _/bits >>, _) ->
+ cookie_list(Rest2, Acc);
+ (Rest2, Name, Value) ->
+ cookie_list(Rest2, [{Name, Value}|Acc])
+ end)
+ end).
+
%% @doc Parse a content type.
-spec content_type(binary()) -> any().
content_type(Data) ->
@@ -341,12 +370,17 @@ params(Data, Fun) ->
-spec params(binary(), fun(), [{binary(), binary()}]) -> any().
params(Data, Fun, Acc) ->
whitespace(Data,
- fun (<< $;, Rest/binary >>) -> param(Rest, Fun, Acc);
- (Rest) -> Fun(Rest, lists:reverse(Acc))
+ fun (<< $;, Rest/binary >>) ->
+ param(Rest,
+ fun (Rest2, Attr, Value) ->
+ params(Rest2, Fun, [{Attr, Value}|Acc])
+ end);
+ (Rest) ->
+ Fun(Rest, lists:reverse(Acc))
end).
--spec param(binary(), fun(), [{binary(), binary()}]) -> any().
-param(Data, Fun, Acc) ->
+-spec param(binary(), fun()) -> any().
+param(Data, Fun) ->
whitespace(Data,
fun (Rest) ->
token_ci(Rest,
@@ -354,8 +388,7 @@ param(Data, Fun, Acc) ->
(<< $=, Rest2/binary >>, Attr) ->
word(Rest2,
fun (Rest3, Value) ->
- params(Rest3, Fun,
- [{Attr, Value}|Acc])
+ Fun(Rest3, Attr, Value)
end);
(_Rest2, _Attr) -> {error, badarg}
end)
@@ -772,6 +805,56 @@ ce_identity(Data) ->
%% Interpretation.
+%% @doc Convert a cookie name, value and options to its iodata form.
+%% @end
+%%
+%% Initially from Mochiweb:
+%% * Copyright 2007 Mochi Media, Inc.
+%% Initial binary implementation:
+%% * Copyright 2011 Thomas Burdick <[email protected]>
+-spec cookie_to_iodata(iodata(), iodata(), cowboy_req:cookie_opts())
+ -> iodata().
+cookie_to_iodata(Name, Value, Opts) ->
+ MaxAgeBin = case lists:keyfind(max_age, 1, Opts) of
+ false -> <<>>;
+ {_, MaxAge} when is_integer(MaxAge), MaxAge >= 0 ->
+ UTC = calendar:universal_time(),
+ Secs = calendar:datetime_to_gregorian_seconds(UTC),
+ Expires = calendar:gregorian_seconds_to_datetime(Secs + MaxAge),
+ [<<"; Expires=">>, cowboy_clock:rfc2109(Expires),
+ <<"; Max-Age=">>, integer_to_list(MaxAge)]
+ end,
+ DomainBin = case lists:keyfind(domain, 1, Opts) of
+ false -> <<>>;
+ {_, Domain} -> [<<"; Domain=">>, quote(Domain)]
+ end,
+ PathBin = case lists:keyfind(path, 1, Opts) of
+ false -> <<>>;
+ {_, Path} -> [<<"; Path=">>, quote(Path)]
+ end,
+ SecureBin = case lists:keyfind(secure, 1, Opts) of
+ false -> <<>>;
+ {_, true} -> <<"; Secure">>
+ end,
+ HttpOnlyBin = case lists:keyfind(http_only, 1, Opts) of
+ false -> <<>>;
+ {_, true} -> <<"; HttpOnly">>
+ end,
+ [Name, <<"=">>, quote(Value), <<"; Version=1">>,
+ MaxAgeBin, DomainBin, PathBin, SecureBin, HttpOnlyBin].
+
+-spec quote(binary()) -> binary().
+quote(Bin) ->
+ quote(Bin, <<>>).
+
+-spec quote(binary(), binary()) -> binary().
+quote(<<>>, Acc) ->
+ Acc;
+quote(<< $", Rest/bits >>, Acc) ->
+ quote(Rest, << Acc/binary, $\\, $" >>);
+quote(<< C, Rest/bits >>, Acc) ->
+ quote(Rest, << Acc/binary, C >>).
+
%% @doc Convert an HTTP version tuple to its binary form.
-spec version_to_binary(version()) -> binary().
version_to_binary({1, 1}) -> <<"HTTP/1.1">>;
@@ -927,6 +1010,38 @@ nonempty_token_list_test_() ->
],
[{V, fun() -> R = nonempty_list(V, fun token/2) end} || {V, R} <- Tests].
+cookie_list_test_() ->
+ %% {Value, Result}.
+ Tests = [
+ {<<"name=value; name2=value2">>, [
+ {<<"name">>, <<"value">>},
+ {<<"name2">>, <<"value2">>}
+ ]},
+ {<<"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"">>, [
+ {<<"customer">>, <<"WILE_E_COYOTE">>}
+ ]},
+ {<<"$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"; "
+ "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"; "
+ "Shipping=\"FedEx\"; $Path=\"/acme\"">>, [
+ {<<"customer">>, <<"WILE_E_COYOTE">>},
+ {<<"part_number">>, <<"Rocket_Launcher_0001">>},
+ {<<"shipping">>, <<"FedEx">>}
+ ]},
+ %% Potential edge cases (initially from Mochiweb).
+ {<<"foo=\"\\x\"">>, [{<<"foo">>, <<"x">>}]},
+ {<<"=">>, {error, badarg}},
+ {<<" foo ; bar ">>, {error, badarg}},
+ {<<"foo=;bar=">>, {error, badarg}},
+ {<<"foo=\"\\\";\";bar ">>, {error, badarg}},
+ {<<"foo=\"\\\";\";bar=good ">>,
+ [{<<"foo">>, <<"\";">>}, {<<"bar">>, <<"good">>}]},
+ {<<"foo=\"\\\";bar">>, {error, badarg}},
+ {<<"">>, {error, badarg}},
+ {<<"foo=bar , baz=wibble ">>,
+ [{<<"foo">>, <<"bar">>}, {<<"baz">>, <<"wibble">>}]}
+ ],
+ [{V, fun() -> R = cookie_list(V) end} || {V, R} <- Tests].
+
media_range_list_test_() ->
%% {Tokens, Result}
Tests = [
@@ -1040,6 +1155,44 @@ digits_test_() ->
],
[{V, fun() -> R = digits(V) end} || {V, R} <- Tests].
+cookie_to_iodata_test_() ->
+ %% {Name, Value, Opts, Result}
+ Tests = [
+ {<<"Customer">>, <<"WILE_E_COYOTE">>,
+ [{http_only, true}, {domain, <<"acme.com">>}],
+ <<"Customer=WILE_E_COYOTE; Version=1; "
+ "Domain=acme.com; HttpOnly">>},
+ {<<"Customer">>, <<"WILE_E_COYOTE">>,
+ [{path, <<"/acme">>}],
+ <<"Customer=WILE_E_COYOTE; Version=1; Path=/acme">>},
+ {<<"Customer">>, <<"WILE_E_COYOTE">>,
+ [{path, <<"/acme">>}, {badoption, <<"negatory">>}],
+ <<"Customer=WILE_E_COYOTE; Version=1; Path=/acme">>}
+ ],
+ [{R, fun() -> R = iolist_to_binary(cookie_to_iodata(N, V, O)) end}
+ || {N, V, O, R} <- Tests].
+
+cookie_to_iodata_max_age_test() ->
+ F = fun(N, V, O) ->
+ binary:split(iolist_to_binary(
+ cookie_to_iodata(N, V, O)), <<";">>, [global])
+ end,
+ [<<"Customer=WILE_E_COYOTE">>,
+ <<" Version=1">>,
+ <<" Expires=", _/binary>>,
+ <<" Max-Age=111">>,
+ <<" Secure">>] = F(<<"Customer">>, <<"WILE_E_COYOTE">>,
+ [{max_age, 111}, {secure, true}]),
+ case catch F(<<"Customer">>, <<"WILE_E_COYOTE">>, [{max_age, -111}]) of
+ {'EXIT', {{case_clause, {max_age, -111}}, _}} -> ok
+ end,
+ [<<"Customer=WILE_E_COYOTE">>,
+ <<" Version=1">>,
+ <<" Expires=", _/binary>>,
+ <<" Max-Age=86417">>] = F(<<"Customer">>, <<"WILE_E_COYOTE">>,
+ [{max_age, 86417}]),
+ ok.
+
x_www_form_urlencoded_test_() ->
%% {Qs, Result}
Tests = [
diff --git a/src/cowboy_req.erl b/src/cowboy_req.erl
index 2d45a59..dc98e30 100644
--- a/src/cowboy_req.erl
+++ b/src/cowboy_req.erl
@@ -118,6 +118,12 @@
-include_lib("eunit/include/eunit.hrl").
-endif.
+-type cookie_option() :: {max_age, non_neg_integer()}
+ | {domain, binary()} | {path, binary()}
+ | {secure, boolean()} | {http_only, boolean()}.
+-type cookie_opts() :: [cookie_option()].
+-export_type([cookie_opts/0]).
+
-type resp_body_fun() :: fun(() -> {sent, non_neg_integer()}).
-record(http_req, {
@@ -430,6 +436,8 @@ parse_header(Name, Req, Default) when Name =:= <<"content-length">> ->
parse_header(Name, Req, Default, fun cowboy_http:digits/1);
parse_header(Name, Req, Default) when Name =:= <<"content-type">> ->
parse_header(Name, Req, Default, fun cowboy_http:content_type/1);
+parse_header(Name = <<"cookie">>, Req, Default) ->
+ parse_header(Name, Req, Default, fun cowboy_http:cookie_list/1);
parse_header(Name, Req, Default) when Name =:= <<"expect">> ->
parse_header(Name, Req, Default,
fun (Value) ->
@@ -481,11 +489,10 @@ cookie(Name, Req) when is_binary(Name) ->
-spec cookie(binary(), Req, Default)
-> {binary() | true | Default, Req} when Req::req(), Default::any().
cookie(Name, Req=#http_req{cookies=undefined}, Default) when is_binary(Name) ->
- case header(<<"cookie">>, Req) of
- {undefined, Req2} ->
+ case parse_header(<<"cookie">>, Req) of
+ {ok, undefined, Req2} ->
{Default, Req2#http_req{cookies=[]}};
- {RawCookie, Req2} ->
- Cookies = cowboy_cookies:parse_cookie(RawCookie),
+ {ok, Cookies, Req2} ->
cookie(Name, Req2#http_req{cookies=Cookies}, Default)
end;
cookie(Name, Req, Default) ->
@@ -497,11 +504,10 @@ cookie(Name, Req, Default) ->
%% @doc Return the full list of cookie values.
-spec cookies(Req) -> {list({binary(), binary() | true}), Req} when Req::req().
cookies(Req=#http_req{cookies=undefined}) ->
- case header(<<"cookie">>, Req) of
- {undefined, Req2} ->
+ case parse_header(<<"cookie">>, Req) of
+ {ok, undefined, Req2} ->
{[], Req2#http_req{cookies=[]}};
- {RawCookie, Req2} ->
- Cookies = cowboy_cookies:parse_cookie(RawCookie),
+ {ok, Cookies, Req2} ->
cookies(Req2#http_req{cookies=Cookies})
end;
cookies(Req=#http_req{cookies=Cookies}) ->
@@ -794,11 +800,11 @@ multipart_skip(Req) ->
%% Response API.
%% @doc Add a cookie header to the response.
--spec set_resp_cookie(binary(), binary(),
- [cowboy_cookies:cookie_option()], Req) -> Req when Req::req().
-set_resp_cookie(Name, Value, Options, Req) ->
- {HeaderName, HeaderValue} = cowboy_cookies:cookie(Name, Value, Options),
- set_resp_header(HeaderName, HeaderValue, Req).
+-spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req)
+ -> Req when Req::req().
+set_resp_cookie(Name, Value, Opts, Req) ->
+ Cookie = cowboy_http:cookie_to_iodata(Name, Value, Opts),
+ set_resp_header(<<"set-cookie">>, Cookie, Req).
%% @doc Add a header to the response.
-spec set_resp_header(binary(), iodata(), Req)
diff --git a/src/cowboy_websocket.erl b/src/cowboy_websocket.erl
index e62a301..c53fe89 100644
--- a/src/cowboy_websocket.erl
+++ b/src/cowboy_websocket.erl
@@ -153,9 +153,9 @@ websocket_handshake(State=#state{socket=Socket, transport=Transport,
{<< "http", Location/binary >>, Req1} = cowboy_req:url(Req),
{ok, Req2} = cowboy_req:upgrade_reply(
<<"101 WebSocket Protocol Handshake">>,
- [{<<"Upgrade">>, <<"WebSocket">>},
- {<<"Sec-Websocket-Location">>, << "ws", Location/binary >>},
- {<<"Sec-Websocket-Origin">>, Origin}],
+ [{<<"upgrade">>, <<"WebSocket">>},
+ {<<"sec-websocket-location">>, << "ws", Location/binary >>},
+ {<<"sec-websocket-origin">>, Origin}],
Req1),
%% Flush the resp_sent message before moving on.
receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,
@@ -182,8 +182,8 @@ websocket_handshake(State=#state{transport=Transport, challenge=Challenge},
Req, HandlerState) ->
{ok, Req2} = cowboy_req:upgrade_reply(
101,
- [{<<"Upgrade">>, <<"websocket">>},
- {<<"Sec-Websocket-Accept">>, Challenge}],
+ [{<<"upgrade">>, <<"websocket">>},
+ {<<"sec-websocket-accept">>, Challenge}],
Req),
%% Flush the resp_sent message before moving on.
receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,