Study · Advanced · HTTP/1.1
Thực hành upload tệp
Gửi tệp trực tiếp trước, rồi thử một form multipart. So sánh lúc nào server bắt đầu ghi và chuyện gì xảy ra khi client ngắt giữa chừng.
Các bài này gửi tệp từ client lên server. Muốn trả tệp đã lưu từ server về client, xem tải xuống với file response và sendfile. Tệp lớn hơn 8 MiB: tải lên qua nhiều request.
Chọn ngôn ngữ
Mở mục ngôn ngữ bên dưới, chạy server trong một thư mục mới rồi mở terminal thứ hai ở cùng thư mục. Ví dụ dùng HTTP/1.1 trên 127.0.0.1:8080 và lưu vào uploads/. Mỗi lần chỉ chạy một server. Khi xong, nhấn Enter trong terminal của server để dừng.
C / C++ · SDK 2.3.0
Cài gói chính thức SDK 2.3.0. Cài GMime và pkg-config cho ví dụ đọc form.
Cài thư viện đọc form
sudo apt install libgmime-3.0-dev pkg-configbrew install gmime pkgconfMã nguồn C/C++
Lưu 5 tệp này cùng thư mục dự án.
cmake_minimum_required(VERSION 3.24)
project(coakka_http_upload LANGUAGES C CXX)
find_package(CoAkkaHttpHost 2.3.0 EXACT CONFIG REQUIRED)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GMime REQUIRED IMPORTED_TARGET gmime-3.0)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# Some GMime distributions require a destroy callback in this signature.
include(CheckCSourceCompiles)
set(CMAKE_REQUIRED_LIBRARIES PkgConfig::GMime)
check_c_source_compiles("
#include <gmime/gmime.h>
int main(void) {
g_mime_parser_options_set_warning_callback(0, 0, 0, 0);
return 0;
}
" UPLOAD_GMIME_CALLBACK_HAS_NOTIFY)
unset(CMAKE_REQUIRED_LIBRARIES)
add_library(upload-handler STATIC upload.c)
if(UPLOAD_GMIME_CALLBACK_HAS_NOTIFY)
target_compile_definitions(upload-handler PRIVATE UPLOAD_GMIME_CALLBACK_HAS_NOTIFY)
endif()
target_link_libraries(upload-handler PUBLIC CoAkkaHttp::host PkgConfig::GMime)
add_executable(upload-c main.c)
add_executable(upload-cpp main.cpp)
target_link_libraries(upload-c PRIVATE upload-handler)
target_link_libraries(upload-cpp PRIVATE upload-handler)
foreach(target IN ITEMS upload-handler upload-c upload-cpp)
target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic -Werror)
endforeach()
#ifndef COAKKA_PORTAL_UPLOAD_H
#define COAKKA_PORTAL_UPLOAD_H
#ifdef __cplusplus
extern "C" {
#endif
int run_upload_lab(void);
#ifdef __cplusplus
}
#endif
#endif
#define _POSIX_C_SOURCE 200809L
#include "upload.h"
#include <coakka/http/host.h>
#include <errno.h>
#include <gmime/gmime.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
enum { FORM_LIMIT = 64 * 1024, FILE_LIMIT = 32 * 1024, MAX_UPLOADS = 16 };
enum { RAW_ROUTE = 1, FORM_ROUTE = 2 };
typedef struct {
coakka_http_host_exchange_t id;
bool active;
FILE *file;
char path[sizeof("uploads/incoming-XXXXXX")];
size_t size;
unsigned failure;
} upload_t;
static coakka_http_host_bytes_t bytes(const char *value) {
return (coakka_http_host_bytes_t){(const uint8_t *)value, strlen(value)};
}
static void discard(upload_t *upload) {
if (upload->file != NULL) {
fclose(upload->file);
}
if (upload->path[0] != '\0' && unlink(upload->path) != 0 && errno != ENOENT) {
perror("remove partial upload");
}
*upload = (upload_t){0};
}
static void begin(upload_t *upload, coakka_http_host_exchange_t id) {
upload->active = true;
upload->id = id;
// A unique temporary file in the same directory as the final file.
strcpy(upload->path, "uploads/incoming-XXXXXX");
const int fd = mkstemp(upload->path);
if (fd < 0) {
upload->path[0] = '\0';
upload->failure = 500U;
return;
}
upload->file = fdopen(fd, "wb");
if (upload->file == NULL) {
close(fd);
upload->failure = 500U;
}
}
static void append(upload_t *upload, const uint8_t *data, size_t size) {
if (upload->failure != 0U) {
return;
}
if (size > FILE_LIMIT - upload->size) {
upload->failure = 413U;
} else if (size != 0U && fwrite(data, 1U, size, upload->file) != size) {
upload->failure = 500U;
} else {
upload->size += size;
}
}
static unsigned finish(upload_t *upload, const char *destination) {
if (upload->failure != 0U) {
return upload->failure;
}
const int close_result = fclose(upload->file);
upload->file = NULL;
if (close_result != 0 || rename(upload->path, destination) != 0) {
return 500U;
}
upload->path[0] = '\0';
return 201U;
}
static void parser_warning(gint64 offset, GMimeParserWarning warning,
const gchar *item, gpointer context) {
(void)offset;
(void)warning;
(void)item;
*(bool *)context = true;
}
static unsigned parse_form(coakka_http_host_bytes_t content_type,
coakka_http_host_bytes_t body, size_t *saved) {
if (content_type.size == 0U ||
memchr(content_type.data, '\r', content_type.size) != NULL ||
memchr(content_type.data, '\n', content_type.size) != NULL ||
memchr(content_type.data, '\0', content_type.size) != NULL) {
return 400U;
}
GByteArray *message = g_byte_array_sized_new((
guint)(content_type.size + body.size + sizeof("Content-Type: \r\n\r\n")));
g_byte_array_append(message, (const guint8 *)"Content-Type: ", 14U);
g_byte_array_append(message, content_type.data, (guint)content_type.size);
g_byte_array_append(message, (const guint8 *)"\r\n\r\n", 4U);
if (body.size != 0U) {
g_byte_array_append(message, body.data, (guint)body.size);
}
// Core has already admitted a complete buffered form. The app parser
// validates its structure while request bytes are still available.
GMimeStream *input = g_mime_stream_mem_new_with_buffer(
(const char *)message->data, message->len);
GMimeParser *parser = g_mime_parser_new_with_stream(input);
GMimeParserOptions *options = g_mime_parser_options_new();
bool warned = false;
#ifdef UPLOAD_GMIME_CALLBACK_HAS_NOTIFY
g_mime_parser_options_set_warning_callback(options, parser_warning, &warned,
NULL);
#else
g_mime_parser_options_set_warning_callback(options, parser_warning, &warned);
#endif
GMimeObject *form = g_mime_parser_construct_part(parser, options);
unsigned status = 400U;
if (!warned && GMIME_IS_MULTIPART(form) &&
g_mime_content_type_is_type(g_mime_object_get_content_type(form),
"multipart", "form-data") &&
g_mime_multipart_get_count(GMIME_MULTIPART(form)) == 1) {
GMimeObject *item = g_mime_multipart_get_part(GMIME_MULTIPART(form), 0);
const char *disposition = g_mime_object_get_disposition(item);
const char *field =
g_mime_object_get_content_disposition_parameter(item, "name");
if (GMIME_IS_PART(item) && disposition != NULL && field != NULL &&
strcasecmp(disposition, "form-data") == 0 &&
strcmp(field, "file") == 0 &&
g_mime_object_get_header(item, "Content-Transfer-Encoding") == NULL) {
const char *filename = g_mime_part_get_filename(GMIME_PART(item));
GMimeDataWrapper *content = g_mime_part_get_content(GMIME_PART(item));
if (filename != NULL && filename[0] != '\0' && content != NULL) {
GMimeStream *output = g_mime_stream_mem_new();
if (g_mime_data_wrapper_write_to_stream(content, output) >= 0) {
const GByteArray *file =
g_mime_stream_mem_get_byte_array(GMIME_STREAM_MEM(output));
if (file->len > FILE_LIMIT) {
status = 413U;
} else {
upload_t upload = {0};
begin(&upload, (coakka_http_host_exchange_t){0});
append(&upload, file->data, file->len);
*saved = upload.size;
status = finish(&upload, "uploads/multipart.bin");
discard(&upload);
}
}
g_object_unref(output);
}
}
}
if (form != NULL) {
g_object_unref(form);
}
g_mime_parser_options_free(options);
g_object_unref(parser);
g_object_unref(input);
g_byte_array_unref(message);
return status;
}
static coakka_http_host_bytes_t
content_type(const coakka_http_host_request_event_t *event) {
const uint32_t count = coakka_http_host_request_header_count(event);
for (uint32_t index = 0U; index < count; ++index) {
coakka_http_host_header_t header = {0};
if (coakka_http_host_request_header(event, index, &header) &&
header.name.size == sizeof("content-type") - 1U &&
strncasecmp((const char *)header.name.data, "content-type",
header.name.size) == 0) {
return header.value;
}
}
return (coakka_http_host_bytes_t){0};
}
static upload_t *find_upload(upload_t *uploads,
coakka_http_host_exchange_t id) {
for (size_t index = 0; index < MAX_UPLOADS; ++index) {
upload_t *upload = &uploads[index];
if (upload->active && upload->id.slot == id.slot &&
upload->id.generation == id.generation) {
return upload;
}
}
return NULL;
}
static bool check(coakka_http_host_status_t status, const char *step) {
if (status == COAKKA_HTTP_HOST_OK) {
return true;
}
fprintf(stderr, "%s: %s\n", step, coakka_http_host_status_name(status));
return false;
}
static bool take_upload(coakka_http_host_service_t *service,
upload_t *uploads) {
coakka_http_host_request_event_t event;
coakka_http_host_request_event_init(&event);
const coakka_http_host_status_t received =
coakka_http_host_take_request(service, 500U, &event);
if (received == COAKKA_HTTP_HOST_TIMEOUT) {
return true;
}
if (!check(received, "read event")) {
return false;
}
const coakka_http_host_exchange_t id = event.exchange;
const char *name = "raw.bin";
size_t saved = 0U;
unsigned status = 0U;
upload_t *upload = find_upload(uploads, id);
if (event.kind == COAKKA_HTTP_HOST_REQUEST) {
if (coakka_http_host_request_route_id(&event) == FORM_ROUTE) {
name = "multipart.bin";
status = parse_form(content_type(&event),
coakka_http_host_request_body(&event), &saved);
} else {
for (size_t index = 0; index < MAX_UPLOADS; ++index) {
if (!uploads[index].active) {
begin(&uploads[index], id);
break;
}
}
}
} else if (event.kind == COAKKA_HTTP_HOST_REQUEST_DATA && upload != NULL) {
append(upload, event.data.data, event.data.size);
} else if (event.kind == COAKKA_HTTP_HOST_REQUEST_END) {
if (upload == NULL) {
status = 503U;
} else {
saved = upload->size;
status = finish(upload, "uploads/raw.bin");
discard(upload);
}
} else if ((event.kind == COAKKA_HTTP_HOST_REQUEST_CANCELLED ||
event.kind == COAKKA_HTTP_HOST_REQUEST_TERMINAL) &&
upload != NULL) {
discard(upload);
}
// No view into Core-owned event storage survives this release.
if (!check(coakka_http_host_release_request(service, &event),
"release event")) {
return false;
}
if (status != 0U) {
char message[80];
if (status == 201U) {
snprintf(message, sizeof(message), "saved %s (%zu bytes)\n", name, saved);
} else {
const char *error = status == 413U ? "file exceeds 32 KiB\n"
: status == 400U
? "expected one complete file field\n"
: "cannot save upload\n";
snprintf(message, sizeof(message), "%s", error);
}
coakka_http_host_response_t response;
coakka_http_host_response_init(&response);
response.status_code = status;
response.body = bytes(message);
// The peer may have disconnected after a complete input was received.
// Log a rejected response without shutting down the lab.
(void)check(coakka_http_host_respond(service, id, &response), "respond");
}
return true;
}
static bool drain(coakka_http_host_service_t *service, upload_t *uploads) {
if (!check(coakka_http_host_service_begin_drain(service), "begin drain")) {
return false;
}
// Keep releasing events as Core finishes in-flight work.
for (;;) {
coakka_http_host_drain_state_t state = COAKKA_HTTP_HOST_DRAIN_NOT_STARTED;
const coakka_http_host_status_t status =
coakka_http_host_service_wait_drained(service, 0U, &state);
if (status != COAKKA_HTTP_HOST_TIMEOUT ||
state != COAKKA_HTTP_HOST_DRAIN_PENDING) {
return check(status, "finish drain");
}
if (!take_upload(service, uploads)) {
return false;
}
}
}
int run_upload_lab(void) {
if (mkdir("uploads", 0700) != 0 && errno != EEXIST) {
perror("create uploads");
return EXIT_FAILURE;
}
coakka_http_host_configuration_t config;
coakka_http_host_configuration_init(&config);
config.bind_address = bytes("127.0.0.1");
config.port = 8080;
config.limits.max_request_body_bytes = FORM_LIMIT;
config.limits.drain_timeout_ms = 2000U;
config.limits.stop_timeout_ms = 4000U;
coakka_http_host_route_t routes[2];
for (size_t index = 0; index < 2; ++index) {
coakka_http_host_route_init(&routes[index]);
routes[index].route_id = index + 1U;
routes[index].handler_binding_id = index + 1U;
routes[index].method = bytes("POST");
}
routes[0].encoded_path_pattern = bytes("/upload/raw");
routes[0].flags |= COAKKA_HTTP_HOST_ROUTE_STREAMING_REQUEST;
routes[1].encoded_path_pattern = bytes("/upload/multipart");
coakka_http_host_service_t *service = NULL;
uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
if (!check(coakka_http_host_service_create(&config, routes, 2U, &service,
&failed_route),
"create service")) {
return EXIT_FAILURE;
}
g_mime_init();
coakka_http_host_issue_t issue;
coakka_http_host_issue_init(&issue);
bool running =
check(coakka_http_host_service_start(service, &issue), "start");
upload_t uploads[MAX_UPLOADS] = {0};
if (running) {
puts("Listening on http://127.0.0.1:8080; press Enter to stop.");
fflush(stdout);
struct pollfd input = {.fd = STDIN_FILENO, .events = POLLIN};
while (running) {
const int ready = poll(&input, 1U, 0);
if (ready > 0) {
break; // Enter or EOF; the same reader will finish draining events.
}
if (ready < 0 && errno != EINTR) {
perror("read stop input");
running = false;
break;
}
running = take_upload(service, uploads);
}
if (running) {
running = drain(service, uploads);
}
}
for (size_t index = 0; index < MAX_UPLOADS; ++index) {
discard(&uploads[index]);
}
const bool closed = check(coakka_http_host_service_stop(service), "stop");
const bool destroyed =
check(coakka_http_host_service_destroy(&service), "destroy");
g_mime_shutdown();
return running && closed && destroyed ? EXIT_SUCCESS : EXIT_FAILURE;
}
#include "upload.h"
int main(void) { return run_upload_lab(); }
#include "upload.h"
// The C ABI works unchanged inside a C++ application.
int main() { return run_upload_lab(); }
cmake -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build build./build/upload-c./build/upload-cppChạy một bản mỗi lần. Nhấn Enter trong terminal của server để dừng.
Go · 2.3.2
Cài gói chính thức. Lưu mã thành upload.go trong thư mục mới.
upload.go
package main
import (
"bytes"
"errors"
"io"
"log"
"mime"
"mime/multipart"
"os"
"path/filepath"
"strconv"
coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)
const (
formLimit = 64 * 1024
fileLimit = 32 * 1024
)
var errTooLarge = errors.New("file exceeds 32 KiB")
// Copy only the accepted bytes. Reading one extra byte distinguishes EOF from
// a file that exceeds the limit.
func copyFile(output io.Writer, input io.Reader) (int64, error) {
count, err := io.Copy(output, io.LimitReader(input, fileLimit))
if err != nil {
return 0, err
}
var extra [1]byte
n, err := io.ReadFull(input, extra[:])
if n != 0 {
// Let a small oversized upload reach EOF before replying. This
// discards at most 32 KiB more and never writes it to disk.
_, _ = io.Copy(io.Discard, io.LimitReader(input, formLimit-fileLimit))
return 0, errTooLarge
}
if err != io.EOF {
return 0, err
}
return count, nil
}
func store(input io.Reader, destination string) (coakkahttp.Response, error) {
file, err := os.CreateTemp("uploads", "incoming-*.part")
if err != nil {
return coakkahttp.Text(500, "cannot open upload\n")
}
defer os.Remove(file.Name()) // After rename the temporary name no longer exists.
count, readErr := copyFile(file, input)
closeErr := file.Close()
if errors.Is(readErr, errTooLarge) {
return coakkahttp.Text(413, "file exceeds 32 KiB\n")
}
if readErr != nil || closeErr != nil {
return coakkahttp.Text(400, "upload did not complete\n")
}
if err := os.Rename(file.Name(), filepath.Join("uploads", destination)); err != nil {
return coakkahttp.Text(500, "cannot save upload\n")
}
return coakkahttp.Text(201, "saved "+destination+" ("+strconv.FormatInt(count, 10)+" bytes)\n")
}
func raw(request *coakkahttp.Request) (coakkahttp.Response, error) {
return store(request.Body, "raw.bin")
}
func form(request *coakkahttp.Request) (coakkahttp.Response, error) {
contentType, _ := request.Headers.Get("Content-Type")
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil || mediaType != "multipart/form-data" || params["boundary"] == "" {
return coakkahttp.Text(400, "expected one file field\n")
}
reader := multipart.NewReader(request.Body, params["boundary"])
part, err := reader.NextRawPart()
if err != nil || part.FormName() != "file" || part.FileName() == "" ||
part.Header.Get("Content-Transfer-Encoding") != "" {
return coakkahttp.Text(400, "expected one file field\n")
}
data, err := io.ReadAll(io.LimitReader(part, fileLimit+1))
if len(data) > fileLimit {
return coakkahttp.Text(413, "file exceeds 32 KiB\n")
}
if err != nil {
return coakkahttp.Text(400, "invalid multipart body\n")
}
if _, err := reader.NextRawPart(); err != io.EOF {
return coakkahttp.Text(400, "expected one complete file field\n")
}
return store(bytes.NewReader(data), "multipart.bin")
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() (err error) {
if err := os.MkdirAll("uploads", 0700); err != nil {
return err
}
limits := coakkahttp.DefaultLimits()
limits.MaxRequestBodyBytes = formLimit
// Reserve room for the lab's burst of 4 KiB chunks while the handler writes.
limits.RequestStreamMaxRetainedItems = 16
service, err := coakkahttp.NewBuilder().
Listen("127.0.0.1", 8080).
Limits(limits).
PostStream("/upload/raw", raw).
Post("/upload/multipart", form).
Start()
if err != nil {
return err
}
defer func() { err = errors.Join(err, service.Close()) }()
log.Print("Listening on http://127.0.0.1:8080; press Enter to stop.")
_, _ = os.Stdin.Read(make([]byte, 1))
return nil
}
go mod init example.com/coakka-upload
go get github.com/phuong-tran/coakka-http-runtime-go/[email protected]
export CGO_CFLAGS="-I$COAKKA_HTTP_SDK/include"
export CGO_LDFLAGS="-L$COAKKA_HTTP_SDK/lib -Wl,-rpath,$COAKKA_HTTP_SDK/lib"
go run upload.goVí dụ Go cho phép 16 phần đang chờ đọc, đủ để lượt kiểm tra gửi dồn không làm đầy hàng đợi trước khi handler kịp ghi tệp.
Java / Kotlin · JVM 2.3.2
Cài gói chính thức. Dùng JDK 17 trở lên và tạo thư mục dự án riêng. Lưu các tệp đúng đường dẫn. Cả Java và Kotlin dùng UploadFiles.java để xử lý tệp; thư viện đọc form được cài từ Maven Central.
Mã nguồn Java và Kotlin
package study;
import coakka.http.Request;
import coakka.http.Response;
import coakka.http.Responses;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.ContentDisposition;
import jakarta.mail.internet.ContentType;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.util.ByteArrayDataSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public final class UploadFiles {
static final long FORM_LIMIT = 64 * 1024;
private static final int FILE_LIMIT = 32 * 1024;
private static final Path UPLOADS = Paths.get("uploads");
private UploadFiles() {}
static void prepare() throws IOException {
Files.createDirectories(UPLOADS);
}
static Response raw(Request request) {
return store(request.getBody(), "raw.bin");
}
static Response form(Request request) {
byte[] data;
try {
String contentType = request.getHeaders().get("content-type");
if (contentType == null) {
return Responses.text("expected multipart/form-data\n", 400);
}
ContentType type = new ContentType(contentType);
if (!type.match("multipart/form-data") || type.getParameter("boundary") == null) {
return Responses.text("expected multipart/form-data with a boundary\n", 400);
}
MimeMultipart form = new MimeMultipart(
new ByteArrayDataSource(request.bytes(), contentType));
if (form.getCount() != 1 || !form.isComplete()) {
return Responses.text("expected one complete file field\n", 400);
}
MimeBodyPart part = (MimeBodyPart) form.getBodyPart(0);
String rawDisposition = part.getHeader("Content-Disposition", null);
if (rawDisposition == null) {
return Responses.text("expected one file field\n", 400);
}
ContentDisposition disposition = new ContentDisposition(rawDisposition);
String filename = disposition.getParameter("filename");
if (!"form-data".equalsIgnoreCase(disposition.getDisposition())
|| !"file".equals(disposition.getParameter("name"))
|| filename == null || filename.isEmpty()
|| part.getHeader("Content-Transfer-Encoding") != null
|| part.isMimeType("multipart/*")) {
return Responses.text("expected one file field\n", 400);
}
try (InputStream input = part.getRawInputStream()) {
// Core has bounded the complete form; the parser has validated it.
byte[] buffer = new byte[FILE_LIMIT + 1];
int count = 0;
while (count < buffer.length) {
int read = input.read(buffer, count, buffer.length - count);
if (read < 0) {
break;
}
count += read;
}
if (count > FILE_LIMIT) {
return Responses.text("file exceeds 32 KiB\n", 413);
}
data = java.util.Arrays.copyOf(buffer, count);
}
} catch (IOException | MessagingException error) {
return Responses.text("invalid multipart body\n", 400);
}
return store(new ByteArrayInputStream(data), "multipart.bin");
}
private static Response store(InputStream input, String name) {
Path temporary = null;
try {
temporary = Files.createTempFile(UPLOADS, "incoming-", ".part");
int count = 0;
try (OutputStream output = Files.newOutputStream(temporary)) {
byte[] buffer = new byte[4096];
int read;
while ((read = input.read(buffer)) != -1) {
if (read > FILE_LIMIT - count) {
return Responses.text("file exceeds 32 KiB\n", 413);
}
output.write(buffer, 0, read);
count += read;
}
}
Files.move(temporary, UPLOADS.resolve(name),
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
return Responses.text("saved " + name + " (" + count + " bytes)\n", 201);
} catch (IOException error) {
System.err.println("Upload did not complete: " + error);
return Responses.text("upload did not complete\n", 400);
} finally {
if (temporary != null) {
try {
Files.deleteIfExists(temporary);
} catch (IOException error) {
System.err.println("Cannot remove temporary upload: " + error);
}
}
}
}
}
package study;
import coakka.http.Limits;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
public final class JavaUpload {
private JavaUpload() {}
public static void main(String[] args) throws Exception {
UploadFiles.prepare();
// The fifth argument bounds buffered bodies; zero keeps other Core defaults.
Limits limits = new Limits(0, 0, 0, 0, UploadFiles.FORM_LIMIT);
Service service = new ServiceBuilder()
.listen("127.0.0.1", 8080)
.limits(limits)
.postStream("/upload/raw", UploadFiles::raw)
.post("/upload/multipart", UploadFiles::form)
.start();
try {
System.out.println("Listening on http://127.0.0.1:8080; press Enter to stop.");
System.in.read();
} finally {
service.close();
}
}
}
package study
import coakka.http.Limits
import coakka.http.ServiceBuilder
fun main() {
UploadFiles.prepare()
val service = ServiceBuilder()
.listen(host = "127.0.0.1", port = 8080)
.limits(Limits(maxRequestBodyBytes = UploadFiles.FORM_LIMIT))
.postStream(pattern = "/upload/raw") { request -> UploadFiles.raw(request) }
.post(pattern = "/upload/multipart") { request -> UploadFiles.form(request) }
.start()
try {
println("Listening on http://127.0.0.1:8080; press Enter to stop.")
readlnOrNull()
} finally {
service.close()
}
}
Các lệnh sau dành cho Pi ARM64. Trên macOS ARM64 có thể bỏ tùy chọn linux-aarch64.
Maven
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example.coakka</groupId>
<artifactId>coakka-http-upload-lab</artifactId>
<version>1.0.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>17</maven.compiler.release>
<kotlin.version>2.3.10</kotlin.version>
<coakka.version>2.3.2</coakka.version>
<coakka.target>macos-aarch64</coakka.target>
</properties>
<dependencies>
<dependency>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>coakka-http-runtime-jvm</artifactId>
<version>${coakka.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-mail</artifactId>
<version>2.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile-kotlin</id>
<phase>process-sources</phase>
<goals><goal>compile</goal></goals>
<configuration>
<jvmTarget>17</jvmTarget>
<args><arg>-Werror</arg><arg>-Xjdk-release=17</arg></args>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<release>17</release>
<showWarnings>true</showWarnings>
<compilerArgs><arg>-Xlint:all</arg><arg>-Werror</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.8.1</version>
<executions>
<execution>
<id>unpack-coakka-native</id>
<phase>process-resources</phase>
<goals><goal>unpack</goal></goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>coakka-http-runtime-jvm</artifactId>
<version>${coakka.version}</version>
<classifier>${coakka.target}</classifier>
<type>zip</type>
<outputDirectory>${project.build.directory}/coakka-native</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
mvn -q -Dcoakka.target=linux-aarch64 compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txtjava -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaUploadjava -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinUploadKtGradle
plugins {
kotlin("jvm") version "2.3.10"
}
repositories {
mavenCentral()
}
val coakkaTarget = providers.gradleProperty("coakkaTarget")
.orElse("macos-aarch64")
val coakkaNative by configurations.creating
dependencies {
implementation("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2")
implementation("org.eclipse.angus:angus-mail:2.0.5")
coakkaNative("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2:${coakkaTarget.get()}@zip")
}
val unpackCoakkaNative by tasks.registering(Sync::class) {
from(coakkaNative.map(::zipTree))
into(layout.buildDirectory.dir("coakka-native"))
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
freeCompilerArgs.add("-Xjdk-release=17")
allWarningsAsErrors.set(true)
}
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(17)
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}
tasks.register<JavaExec>("runJavaUpload") {
dependsOn(unpackCoakkaNative)
classpath = sourceSets["main"].runtimeClasspath
mainClass.set("study.JavaUpload")
standardInput = System.`in`
jvmArgs("-Djava.library.path=${layout.buildDirectory.dir("coakka-native/native").get().asFile}")
}
tasks.register<JavaExec>("runKotlinUpload") {
dependsOn(unpackCoakkaNative)
classpath = sourceSets["main"].runtimeClasspath
mainClass.set("study.KotlinUploadKt")
standardInput = System.`in`
jvmArgs("-Djava.library.path=${layout.buildDirectory.dir("coakka-native/native").get().asFile}")
}
rootProject.name = "coakka-http-upload-lab"
gradle -PcoakkaTarget=linux-aarch64 runJavaUploadgradle -PcoakkaTarget=linux-aarch64 runKotlinUploadPython · 2.3.2
Cài gói chính thức. Lưu mã thành upload.py.
upload.py
import io
import os
import tempfile
from email import policy
from email.parser import BytesParser
from pathlib import Path
from typing import BinaryIO
from coakka_http import Builder, Limits, Request, Response
FORM_LIMIT = 64 * 1024
FILE_LIMIT = 32 * 1024
UPLOADS = Path("uploads")
def store(source: BinaryIO, name: str) -> Response:
temporary: Path | None = None
try:
with tempfile.NamedTemporaryFile(
dir=UPLOADS, prefix="incoming-", suffix=".part", delete=False
) as output:
temporary = Path(output.name)
count = 0
while True:
chunk = source.read(4096)
if not chunk:
break
count += len(chunk)
if count > FILE_LIMIT:
return Response.text("file exceeds 32 KiB\n", status=413)
output.write(chunk)
os.replace(temporary, UPLOADS / name)
return Response.text(f"saved {name} ({count} bytes)\n", status=201)
except OSError as error:
print(f"Upload did not complete: {error}", flush=True)
return Response.text("upload did not complete\n", status=400)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def raw(request: Request) -> Response:
return store(request.body_reader, "raw.bin")
def form(request: Request) -> Response:
content_type = request.headers.get("content-type") or ""
if "\r" in content_type or "\n" in content_type:
return Response.text("invalid content type\n", status=400)
try:
message = BytesParser(policy=policy.default).parsebytes(
b"Content-Type: " + content_type.encode("ascii") + b"\r\n\r\n" + request.body
)
except (ValueError, RecursionError):
return Response.text("invalid multipart body\n", status=400)
parts = list(message.iter_parts())
if (
message.get_content_type() != "multipart/form-data"
or message.defects
or len(parts) != 1
):
return Response.text("expected one complete file field\n", status=400)
part = parts[0]
if (
part.defects
or part.is_multipart()
or part.get_content_disposition() != "form-data"
or part.get_param("name", header="content-disposition") != "file"
or not part.get_filename()
or part.get("Content-Transfer-Encoding") is not None
):
return Response.text("expected one file field\n", status=400)
content = part.get_payload(decode=True)
if not isinstance(content, bytes):
return Response.text("invalid file field\n", status=400)
if len(content) > FILE_LIMIT:
return Response.text("file exceeds 32 KiB\n", status=413)
return store(io.BytesIO(content), "multipart.bin")
def main() -> None:
UPLOADS.mkdir(mode=0o700, exist_ok=True)
service = (
Builder()
.listen("127.0.0.1", 8080)
.limits(
Limits(max_request_body_bytes=FORM_LIMIT, request_stream_max_retained_items=16)
)
.post_stream("/upload/raw", raw)
.post("/upload/multipart", form)
.start()
)
with service:
print("Listening on http://127.0.0.1:8080; press Enter to stop.", flush=True)
input()
if __name__ == "__main__":
main()
python3 -m venv .venv
. .venv/bin/activate
python -m pip install coakka-http-runtime-python==2.3.2
python upload.pyNode.js / Bun · 2.3.2
Dùng chung upload.mjs cho Node.js và Bun. Chọn đúng gói theo môi trường chạy.
upload.mjs
import { randomUUID } from "node:crypto";
import { closeSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";
// The same example runs under Node.js and Bun with their respective packages.
const packageName = process.versions.bun
? "coakka-http-runtime-bun"
: "coakka-http-runtime-node";
const { Builder, Limits, Response } = await import(packageName);
const FORM_LIMIT = 64 * 1024;
const FILE_LIMIT = 32 * 1024;
const pending = new Map();
mkdirSync("uploads", { mode: 0o700, recursive: true });
function begin() {
const path = `uploads/incoming-${randomUUID()}.part`;
return { path, fd: openSync(path, "wx", 0o600), count: 0, tooLarge: false };
}
function discard(upload) {
try {
if (upload.fd !== undefined) {
const fd = upload.fd;
upload.fd = undefined;
closeSync(fd);
}
} finally {
rmSync(upload.path, { force: true });
}
}
function append(upload, chunk) {
if (upload.tooLarge || chunk.length > FILE_LIMIT - upload.count) {
upload.tooLarge = true;
return;
}
for (let offset = 0; offset < chunk.length;) {
const count = writeSync(upload.fd, chunk, offset, chunk.length - offset);
if (count === 0) throw new Error("upload write made no progress");
offset += count;
}
upload.count += chunk.length;
}
function finish(upload, name) {
if (upload.tooLarge) {
return Response.text("file exceeds 32 KiB\n", { status: 413 });
}
const fd = upload.fd;
upload.fd = undefined;
closeSync(fd);
renameSync(upload.path, `uploads/${name}`);
return Response.text(`saved ${name} (${upload.count} bytes)\n`, { status: 201 });
}
function raw(event) {
const key = `${event.id.slot}:${event.id.generation}`;
if (event.kind === "start") {
pending.set(key, begin());
return;
}
const upload = pending.get(key);
if (!upload) return;
if (event.kind === "data") {
append(upload, event.data);
} else if (event.kind === "end") {
return finish(upload, "raw.bin");
} else if (event.kind === "dispose") {
pending.delete(key);
discard(upload);
}
}
async function form(request) {
const contentType = request.headers.get("content-type");
if (!contentType?.toLowerCase().startsWith("multipart/form-data;")) {
return Response.text("expected one file field\n", { status: 400 });
}
let fields;
try {
fields = await new globalThis.Response(request.bytes(), {
headers: { "Content-Type": contentType },
}).formData();
} catch {
return Response.text("invalid multipart body\n", { status: 400 });
}
const entries = [...fields];
const file = fields.get("file");
if (entries.length !== 1 || !file || typeof file === "string" || !file.name) {
return Response.text("expected one file field\n", { status: 400 });
}
if (file.size > FILE_LIMIT) {
return Response.text("file exceeds 32 KiB\n", { status: 413 });
}
const upload = begin();
try {
append(upload, new Uint8Array(await file.arrayBuffer()));
return finish(upload, "multipart.bin");
} finally {
discard(upload);
}
}
const service = new Builder()
.listen("127.0.0.1", 8080)
.limits(new Limits({ maxRequestBodyBytes: FORM_LIMIT }))
.postStream("/upload/raw", raw)
.post("/upload/multipart", form)
.start();
console.log("Listening on http://127.0.0.1:8080; press Enter to stop.");
try {
for await (const chunk of process.stdin) {
if (chunk.length > 0) break;
}
} finally {
await service.close();
}
Node.js · npm
npm install --save-exact [email protected]
node upload.mjsBun
bun add --exact [email protected]
bun upload.mjsBài 01
Upload trực tiếp
Khi client gửi application/octet-stream, handler ghi từng phần vào tệp tạm. Giới hạn lưu là 32 KiB (32.768 byte). Chỉ đổi tên sang raw.bin sau khi đọc hết và đóng tệp thành công.
printf 'hello upload\n' > demo.bin
curl --silent --show-error --include \
-H 'Content-Type: application/octet-stream' \
--data-binary @demo.bin http://127.0.0.1:8080/upload/raw
cmp demo.bin uploads/raw.binKết quả đúng: Phản hồi 201 Created; cmp không in gì nếu tệp lưu trùng với tệp gửi. saved raw.bin (13 bytes).
Thử tệp vượt 32 KiB
head -c 32769 /dev/zero > too-large.bin
curl --silent --show-error --include \
-H 'Content-Type: application/octet-stream' \
--data-binary @too-large.bin http://127.0.0.1:8080/upload/rawMong đợi 413. Tệp đã lưu trước đó vẫn giữ nguyên; request này không để lại tệp tạm.
Bài 02
Upload multipart
CoAkka HTTP Runtime giới hạn 64 KiB (65.536 byte) cho toàn bộ body, gồm tệp, header của từng phần và dấu phân cách. Handler kiểm tra có đúng một trường tệp tên file và tệp không quá 32 KiB. Tên do client gửi không được dùng làm đường dẫn lưu.
printf 'hello upload\n' > demo.bin
curl --silent --show-error --include \
-F '[email protected]' http://127.0.0.1:8080/upload/multipart
cmp demo.bin uploads/multipart.binKết quả đúng: Phản hồi 201 Created; cmp không in gì nếu tệp lưu trùng với tệp gửi. saved multipart.bin (13 bytes).
Thử vượt giới hạn của cả form
head -c 65536 /dev/zero > form-too-large.bin
curl --silent --show-error --include \
-F '[email protected]' http://127.0.0.1:8080/upload/multipartMong đợi 413: riêng tệp đã chạm 64 KiB, phần bao quanh làm body vượt giới hạn. Một form đủ nhỏ nhưng có tệp vượt 32 KiB cũng nhận 413; thiếu trường file hoặc form sai cấu trúc nhận 400.
Thử ngắt kết nối
Dùng thư mục mới, hoặc tự chuyển raw.bin và multipart.bin đã lưu sang chỗ khác trước khi thử. Lưu check_upload.py cạnh thư mục uploads/. Script chủ động đóng kết nối trước khi gửi hết nội dung đã khai báo; không cần đoán thời điểm để nhấn Ctrl+C.
check_upload.py
"""Loopback exercise: success, size limits, and a client that disconnects."""
import argparse
import http.client
import socket
import time
from pathlib import Path
UPLOADS = Path("uploads")
RAW = ("raw", "application/octet-stream", "raw.bin")
BOUNDARY = "coakka-upload-lab"
FORM = ("multipart", f"multipart/form-data; boundary={BOUNDARY}", "multipart.bin")
FILE_LIMIT = 32 * 1024
def form(data: bytes, *, complete: bool = True, field: str = "file") -> bytes:
start = (
f"--{BOUNDARY}\r\n"
f'Content-Disposition: form-data; name="{field}"; filename="../../demo.bin"\r\n'
"Content-Type: application/octet-stream\r\n\r\n"
).encode("ascii")
end = f"\r\n--{BOUNDARY}--\r\n".encode("ascii") if complete else b""
return start + data + end
def post(route: tuple[str, str, str], data: bytes, expected: int, *, chunked: bool = False) -> bytes:
path, content_type, _ = route
connection = http.client.HTTPConnection("127.0.0.1", 8080, timeout=8)
try:
body = (data[i:i + 4096] for i in range(0, len(data), 4096)) if chunked else data
connection.request(
"POST", f"/upload/{path}", body, {"Content-Type": content_type},
encode_chunked=chunked,
)
response = connection.getresponse()
body = response.read()
if response.status != expected:
raise RuntimeError(f"{path}: expected {expected}, got {response.status}: {body!r}")
return body
finally:
connection.close()
def wait_for(predicate, message: str) -> None:
deadline = time.monotonic() + 6
while not predicate():
if time.monotonic() >= deadline:
raise RuntimeError(message)
time.sleep(0.02)
def pending() -> list[Path]:
return list(UPLOADS.glob("incoming-*"))
def abort(route: tuple[str, str, str], initial: bytes, *, expect_partial: bool) -> None:
path, content_type, _ = route
with socket.create_connection(("127.0.0.1", 8080), timeout=5) as client:
headers = (
f"POST /upload/{path} HTTP/1.1\r\n"
"Host: 127.0.0.1:8080\r\n"
f"Content-Type: {content_type}\r\n"
f"Content-Length: {len(initial) + 8192}\r\n\r\n"
)
client.sendall(headers.encode("ascii") + initial)
if expect_partial:
wait_for(lambda: any(f.stat().st_size for f in pending()), "no partial file was written")
print("raw: saw data on disk before disconnect")
else:
# The incomplete HTTP body cannot reach the buffered form handler.
until = time.monotonic() + 0.4
while time.monotonic() < until:
if pending():
raise RuntimeError("incomplete multipart created a temporary file")
time.sleep(0.02)
# Closing without sending the remaining Content-Length simulates a
# client that disappears in the middle of the upload.
wait_for(lambda: not pending(), f"{path}: partial file was not removed")
print(f"{path}: disconnect left no temporary file")
def exercise(route: tuple[str, str, str]) -> None:
path, _, name = route
wire = (lambda data: data) if path == "raw" else form
data = bytes(range(256)) * (FILE_LIMIT // 256)
target = UPLOADS / name
if target.exists() or pending():
raise RuntimeError("start in a clean lab directory")
partial = b"x" * 12288
if path == "multipart":
partial = form(partial, complete=False)
abort(route, partial, expect_partial=path == "raw")
if target.exists():
raise RuntimeError("disconnect published an incomplete file")
if path == "multipart":
post(route, form(b"hi", complete=False), 400)
post(route, form(b"hi", field="other"), 400)
post(route, wire(b"x" * (64 * 1024)), 413)
post(route, wire(data + b"x"), 413)
if pending() or target.exists():
raise RuntimeError("a refused request left a file")
result = post(route, wire(data), 201)
if result != f"saved {name} ({len(data)} bytes)\n".encode() or target.read_bytes() != data:
raise RuntimeError("saved file differs from the upload")
wait_for(lambda: not pending(), "successful request left a temporary file")
if path == "raw":
post(route, data + b"x", 413, chunked=True)
if target.read_bytes() != data or pending():
raise RuntimeError("a refused request changed a saved file or left a temporary file")
print(f"{path}: 201, {len(data)} exact bytes; oversize request returned 413")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("mode", choices=("raw", "multipart", "both"))
mode = parser.parse_args().mode
if mode in ("raw", "both"):
exercise(RAW)
if mode in ("multipart", "both"):
exercise(FORM)
if __name__ == "__main__":
main()
python3 check_upload.py raw
python3 check_upload.py multipart- Upload trực tiếp
- Script thấy
incoming-*có dữ liệu trước khi ngắt, rồi kiểm tra tệp biến mất. Server không tạoraw.bintừ request dở. - Upload multipart
- Handler nhận body đã hoàn chỉnh, nên form gửi dở chưa tạo tệp tạm hay
multipart.bin.
Sau đó script thử tệp quá cỡ, rồi gửi lại tệp đúng giới hạn và kiểm tra đủ 32.768 byte. Ngắt kết nối nghĩa là client không nhận được mã HTTP cho request đó.
Mỗi ngôn ngữ dọn tệp ở đâu?
- C / C++
- Xóa tệp tạm nếu nhận
REQUEST_CANCELLEDhoặc sự kiện kết thúc trước khi ghi xong. - Go, Java, Kotlin, Python
- Nếu đọc bị lỗi, bỏ qua bước đổi tên. Phần dọn dẹp trong
deferhoặcfinallysẽ xóa tệp tạm. - Node.js / Bun
- Mỗi request đã bắt đầu có sự kiện
dispose. Xóa tệp tạm và dọn trạng thái ở đây; không gửi phản hồi từ sự kiện này.
Đây là bài thực hành chạy trên máy cá nhân. Server đổi tên trong cùng thư mục sau khi ghi xong; request thành công tiếp theo ghi đè tệp của bài. Nếu cả tiến trình bị tắt đột ngột, mã dọn tệp không chạy: khi khởi động lại, chỉ xóa các tệp incoming-* còn sót sau khi chắc chắn server cũ đã dừng.