Clear up input file code in purr.

In order to accept a file from stdin, it is necessary to buffer it in
its entirety, so that the final size is known and can be included in the
HTTP header.

As it stands, the stream mode for mmap_file, when used for reading
files, is not extremely useful.

Also:

- files.c: look at fwrite error.
- mmap_file.c: disable buffering for FILE stream.
This commit is contained in:
Érico Rolim 2020-10-01 19:09:27 -03:00
parent 0b7243174c
commit 7803af405c
3 changed files with 21 additions and 10 deletions

View File

@ -185,7 +185,7 @@ size_t mmap_to_ssl(struct transmission_information ti)
if (ti.ssl) {
err = br_sslio_write_all(ti.ioc, tmp, wlen);
} else {
fwrite(tmp, 1, wlen, ti.socket_write_stream);
err = (int)fwrite(tmp, 1, wlen, ti.socket_write_stream) != wlen;
}
if (err == 0) {
rv += wlen;

View File

@ -54,6 +54,9 @@ struct mmap_file create_mmap_from_FILE(FILE *stream, const char *mode)
return rv;
}
// remove buffering
setbuf(stream, NULL);
rv.stream = stream;
rv.use_stream = true;
// make data pointer valid, for error checking
@ -116,7 +119,6 @@ int read_from_mmap(struct mmap_file *file, uint8_t *buffer, int n)
assert(file->prot & PROT_READ);
if (file->use_stream) {
// TODO: returns bogus values, transmissions end up empty
return fread(buffer, 1, n, file->stream);
}

25
purr.c
View File

@ -188,19 +188,28 @@ int main (int argc, char **argv)
}
url = argv[1];
} else if (send) {
if (argc == 2 && strcmp(argv[1], "-")) {
input = create_mmap_from_file(argv[1], PROT_READ);
if (ERROR_MMAP(input)) {
perror("couln't open input file");
exit(EXIT_FAILURE);
}
} else if (argc > 2) {
bool using_stdin = false;
if (argc > 2) {
usage(true);
} else if (argc == 2 && strcmp(argv[1], "-")) {
input = create_mmap_from_file(argv[1], PROT_READ);
} else {
fputs("stdin not supported for ~now~ meow!\n", stderr);
// it is necessary to read from stdin instead of streaming a file,
// because the HTTP header includes a Content-Length field,
// which needs to be populated.
input = create_mmap_from_file(NULL, PROT_MEM);
using_stdin = true;
}
if (ERROR_MMAP(input)) {
perror("create_mmap_from_file()");
exit(EXIT_FAILURE);
}
if (using_stdin) {
input.size = fread(input.data, 1, OUTPUT_FILE_SIZE, stdin);
}
if (url_opt) {
url = url_opt;
} else {