-:- module(serve, [serve/3]).
+:- module(serve, [serve/4]).
:- use_module(library(dcgs)).
:- use_module(config).
:- use_module(library(iso_ext)).
:- use_module(library(lists)).
:- use_module(library(pio)).
+:- use_module(library(charsio)).
:- use_module(library(sockets)).
+:- use_module(library(debug)).
:- use_module(log).
:- use_module(mime).
:- use_module(response).
-%% serve(+Stream, +Path, +Query)
+%% serve(+Stream, +Root, +Path, -Query)
%
% Serve the file at Path to Stream
-serve(S, /, Q) :-
- serve(S, '/index.gmi', Q).
-serve(S, Path, _) :-
+serve(S, Root, /, Q) :-
+ serve(S, Root, '/index.gmi', Q).
+serve(S, Root, Path, _) :-
atom_chars(Path, Chars),
( is_absolute(Chars)
-> guess_mime(Chars, Mime),
- content(Root),
append(Root, Chars, File),
( file_exists(File)
-> log_msg("response", "File does exist~n", []),
phrase(response(success, Mime), Response0),
format(S, "~s", [Response0]),
open(stream(S), write, _, [type(binary)]),
- catch(copy_stream(FileStream, S),
+ catch(src_dest(FileStream, S),
error(existence_error(stream, _), _),
log_msg("response", "Client disconnected mid-stream~n", [])),
log_msg("response", "Sent binary response~n", [])
),
close(FileStream)
).
+
+src_dest(FileStream, DestStream) :-
+ get_n_chars(FileStream, 4096, Chars),
+ ( Chars = [] -> true
+ ; phrase_to_stream(seq(Chars), DestStream),
+ false).
+
+src_dest(FileStream, DestStream) :-
+ src_dest(FileStream, DestStream).