summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: cfdc4e7e3f9d988faf26ea298a09c356b4f8a976 (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
//! zhttpd is a very basic http server written in Zig, by ZachIR. It is single
//! threaded, and does not yet support every error code, nor does it support
//! TLS/SSL, but it does display web pages.

// Copyright (C) 2024 ZachIR
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

const std = @import("std");
const log = std.log.scoped(.server);

/// zhttpd relies on mime in addition to std, which is included as made by
/// andrewrk at https://github.com/andrewrk/mime.git
const mime = @import("mime/mime.zig");

/// The server has a hardcoded address and port of 127.0.0.1:8080
/// The path requested for a file has the limit of fs.MAX_PATH_BYTES, which is
/// the maxmimum length for a file path in the OS
/// The maximum file size is 1 << 21, aka (1 * 2^20), which is 2 MB.
const server_addr = "127.0.0.1";
const server_port = 8080;
const max_path_bytes = std.fs.MAX_PATH_BYTES;
const buffer_limit = 1 << 21;

/// readFiles() reads the file to a provided buffer, and returns the number of
/// bytes read.
/// readFiles() can fail from std.fmt.allocPrint(), std.fs.cwd().openFile(),
/// file.stat(), and file.readAll()
/// std.fmt.allocPrint() will return an AllocPrintError
/// std.fs.cwd().openFile() will return a File.OpenError
/// file.stat() will return a StatError
/// file.readAll() will return a ReadError
fn readFiles(target: []const u8, buffer: []u8) !usize {
    // fba_buffer is the maximum malloc size for this functiono, as it's using
    // a Fixed Buffer Allocator. It needs to be able to contain file_path,
    // which is max_path_bytes in size, twice over, because it may also get
    // allocPrint'ed to if the provided target is a directory.
    var fba_buffer: [max_path_bytes * 2]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&fba_buffer);
    const allocator = fba.allocator();

    // `target` is relative to the root of the http server; for now, it's
    // going to assume the root (/) is the current working directory.
    var file_path = try allocator.alloc(u8, max_path_bytes);
    defer allocator.free(file_path);
    var cwd_buffer = [_]u8{0} ** max_path_bytes;
    const cwd = try std.os.getcwd(&cwd_buffer);
    file_path = try std.fmt.allocPrint(allocator, "{s}{s}", .{ cwd, target });

    log.info("Loading file {s}...", .{file_path});
    // Determine if the requested file exists
    const file = try std.fs.cwd().openFile(file_path, .{});
    defer file.close();
    var stat = try file.stat();
    switch (stat.kind) {
        // If the path is a directory, it needs to get the file at
        // directory/index.html. This isn't technically the standard
        // (probably), but it's the assumption I will make for now.
        .directory => {
            if (std.mem.endsWith(u8, target, "/")) {
                file_path = try std.fmt.allocPrint(allocator, "{s}index.html", .{target});
            } else {
                file_path = try std.fmt.allocPrint(allocator, "{s}/index.html", .{target});
            }
            return readFiles(file_path, buffer);
        },
        // If it's a file then write all of the contents (up to buffer_limit
        // bytes) into the provided arg buffer, and return the number of bytes
        // written.
        .file => {
            return try file.readAll(buffer);
        },
        // Otherwise, it's an error I'm not going to handle.
        else => {
            return 0;
        },
    }
}

/// handleRequest() handles the requests from the server and, if necessary,
/// calls readFiles to read requested files.
/// handleRequest() can fail from response.headers.append(), response.do(),
/// response.writeAll(), response.finish(), and readFiles()
/// response.headers.append() does not define what error types it will return
/// response.do() does not define what error types it will return
/// response.writeAll() will return a WriteError
/// response.finish() will return a FinishError
/// readFiles() does not define what error types it will return
/// handleRequest handles the following status codes:
/// - 200 OK
/// - 403 Forbidden
/// - 404 Not Found
/// - 413 Payload Too Large
/// - 414 URI Too Long
fn handleRequest(response: *std.http.Server.Response) !void {
    // Log the request details
    log.info("{s} {s} {s}", .{ @tagName(response.request.method), @tagName(response.request.version), response.request.target });

    // Create a []u8 to read up to buffer_limit characters
    var read = [_]u8{0} ** buffer_limit;

    // Set "connection" header to "keep-alive" if present in request headers
    if (response.request.headers.contains("connection")) {
        try response.headers.append("connection", "keep-alive");
    }

    // First try to read the file into the read buffer; also handle and return
    // certain easy error codes here
    const size = readFiles(response.request.target, &read) catch |err| {
        switch (err) {
            // Return an error 403 if the file is denied because of permissions
            error.AccessDenied => {
                response.status = .forbidden;
            },
            // Return an error 404 if the file is not found
            error.FileNotFound => {
                response.status = .not_found;
            },
            // Return an error 414 if the URI is too long to be read
            error.OutOfMemory => {
                response.status = .uri_too_long;
            },
            // Otherwise, some other error happened that I don't know. This
            // will eventually return an error 500
            else => {
                return err;
            },
        }
        // For all of the above error cases, it's not actually returning any
        // data, so .content_length is 0
        response.transfer_encoding = .{ .content_length = 0 };
        try response.do();
        return;
    };
    if (size >= buffer_limit) {
        // If the amount read into read is as big as the buffer_limit, that
        // means there was more text than could be processed and so this will
        // return an error 413
        response.status = .payload_too_large;
        response.transfer_encoding = .{ .content_length = 0 };
        try response.do();
        return;
    } else if (size > 0) {
        // Get the file extension, and set the content-type header if it exists
        // (using mime.zig)
        // To do this, iterate through response.request.target in reverse
        // looking for a '/' or a '.'
        // a '/' indicates a directory, so there is no extension
        // a '.' indicates a file extension
        var i: usize = response.request.target.len;
        var mime_type: ?mime.Type = undefined;
        // TODO properly handle files with no extension
        if (std.mem.endsWith(u8, response.request.target, "/")) {
            log.warn("Dir requested, returning index.html!", .{});
            try response.headers.append("content-type", "text/html");
        } else {
            while (i > 0) {
                i -= 1;
                switch (response.request.target[i]) {
                    '/' => {
                        i = 0;
                        break;
                    },
                    '.' => {
                        break;
                    },
                    else => {
                        continue;
                    },
                }
            }
            if (i <= 0) {
                log.warn("No extension detected!", .{});
                if (std.mem.indexOf(u8, &read, "<html")) |_| {
                    try response.headers.append("content-type", "text/html");
                } else {
                    try response.headers.append("content-type", "text/plain");
                }
            } else {
                log.info("Extension {s} detected!", .{response.request.target[i..]});
                mime_type = mime.extension_map.get(response.request.target[i..]);
                if (mime_type) |mime_val| {
                    try response.headers.append("content-type", @tagName(mime_val));
                } else {
                    // Should maybe return error 415?
                    try response.headers.append("content-type", "text/plain");
                }
            }
        }
        log.info("{}", .{size});
        // Check if the request target contains "?chunked"
        if (std.mem.indexOf(u8, response.request.target, "?chunked") != null) {
            response.transfer_encoding = .chunked;
        } else {
            response.transfer_encoding = .{ .content_length = size };
        }
        // Transmit the response
        try response.do();
        if (response.request.method != .HEAD) {
            _ = try response.write(read[0..size]);
            try response.finish();
        }
    } else {
        // If the file was not found, return error 404
        response.status = .not_found;
        response.transfer_encoding = .{ .content_length = 0 };
        try response.do();
    }
}

/// runServer() accepts inputs from the server, and passes the requests on to
/// handleRequest().
/// runServer() can fail from server.accept(), response.wait(), and
/// handleRequest().
/// server.accept() will return an AcceptError
/// resonse.wait() will return a WaitError
/// runServer() handles the following error codes:
/// - 500 (Internal Server Error)
fn runServer(server: *std.http.Server) !void {
    var fba_buffer: [buffer_limit]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&fba_buffer);
    const allocator = fba.allocator();

    outer: while (true) {
        // Accept incoming connection
        var response = try server.accept(.{
            .allocator = allocator,
        });
        defer response.deinit();

        while (response.reset() != .closing) {
            // Handle errors during request processing
            response.wait() catch |err| switch (err) {
                error.HttpHeadersInvalid => continue :outer,
                error.EndOfStream => continue,
                else => return err,
            };

            // Process the request
            handleRequest(&response) catch |err| {
                response.status = .internal_server_error;
                response.transfer_encoding = .{ .content_length = 0 };
                try response.do();
                return err;
            };
        }
    }
}

/// printInfo() prints the copyright legal information. Theoretically it
/// shouldn't fail, but if it does stderr.print() will throw a WriteError.
pub fn printInfo(stderr: std.fs.File.Writer) !void {
    try stderr.print("zhttpd version 0.1.0, Copyright (C) 2024 ZachIR\n", .{});
    try stderr.print("zhttpd comes with ABSOLUTELY NO WARRANTY. This is ", .{});
    try stderr.print("free software, and you are welcome to ", .{});
    try stderr.print("redistribute it under certain conditions; see the ", .{});
    try stderr.print("included LICENSE for more details.\n", .{});
}

/// main() initializes the server, parses the IP and port, and begins
/// runServer().
/// main() can fail exit from server.listen() and runServer(), which do not
/// specify the error types they can return.
pub fn main() !void {
    var fba_buffer: [@sizeOf(std.http.Server)]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&fba_buffer);
    const allocator = fba.allocator();

    //const stdout = std.io.getStdOut().writer();
    const stderr = std.io.getStdErr().writer();

    try printInfo(stderr);

    // Initialize the server
    var server = std.http.Server.init(allocator, .{ .reuse_address = true });
    defer server.deinit();

    // Log the server address and port
    try stderr.print("Server is running at {s}:{d}\n", .{ server_addr, server_port });

    // Parse the server address
    const address = std.net.Address.parseIp(server_addr, server_port) catch unreachable;
    try server.listen(address);

    // Run the server
    runServer(&server) catch |err| {
        // Handle server errors
        log.err("server error: {}\n", .{err});
        if (@errorReturnTrace()) |trace| {
            std.debug.dumpStackTrace(trace.*);
        }
        std.os.exit(1);
    };
}