Skip to content

Commit cefe99f

Browse files
committed
response: use a rolling response timeout when sending data to clients
Previously, clients could DoS the server by requesting large files without ever reading them from the output socket because the timeout was set based upon the size of the files being requested. This change adds a rolling send timeout such that for every chunk of data that is read by the client, the timeout resets. If the client is too slow, then the connection is eventually terminated. To test this change you can set up a file server with a low send timeout: #lang racket/base (require (prefix-in files: web-server/dispatchers/dispatch-files) web-server/dispatchers/filesystem-map web-server/web-server) (define shutdown (serve #:dispatch (files:make #:url->path (make-url->path ".")) #:port 9000 #:response-send-timeout 5)) (with-handlers ([exn:break? (lambda _ (shutdown))]) (sync never-evt)) create a large file in the directory that the server is running in: # creates a 100MB file called test.dat filled with zeros # replace "bs=1M" with "bs=1m" on macOs dd if=/dev/null of=test.dat count=100 bs=1M and try to read that file using a client that's intentionally slower than that send timeout: #lang racket/base (require racket/format racket/tcp) (define-values (in out) (tcp-connect "127.0.0.1" 9000)) (parameterize ([current-output-port out]) (display "GET /test.dat HTTP/1.1\r\n") (display "\r\n") (flush-output)) (define st (current-inexact-milliseconds)) (define n 0) (let loop () (printf "delta: ~ams and ~amb\n" (- (current-inexact-milliseconds) st) (~r (/ n 1024 1024))) (define bs (read-bytes (* 1 1024 1024) in)) (unless (eof-object? bs) (set! n (+ n (bytes-length bs))) (sleep 10) (loop))) Following this sequence of steps on my machine, the client gets disconnected within about 20 seconds: $ racket client.rkt delta: 0.075927734375ms and 0mb delta: 10009.180908203125ms and 1mb delta: 20015.35791015625ms and 1.5544mb $ Before this change, the client would only get disconnected after 100 million seconds (1 second per every byte in the requested file).
1 parent 65460f6 commit cefe99f

17 files changed

Lines changed: 191 additions & 77 deletions

‎web-server-doc/web-server/scribblings/connection-manager.scrbl‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,10 @@ for doing this.
5353
Calls @racket[increment-timer!] with the timer behind @racket[c] with @racket[t].
5454
}
5555

56+
@defproc[(reset-connection-timeout! [c connection?]
57+
[t number?]) void?]{
58+
59+
Calls @racket[reset-timer!] with the timer behind @racket[c] with @racket[t].
60+
}
61+
5662
}

‎web-server-doc/web-server/scribblings/ctable.scrbl‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,17 @@ structures.
3131
@index{Web Server configuration table}
3232
The configuration table format is:
3333

34-
@index{port} @index{max-waiting} @index{initial-connection-timeout}
34+
@index{port} @index{max-waiting}
35+
@index{initial-connection-timeout}
36+
@index{response-timeout} @index{response-send-timeout}
3537
@index{default-host-table} @index{virtual-host-table}
3638

3739
@racketblock[
3840
`((port ,integer?)
3941
(max-waiting ,exact-integer?)
4042
(initial-connection-timeout ,integer?)
43+
(response-timeout ,exact-positive-integer?)
44+
(response-send-timeout ,exact-positive-integer?)
4145
(default-host-table
4246
,host-table-sexpr?)
4347
(virtual-host-table
@@ -105,5 +109,5 @@ This function reads a @racket[configuration-table] from @racket[path].
105109
void]{
106110
This function writes a @racket[configuration-table] to @racket[path].
107111
}
108-
112+
109113
}

‎web-server-doc/web-server/scribblings/dispatch-server.scrbl‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,22 @@ ports (e.g., to implement SSL) as used by the dispatch server.
5555
}
5656

5757
@defsignature[dispatch-server-config^ ()]{
58-
5958
@defthing[port listen-port-number?]{Specifies the port to serve on.}
6059
@defthing[listen-ip (or/c string? false/c)]{Passed to @racket[tcp-listen].}
6160
@defthing[max-waiting exact-nonnegative-integer?]{Passed to @racket[tcp-listen].}
6261
@defthing[initial-connection-timeout integer?]{Specifies the initial timeout given to a connection.}
62+
@defthing[response-timeout exact-positive-integer?]{
63+
Specifies the allotted time each request handler has in order to
64+
produce a response.
65+
}
66+
@defthing[response-send-timeout exact-positive-integer?]{
67+
Specifies the amount of time the server will wait for a chunk of
68+
response data to be sent to the client. This timeout is reset every
69+
time a chunk of data is successfully sent to the client.
70+
}
6371
@defproc[(read-request [c connection?]
6472
[p listen-port-number?]
65-
[port-addresses
73+
[port-addresses
6674
(input-port? . -> . (values string? string?))])
6775
(values any/c boolean?)]{
6876
Defines the way the server reads requests off connections to be passed
@@ -82,7 +90,7 @@ provides the unit that actually implements a dispatching server.
8290

8391
@defthing[dispatch-server-with-connect@ (unit/c (import tcp^
8492
dispatch-server-connect^
85-
dispatch-server-config^)
93+
dispatch-server-config^)
8694
(export dispatch-server^))]{
8795
Runs the dispatching server config in a very basic way, except that it uses
8896
@secref["connection-manager"] to manage connections.
@@ -92,7 +100,7 @@ provides the unit that actually implements a dispatching server.
92100
}
93101

94102
@defthing[dispatch-server@ (unit/c (import tcp^
95-
dispatch-server-config^)
103+
dispatch-server-config^)
96104
(export dispatch-server^))]{
97105
Like @racket[dispatch-server-with-connect@], but using @racket[raw:dispatch-server-connect@].}
98106

‎web-server-doc/web-server/scribblings/launch.scrbl‎

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,30 +37,37 @@ This module provides functions for launching dispatching servers.
3737
[#:max-request-line-length max-request-line-length exact-positive-integer? (* 8 1024)]
3838
[#:max-request-fields max-request-fields exact-positive-integer? 100]
3939
[#:max-request-field-length max-request-field-length exact-positive-integer? (* 8 1024)]
40-
[#:max-request-body-length max-request-body-length exact-positive-integer? (* 10 1024 1024)])
40+
[#:max-request-body-length max-request-body-length exact-positive-integer? (* 10 1024 1024)]
41+
[#:response-timeout response-timeout exact-positive-integer? 60]
42+
[#:response-send-timeout response-send-timeout exact-positive-integer? 60])
4143
(-> void)]{
44+
4245
Constructs an appropriate @racket[dispatch-server-config^], invokes the
4346
@racket[dispatch-server@], and calls its @racket[serve] function.
4447

45-
If @racket[connection-close?] is @racket[#t], then every connection is closed after one
46-
request. Otherwise, the client decides based on what HTTP version it uses.
48+
If @racket[connection-close?] is @racket[#t], then every connection is
49+
closed after one request. Otherwise, the client decides based on what
50+
HTTP version it uses.
51+
52+
The @racket[#:dispatch-server-connect@] argument supports the
53+
conversion of raw connections; for example, @racket[make-ssl-connect@]
54+
produces a unit to serve SSL by converting raw TCP ports to SSL ports;
55+
see also @secref["faq:https"].
4756

48-
The @racket[#:dispatch-server-connect@] argument supports the conversion of raw connections;
49-
for example, @racket[make-ssl-connect@] produces a unit to serve SSL by converting
50-
raw TCP ports to SSL ports; see also @secref["faq:https"].
51-
The @racket[#:tcp@] argument supports replacing TCP connections with other kinds of connections (and
52-
was formerly recommended for SLL support). Beware that the server expects the @racket[tcp-accept] operation
53-
from @racket[tcp@] to be effectively atomic; new connections are not accepted while @racket[tcp-accept]
54-
is in progress.
57+
The @racket[#:tcp@] argument supports replacing TCP connections with
58+
other kinds of connections (and was formerly recommended for SLL
59+
support). Beware that the server expects the @racket[tcp-accept]
60+
operation from @racket[tcp@] to be effectively atomic; new connections
61+
are not accepted while @racket[tcp-accept] is in progress.
5562

5663
The @racket[#:request-read-timeout] argument controls how long the
5764
request parser will wait for request data to come in from the client
5865
before it closes the connection. If you need to support large file
5966
uploads over slow connections, then you may need to adjust this
6067
value.
6168

62-
The @racket[#:max-request-line-length] argument controls how long the
63-
(in bytes) "request line" (the first line of an HTTP request, which
69+
The @racket[#:max-request-line-length] argument controls how long (in
70+
bytes) the "request line" (the first line of an HTTP request, which
6471
specifies the request method, path and protocol version) can be.
6572
Increase this if you have very long URLs. Requests with a longer
6673
request line than this value are rejected.
@@ -77,6 +84,19 @@ This module provides functions for launching dispatching servers.
7784
bytes) the request body can be. Requests containing larger bodies
7885
than this value are rejected.
7986

87+
The @racket[#:response-timeout] argument controls how long individual
88+
request handlers are allowed to run until they write their first byte
89+
of response data. This timeout starts after the request has been
90+
read. If the request handler doesn't write its data in time, the
91+
connection is killed.
92+
93+
The @racket[#:response-send-timeout] argument controls how long the
94+
server will wait for response data to be sent to the client. Every
95+
time a new chunk of data is sent to the client, this timeout resets.
96+
If your application uses streaming responses or long polling, then
97+
make sure that you send data (such as a no-op) periodically so your
98+
request handler doesn't hit this timeout.
99+
80100
Here's an example of a simple web server that serves files
81101
from a given path:
82102

@@ -98,6 +118,8 @@ from a given path:
98118
#:changed "1.6" @elem{Added the @racket[#:max-request-fields] argument.}
99119
#:changed "1.6" @elem{Added the @racket[#:max-request-field-length] argument.}
100120
#:changed "1.6" @elem{Added the @racket[#:max-request-body-length] argument.}
121+
#:changed "1.6" @elem{Added the @racket[#:response-timeout] argument.}
122+
#:changed "1.6" @elem{Added the @racket[#:response-send-timeout] argument.}
101123
#:changed "1.1" @elem{Added the @racket[#:dispatch-server-connect@] argument.}]}
102124

103125

@@ -117,7 +139,9 @@ from a given path:
117139
[#:max-request-line-length max-request-line-length exact-positive-integer? (* 8 1024)]
118140
[#:max-request-fields max-request-fields exact-positive-integer? 100]
119141
[#:max-request-field-length max-request-field-length exact-positive-integer? (* 8 1024)]
120-
[#:max-request-body-length max-request-body-length exact-positive-integer? (* 10 1024 1024)])
142+
[#:max-request-body-length max-request-body-length exact-positive-integer? (* 10 1024 1024)]
143+
[#:response-timeout response-timeout exact-positive-integer? 60]
144+
[#:response-send-timeout response-send-timeout exact-positive-integer? 60])
121145
(-> void)]{
122146
Calls @racket[serve] multiple times, once for each @racket[port], and returns
123147
a function that shuts down all of the server instances.
@@ -128,6 +152,8 @@ from a given path:
128152
#:changed "1.6" @elem{Added the @racket[#:max-request-fields] argument.}
129153
#:changed "1.6" @elem{Added the @racket[#:max-request-field-length] argument.}
130154
#:changed "1.6" @elem{Added the @racket[#:max-request-body-length] argument.}
155+
#:changed "1.6" @elem{Added the @racket[#:response-timeout] argument.}
156+
#:changed "1.6" @elem{Added the @racket[#:response-send-timeout] argument.}
131157
#:changed "1.1" @elem{Added the @racket[#:dispatch-server-connect@] argument.}]}
132158

133159

@@ -146,7 +172,9 @@ from a given path:
146172
[#:max-request-line-length max-request-line-length exact-positive-integer? (* 8 1024)]
147173
[#:max-request-fields max-request-fields exact-positive-integer? 100]
148174
[#:max-request-field-length max-request-field-length exact-positive-integer? (* 8 1024)]
149-
[#:max-request-body-length max-request-body-length exact-positive-integer? (* 10 1024 1024)])
175+
[#:max-request-body-length max-request-body-length exact-positive-integer? (* 10 1024 1024)]
176+
[#:response-timeout response-timeout exact-positive-integer? 60]
177+
[#:response-send-timeout response-send-timeout exact-positive-integer? 60])
150178
(-> void)]{
151179
Calls @racket[serve/ports] multiple times, once for each @racket[ip], and returns
152180
a function that shuts down all of the server instances.
@@ -157,6 +185,8 @@ from a given path:
157185
#:changed "1.6" @elem{Added the @racket[#:max-request-fields] argument.}
158186
#:changed "1.6" @elem{Added the @racket[#:max-request-field-length] argument.}
159187
#:changed "1.6" @elem{Added the @racket[#:max-request-body-length] argument.}
188+
#:changed "1.6" @elem{Added the @racket[#:response-timeout] argument.}
189+
#:changed "1.6" @elem{Added the @racket[#:response-send-timeout] argument.}
160190
#:changed "1.1" @elem{Added the @racket[#:dispatch-server-connect@] argument.}]}
161191

162192
@defproc[(serve/web-config@ [config@ (unit/c (import) (export web-config^))]

‎web-server-lib/info.rkt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
(define deps '("srfi-lite-lib"
66
("base" #:version "6.2.900.15")
7-
"net-lib"
7+
"net-lib"
88
"net-cookies-lib"
99
"compatibility-lib"
1010
"scribble-text-lib"

‎web-server-lib/web-server/configuration/configuration-table-structs.rkt‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,16 @@
33
net/url)
44
(require web-server/http/response-structs
55
web-server/http/request-structs
6-
"../private/util.rkt")
6+
"../private/util.rkt")
77

88
; configuration-table = (make-configuration-table nat nat num host-table (listof (cons str host-table)))
99
(define-struct configuration-table
10-
(port max-waiting initial-connection-timeout default-host virtual-hosts))
10+
(port max-waiting initial-connection-timeout response-timeout response-send-timeout default-host virtual-hosts))
1111

1212
; host-table = (make-host-table (listof str) sym messages timeouts paths)
1313
(define-struct host-table (indices log-format messages timeouts paths))
1414

15-
(define-struct host (indices log-format log-path passwords responders timeouts paths))
15+
(define-struct host (indices log-format log-path passwords responders timeouts paths))
1616

1717
(define-struct responders
1818
(servlet servlet-loading authentication servlets-refreshed passwords-refreshed file-not-found protocol collect-garbage))
@@ -32,15 +32,17 @@
3232
([port port-number?]
3333
[max-waiting exact-nonnegative-integer?]
3434
[initial-connection-timeout natural-number/c]
35+
[response-timeout exact-positive-integer?]
36+
[response-send-timeout exact-positive-integer?]
3537
[default-host host-table?]
3638
[virtual-hosts (listof (cons/c string? host-table?))])]
37-
[struct host-table
39+
[struct host-table
3840
([indices (listof string?)]
3941
[log-format symbol?]
4042
[messages messages?]
4143
[timeouts timeouts?]
4244
[paths paths?])]
43-
[struct host
45+
[struct host
4446
([indices (listof string?)]
4547
[log-format symbol?]
4648
[log-path (or/c false/c path-string?)]
@@ -65,13 +67,13 @@
6567
[file-not-found string?]
6668
[protocol string?]
6769
[collect-garbage string?])]
68-
[struct timeouts
70+
[struct timeouts
6971
([default-servlet number?]
7072
[password number?]
7173
[servlet-connection number?]
7274
[file-per-byte number?]
7375
[file-base number?])]
74-
[struct paths
76+
[struct paths
7577
([conf (or/c false/c path-string?)]
7678
[host-base (or/c false/c path-string?)]
7779
[log (or/c false/c path-string?)]

‎web-server-lib/web-server/configuration/configuration-table.rkt‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,16 @@
3434
(define port (get-binding 'port t 80))
3535
(define max-waiting (get-binding 'max-waiting t 511))
3636
(define initial-connection-timeout (get-binding 'initial-connection-timeout t 30))
37+
(define response-timeout (get-binding 'response-timeout t 60))
38+
(define response-send-timeout (get-binding 'response-send-timeout t 60))
3739
(define default-host-table (get-binding* 'default-host-table t `()))
3840
(define virtual-host-table (get-binding* 'virtual-host-table t `()))
3941
(make-configuration-table
40-
port max-waiting initial-connection-timeout
42+
port
43+
max-waiting
44+
initial-connection-timeout
45+
response-timeout
46+
response-send-timeout
4147
(parse-host default-host-table)
4248
(map (lambda (h)
4349
(cons (car h) (parse-host (cdr h))))
@@ -96,6 +102,8 @@
96102
`((port ,(configuration-table-port new))
97103
(max-waiting ,(configuration-table-max-waiting new))
98104
(initial-connection-timeout ,(configuration-table-initial-connection-timeout new))
105+
(response-timeout ,(configuration-table-response-timeout new))
106+
(response-send-timeout ,(configuration-table-response-send-timeout new))
99107
(default-host-table
100108
,(host-table->sexpr (configuration-table-default-host new)))
101109
(virtual-host-table

‎web-server-lib/web-server/http/response.rkt‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,18 @@
1313

1414
(provide/contract
1515
[print-headers (output-port? (listof header?) . -> . void)]
16+
[current-send-timeout (parameter/c exact-positive-integer?)]
1617
[rename ext:output-response output-response (connection? response? . -> . void)]
1718
[rename ext:output-response/method output-response/method (connection? response? bytes? . -> . void)]
1819
[rename ext:output-file output-file (connection? path-string? bytes? (or/c bytes? false/c) (or/c pair? false/c) . -> . void)])
1920

21+
; current-send-timeout : parameter-of number
22+
; This parameter controls the allotted time between sends to the client
23+
; per individual response. Whenever a chunk of data is written to a
24+
; client, the timeout for that connection resets to this value.
25+
(define current-send-timeout
26+
(make-parameter 60))
27+
2028
(define (output-response conn resp)
2129
(output-response/method conn resp #"GET"))
2230

@@ -134,8 +142,8 @@
134142
(unless (eof-object? bytes-read-or-eof)
135143
;; For every chunk, increase the connection timeout s.t.
136144
;; a responder can run indefinitely as long as it writes
137-
;; *something* every 60 seconds.
138-
(reset-connection-timeout! conn 60)
145+
;; *something* every (current-send-timeout) seconds.
146+
(reset-connection-timeout! conn (current-send-timeout))
139147
(fprintf to-client "~a\r\n" (number->string bytes-read-or-eof 16))
140148
(write-bytes buffer to-client 0 bytes-read-or-eof)
141149
(fprintf to-client "\r\n")
@@ -222,6 +230,11 @@
222230
;; (U bytes #f)
223231
;; -> void
224232
(define (output-file/boundary conn file-path method maybe-mime-type ranges boundary)
233+
;; Ensure there is enough time left to write the first chunk of
234+
;; response data. `output-file-range' then resets the connection
235+
;; timeout once for every chunk it's able to write to the client.
236+
(reset-connection-timeout! conn (current-send-timeout))
237+
225238
; total-file-length : integer
226239
(define total-file-length
227240
(file-size file-path))
@@ -278,21 +291,19 @@
278291
(make-206-response modified-seconds maybe-mime-type total-content-length total-file-length converted-ranges boundary)
279292
(make-200-response modified-seconds maybe-mime-type total-content-length)))
280293
; Send the appropriate file content:
294+
; TODO: What if we want to output-file during a POST?
281295
(when (bytes-ci=? method #"GET")
282-
(adjust-connection-timeout! ; Give it one second per byte.
283-
conn
284-
(apply + (map (lambda (range)
285-
(- (cdr range) (car range)))
286-
converted-ranges)))
287-
(with-handlers ([exn:fail? (lambda (exn) (network-error 'output-file (exn-message exn)))])
296+
(with-handlers ([exn:fail? (lambda (exn)
297+
(network-error 'output-file (exn-message exn)))])
288298
(call-with-input-file* file-path
289299
(lambda (input)
290300
(if (= (length converted-ranges) 1)
291301
; Single ranges (in 200 or 206 responses) are sent straight out
292302
; in their simplest form:
293303
(output-file-range conn input (caar converted-ranges) (cdar converted-ranges))
294304
; Multiple ranges are encoded as multipart/byteranges:
295-
(let loop ([ranges converted-ranges] [multipart-headers multipart-headers])
305+
(let loop ([ranges converted-ranges]
306+
[multipart-headers multipart-headers])
296307
(match ranges
297308
[(list)
298309
; Final boundary (must start on new line; ends with a new line)
@@ -327,7 +338,19 @@
327338
;; start must be inclusive; end must be exclusive.
328339
(define (output-file-range conn input start end)
329340
(file-position input start)
330-
(let ([limited-input (make-limited-input-port input (- end start) #f)])
341+
(define custodian (make-custodian))
342+
(parameterize ([current-custodian custodian])
343+
(define limited-input (make-limited-input-port input (- end start) #f))
344+
(thread
345+
(lambda _
346+
(let loop ()
347+
;; Every time the limited-input is read from, reset
348+
;; the connection timeout and give the client another
349+
;; (current-send-timeout) seconds' worth of lease.
350+
(sync (port-progress-evt limited-input))
351+
(unless (port-closed? limited-input)
352+
(reset-connection-timeout! conn (current-send-timeout))
353+
(loop)))))
331354
(copy-port limited-input (connection-o-port conn))
332355
(close-input-port limited-input)))
333356

0 commit comments

Comments
 (0)