summaryrefslogtreecommitdiffhomepage
path: root/examples/rust/upload-reflector/src/lib.rs
blob: 01138b0de944bf1d1d2a5cb77949143c5e5a4acc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* SPDX-License-Identifier: Apache-2.0 */

/*
 * Copyright (C) Andrew Clayton
 * Copyright (C) Timo Stark
 * Copyright (C) F5, Inc.
 */

use unit_wasm::rusty::*;

use std::ptr::null_mut;

static mut CTX: luw_ctx_t = UWR_CTX_INITIALIZER();

static mut TOTAL_RESPONSE_SENT: usize = 0;

// Buffer of some size to store the copy of the request
static mut REQUEST_BUF: *mut u8 = null_mut();

#[no_mangle]
pub extern "C" fn uwr_response_end_handler() {
    unsafe {
        TOTAL_RESPONSE_SENT = 0;
    }
}

#[no_mangle]
pub extern "C" fn uwr_request_end_handler() {
    unsafe {
        if REQUEST_BUF.is_null() {
            return;
        }

        uwr_free(REQUEST_BUF);
        REQUEST_BUF = null_mut();
    }
}

pub fn upload_reflector(ctx: *mut luw_ctx_t) -> i32 {
    let write_bytes: usize;

    // Send headers
    if unsafe { TOTAL_RESPONSE_SENT == 0 } {
        let defct = "application/octet-stream";
        let mut ct = uwr_http_hdr_get_value(ctx, "Content-Type");

        if ct.is_empty() {
            ct = defct;
        }

        uwr_http_init_headers(ctx, 2, 0);
        uwr_http_add_header(ctx, 0, "Content-Type", ct);
        uwr_http_add_header(
            ctx,
            1,
            "Content-Length",
            &format!("{}", uwr_get_http_content_len(ctx)),
        );
        uwr_http_send_headers(ctx);
    }

    unsafe {
        write_bytes = uwr_mem_fill_buf_from_req(ctx, TOTAL_RESPONSE_SENT);
        TOTAL_RESPONSE_SENT += write_bytes;
    }

    uwr_http_send_response(ctx);

    if unsafe { TOTAL_RESPONSE_SENT == uwr_get_http_content_len(ctx) } {
        // Tell Unit no more data to send
        uwr_http_response_end();
    }

    return 0;
}

#[no_mangle]
pub extern "C" fn uwr_request_handler(addr: *mut u8) -> i32 {
    let ctx: *mut luw_ctx_t = unsafe { &mut CTX };

    if unsafe { REQUEST_BUF.is_null() } {
        uwr_init_ctx(ctx, addr, 0 /* Response offset */);
        /*
         * Take a copy of the request and use that, we do this
         * in APPEND mode so we can build up request_buf from
         * multiple requests.
         *
         * Just allocate memory for the total amount of data we
         * expect to get, this includes the request structure
         * itself as well as any body content.
         */
        uwr_set_req_buf(
            ctx,
            unsafe { &mut REQUEST_BUF },
            LUW_SRB_APPEND | LUW_SRB_ALLOC | LUW_SRB_FULL_SIZE,
        );
    } else {
        uwr_req_buf_append(ctx, addr);
    }

    upload_reflector(ctx);

    return 0;
}