From 75d14d6bddf1dd4d9da9d4933428a0cfebb7989d Mon Sep 17 00:00:00 2001 From: Brad Nelson Date: Sun, 28 Aug 2022 22:27:10 -0700 Subject: [PATCH] Making httpd body handling better. --- posix/httpd.fs | 32 ++++++++++++++++++++++++++------ posix/web_interface.fs | 2 +- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/posix/httpd.fs b/posix/httpd.fs index c3446aa..8bb5c3e 100644 --- a/posix/httpd.fs +++ b/posix/httpd.fs @@ -15,12 +15,18 @@ ( Lazy loaded HTTP Daemon ) : httpd r| -vocabulary httpd httpd definitions also sockets +vocabulary httpd httpd definitions +also sockets +also internals 1 constant max-connections 2048 constant chunk-size create chunk chunk-size allot 0 value chunk-filled +256 constant body-chunk-size +create body-chunk body-chunk-size allot +0 value body-1st-read +0 value body-read -1 value sockfd -1 value clientfd sockaddr httpd-port sockaddr client variable client-len @@ -56,21 +62,34 @@ variable goal variable goal# : skipto ( n ch -- n ) >r begin dup r@ in@<> over end< and while 1+ repeat rdrop ; : skipover ( n ch -- n ) skipto 1+ ; -: eat ( n ch -- n a n ) >r dup r> skipover swap over over - 1- >r chunk + r> ; +: eat ( n ch -- n a n ) >r dup r> skipover swap 2dup - 1- >r chunk + r> ; : crnl= ( n -- f ) dup chunk + c@ 13 = swap 1+ chunk + c@ nl = and ; : header ( a n -- a n ) goal# ! goal ! 0 nl skipover begin dup end< while dup crnl= if drop chunk 0 exit then - [char] : eat goal @ goal# @ strcase= if 2 + 13 eat rot drop exit then + [char] : eat goal @ goal# @ strcase= if 1+ 13 eat rot drop exit then nl skipover repeat drop chunk 0 ; -: body ( -- a n ) - ( TODO: Fix to handle body bigger than chunk size ) +: content-length ( -- n ) + s" Content-Length" header s>number? 0= if 0 then ; +: body ( -- a n ) ( reads a part of body ) + body-1st-read if + body-read content-length >= if + 0 0 exit + then + body-chunk body-chunk-size clientfd read-file throw dup +to body-read + body-chunk swap exit + then + -1 to body-1st-read + 0 to body-read 0 nl skipover begin dup end< while - dup crnl= if 2 + chunk-filled over - swap chunk + swap exit then + dup crnl= if + 2 + chunk-filled over - swap chunk + swap + dup +to body-read exit + then nl skipover repeat drop chunk 0 ; @@ -81,6 +100,7 @@ variable goal variable goal# repeat drop 0 ; : read-headers + 0 to body-1st-read 0 to chunk-filled begin completed? 0= while chunk chunk-filled + chunk-size chunk-filled - diff --git a/posix/web_interface.fs b/posix/web_interface.fs index 23b99ec..28bfc65 100644 --- a/posix/web_interface.fs +++ b/posix/web_interface.fs @@ -124,7 +124,7 @@ create out-string out-size 1+ allot align ; : handle-input - body input-stream >stream pause + begin body dup >r input-stream >stream pause r> 0= until out-string out-size output-stream stream> s" text/plain" ok-response out-string z>s send