Study · Advanced · HTTP/1.1

File upload exercises

Send a raw file first, then try a multipart form. See when the server starts writing and what happens when the client disconnects.

These labs send files from client to server. To return a stored file to a client, see file downloads and sendfile. For files over 8 MiB: upload in multiple requests.

Choose a language

Open a language panel, start the server in a fresh directory, then open a second terminal in the same directory. The example uses HTTP/1.1 on 127.0.0.1:8080 and writes into uploads/. Run one server at a time. Press Enter in its terminal when you finish.

C / C++ · SDK 2.3.0

Install the official package SDK 2.3.0. Install GMime and pkg-config for the form parser.

Install the form parser
Debian / Raspberry Pi OS
sudo apt install libgmime-3.0-dev pkg-config
macOS · Homebrew
brew install gmime pkgconf
C/C++ source

Save these 5 files in one project directory.

CMakeLists.txt
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()
upload.h
#ifndef COAKKA_PORTAL_UPLOAD_H
#define COAKKA_PORTAL_UPLOAD_H

#ifdef __cplusplus
extern "C" {
#endif

int run_upload_lab(void);

#ifdef __cplusplus
}
#endif
#endif
upload.c
#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;
}
main.c
#include "upload.h"

int main(void) { return run_upload_lab(); }
main.cpp
#include "upload.h"

// The C ABI works unchanged inside a C++ application.
int main() { return run_upload_lab(); }
CMake
cmake -S . -B build -DCMAKE_PREFIX_PATH="$COAKKA_HTTP_SDK"
cmake --build build
C
./build/upload-c
C++
./build/upload-cpp

Run one program at a time. Press Enter in the server terminal to stop.

Go · 2.3.2

Install the official package. Save the source as upload.go in a new directory.

upload.go
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
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.go

The Go example allows 16 pending stream items so the file writer can keep up with the short burst in the lab checker.

Java / Kotlin · JVM 2.3.2

Install the official package. Use JDK 17 or newer and a new project directory. Save each file at the path shown. Java and Kotlin share UploadFiles.java for file handling. The form parser comes from Maven Central.

Java and Kotlin source
src/main/java/study/UploadFiles.java
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);
                }
            }
        }
    }
}
src/main/java/study/JavaUpload.java
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();
        }
    }
}
src/main/kotlin/study/KotlinUpload.kt
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()
    }
}

The commands below target Pi ARM64. On macOS ARM64, omit the linux-aarch64 option.

Maven
pom.xml
<?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>
Maven
mvn -q -Dcoakka.target=linux-aarch64 compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
Java
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.JavaUpload
Kotlin
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.KotlinUploadKt
Gradle
build.gradle.kts
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}")
}
settings.gradle.kts
rootProject.name = "coakka-http-upload-lab"
Java
gradle -PcoakkaTarget=linux-aarch64 runJavaUpload
Kotlin
gradle -PcoakkaTarget=linux-aarch64 runKotlinUpload
Python · 2.3.2

Install the official package. Save the source as upload.py.

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()
Python
python3 -m venv .venv
. .venv/bin/activate
python -m pip install coakka-http-runtime-python==2.3.2
python upload.py
Node.js / Bun · 2.3.2

Node.js and Bun share upload.mjs. Choose the package for the host you run.

upload.mjs
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

Install the official package.

Node.js
npm install --save-exact [email protected]
node upload.mjs
Bun

Install the official package.

Bun
bun add --exact [email protected]
bun upload.mjs

Lab 01

Upload a raw file

For application/octet-stream, the handler writes each chunk to a temporary file. The file limit is 32 KiB (32,768 bytes). It renames the file to raw.bin only after the body ends and the file closes successfully.

Terminal
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.bin

Expected result: 201 Created; cmp prints nothing when the saved file matches the upload. saved raw.bin (13 bytes).

Try a file over 32 KiB
Terminal
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/raw

Expect 413. A previously saved file stays unchanged, and this request leaves no temporary file.

Lab 02

Upload a multipart form

CoAkka HTTP Runtime limits the entire buffered body to 64 KiB (65,536 bytes), including the file, part headers, and boundaries. The handler accepts exactly one file field named file, at most 32 KiB. The client-supplied filename never becomes a storage path.

Terminal
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.bin

Expected result: 201 Created; cmp prints nothing when the saved file matches the upload. saved multipart.bin (13 bytes).

Exceed the whole-form limit
Terminal
head -c 65536 /dev/zero > form-too-large.bin
curl --silent --show-error --include \
  -F '[email protected]' http://127.0.0.1:8080/upload/multipart

Expect 413: the file alone reaches 64 KiB, and the form adds overhead. A smaller form with a file over 32 KiB also returns 413. A missing file field or a malformed form returns 400.

Uploading a larger file? Try multipart streaming

Test a disconnect

Use a fresh directory, or move previously saved raw.bin and multipart.bin out of uploads/ first. Save check_upload.py next to uploads/. The script closes the connection before sending the declared body length, so there is no need to time a Ctrl+C.

check_upload.py
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()
Terminal
python3 check_upload.py raw
python3 check_upload.py multipart
Upload a raw file
The script sees data in an incoming-* file before disconnecting, then verifies that the file disappears. The interrupted request creates no raw.bin.
Upload a multipart form
The handler receives a complete body, so the interrupted form creates neither a temporary file nor multipart.bin.

The script then tries an oversized file, sends a valid file at the exact limit, and checks all 32,768 saved bytes. A client that disconnects cannot receive an HTTP status for that request.

Where each language cleans up
C / C++
Discard the temporary file on REQUEST_CANCELLED or a terminal event before the upload finishes.
Go, Java, Kotlin, Python
A read error skips the rename. The cleanup registered with defer or finally removes the temporary file.
Node.js / Bun
Each admitted stream has a dispose event. Delete the temporary file and release state there; do not respond from that event.

This is a local exercise. The server renames the file in the same directory once it is written; the next successful request replaces the previous file for that route. If the whole server process is killed, its cleanup cannot run. Remove leftover incoming-* files only after checking that the old server has stopped.