]> gitweb.ps.run Git - zighttp/blob - src/http.zig
bc8f3b1b9a8bc0e6b065c0f17382922e8e4db9c5
[zighttp] / src / http.zig
1 const std = @import("std");
2 const posix = std.posix;
3 const linux = std.os.linux;
4
5 pub const Server = struct {
6     // TODO: factor out
7     const BACKLOG = 2048;
8
9     listener: posix.socket_t,
10     efd: i32,
11     ready_list: [BACKLOG]linux.epoll_event = undefined,
12
13     ready_count: usize = 0,
14     ready_index: usize = 0,
15
16     pub fn init(name: []const u8, port: u16) !Server {
17         const address = try std.net.Address.resolveIp(name, port);
18
19         const tpe: u32 = posix.SOCK.STREAM | posix.SOCK.NONBLOCK;
20         const protocol = posix.IPPROTO.TCP;
21         const listener = try posix.socket(address.any.family, tpe, protocol);
22
23         try posix.setsockopt(listener, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
24         try posix.bind(listener, &address.any, address.getOsSockLen());
25         try posix.listen(listener, BACKLOG);
26
27         // epoll_create1 takes flags. We aren't using any in these examples
28         const efd = try posix.epoll_create1(0);
29
30         var event = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = listener } };
31         try posix.epoll_ctl(efd, linux.EPOLL.CTL_ADD, listener, &event);
32
33         return .{
34             .listener = listener,
35             .efd = efd,
36         };
37     }
38
39     pub fn deinit(self: Server) void {
40         posix.close(self.efd);
41         posix.close(self.listener);
42     }
43
44     pub fn wait(self: *Server) void {
45         if (self.ready_index >= self.ready_count) {
46             self.ready_index = 0;
47             self.ready_count = posix.epoll_wait(self.efd, &self.ready_list, -1);
48         }
49     }
50
51     pub fn next_request(self: *Server, buf: []u8) !?Request {
52         while (self.ready_index < self.ready_count) {
53             const ready = self.ready_list[self.ready_index];
54             const ready_socket = ready.data.fd;
55             self.ready_index += 1;
56
57             if (ready_socket == self.listener) {
58                 const client_socket = try posix.accept(self.listener, null, null, posix.SOCK.NONBLOCK);
59                 errdefer posix.close(client_socket);
60                 var event = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = client_socket } };
61                 try posix.epoll_ctl(self.efd, linux.EPOLL.CTL_ADD, client_socket, &event);
62                 var addr: std.c.sockaddr = undefined;
63                 var addr_size: std.c.socklen_t = @sizeOf(std.c.sockaddr);
64                 _ = std.c.getpeername(client_socket, &addr, &addr_size);
65                 std.debug.print("new connection from {}\n", .{addr});
66             } else {
67                 var closed = false;
68                 var req = Request{ .fd = ready_socket };
69
70                 const read = posix.read(ready_socket, buf) catch 0;
71                 if (read == 0) {
72                     closed = true;
73                 } else {
74                     if (req.parse(buf[0..read]))
75                         return req;
76                 }
77
78                 if (closed or ready.events & linux.EPOLL.RDHUP == linux.EPOLL.RDHUP) {
79                     posix.close(ready_socket);
80                 }
81             }
82         }
83         return null;
84     }
85 };
86
87 // pub const Method = enum { GET, POST };
88 pub const Method = std.http.Method;
89
90 // pub const Header = struct {
91 //     const NAME_SIZE = 32;
92 //     const VALUE_SIZE = 128;
93
94 //     name: std.BoundedArray(u8, NAME_SIZE),
95 //     value: std.BoundedArray(u8, VALUE_SIZE),
96 // };
97 pub const Header = struct {
98     const Name = std.BoundedArray(u8, 32);
99     const Value = std.BoundedArray(u8, 128);
100
101     name: Name = Name.init(0) catch unreachable,
102     value: Value = Value.init(0) catch unreachable,
103 };
104 pub const Status = std.http.Status;
105
106 pub const Request = struct {
107     fd: posix.fd_t,
108
109     method: Method = undefined,
110     target: []const u8 = undefined,
111     version: ?[]const u8 = null,
112     head: ?[]const u8 = null,
113     body: ?[]u8 = null,
114
115     pub fn parse(self: *Request, buf: []u8) bool {
116         std.debug.print("buf: {s}\n", .{buf});
117         var state: u8 = 0;
118
119         var start: u32 = 0;
120         // var end: u32 = 0;
121
122         var index: u32 = 0;
123         while (index < buf.len) {
124             defer index += 1;
125
126             const c = buf[index];
127
128             switch (state) {
129                 0 => {
130                     if (c == ' ') {
131                         self.method = @enumFromInt(Method.parse(buf[start..index]));
132                         start = index + 1;
133                         state += 1;
134                     }
135                 },
136                 1 => {
137                     if (c == ' ') {
138                         self.target = buf[start..index];
139                         start = index + 1;
140                         state += 1;
141                     }
142                 },
143                 2 => {
144                     if (c == '\r') {
145                         self.version = buf[start..index];
146                         start = index + 2;
147                         index += 1;
148                         state += 1;
149                     }
150                 },
151                 3 => {
152                     if (c == '\r' and (index + 2) < buf.len and buf[index + 2] == '\r') {
153                         self.head = buf[start .. index + 2];
154
155                         if (index + 4 < buf.len) {
156                             self.body = buf[index + 4 .. buf.len];
157                         }
158                         return true;
159                     }
160                 },
161                 else => {},
162             }
163         }
164
165         return true;
166     }
167
168     pub fn get_header1(self: Request, name: []const u8) ?[]const u8 {
169         const head = self.head orelse return null;
170         var start: usize = 0;
171         var matching: usize = 0;
172         for (0..head.len) |i| {
173             const c = head[i];
174
175             if (matching < name.len) {
176                 if (c == name[matching]) {
177                     // if (matching == 0) start = i;
178                     matching += 1;
179                 } else {
180                     start = i;
181                     matching = 0;
182                 }
183             } else {
184                 if (c == '\r') {
185                     return head[start..i];
186                 }
187             }
188         }
189         return null;
190     }
191
192     pub fn get_cookie(self: Request, name: []const u8) ?[]const u8 {
193         const cookie = self.get_header("Cookie") orelse return null;
194         var start: usize = 0;
195         var matching: usize = 0;
196         for (0..cookie.len) |i| {
197             const c = cookie[i];
198
199             if (matching < name.len) {
200                 if (c == name[matching]) {
201                     if (matching == 0) start = i;
202                     matching += 1;
203                 } else {
204                     matching = 0;
205                 }
206             } else {
207                 if (c == '=') {
208                     if (std.mem.indexOfScalarPos(u8, cookie, i, ';')) |semi_index| {
209                         return cookie[i + 1 .. semi_index];
210                     } else {
211                         return cookie[i + 1 .. cookie.len];
212                     }
213                 } else {
214                     matching = 0;
215                 }
216             }
217         }
218         return null;
219     }
220
221     pub fn parse1(self: *Request, buf: []const u8) bool {
222         const method_start: usize = 0;
223         const method_end = std.mem.indexOfScalar(u8, buf, ' ') orelse return false;
224         self.method = @enumFromInt(Method.parse(buf[method_start..method_end]));
225
226         const target_start = method_end + 1;
227         const target_end = std.mem.indexOfScalarPos(u8, buf, target_start, ' ') orelse return false;
228         self.target = buf[target_start..target_end];
229
230         const version_start = target_end + 1;
231         const version_end = std.mem.indexOfPos(u8, buf, version_start, "\r\n") orelse buf.len;
232         self.version = buf[version_start..version_end];
233
234         if (version_end + 2 >= buf.len)
235             return true;
236         const head_start = version_end + 2;
237         const head_end = std.mem.indexOfPos(u8, buf, head_start, "\r\n\r\n") orelse buf.len;
238         self.head = buf[head_start..head_end];
239
240         if (head_end + 4 >= buf.len)
241             return true;
242         const body_start = head_end + 4;
243         const body_end = buf.len;
244         self.body = buf[body_start..body_end];
245
246         return true;
247     }
248
249     pub fn get_header(self: Request, name: []const u8) ?[]const u8 {
250         const head = self.head orelse return null;
251         const header_start = std.mem.indexOf(u8, head, name) orelse return null;
252         const colon_index = std.mem.indexOfPos(u8, head, header_start, ": ") orelse return null;
253         const header_end = std.mem.indexOfPos(u8, head, colon_index, "\r\n") orelse return null;
254         return head[colon_index + 2 .. header_end];
255     }
256
257     pub fn get_cookie1(self: Request, name: []const u8) ?[]const u8 {
258         const cookie = self.get_header("Cookie") orelse return null;
259         const name_index = std.mem.indexOf(u8, cookie, name) orelse return null;
260         const eql_index = std.mem.indexOfScalarPos(u8, cookie, name_index, '=') orelse return null;
261         if (std.mem.indexOfScalarPos(u8, cookie, eql_index, ';')) |semi_index| {
262             return cookie[eql_index + 1 .. semi_index];
263         } else {
264             return cookie[eql_index + 1 .. cookie.len];
265         }
266     }
267
268     pub fn get_value(self: Request, name: []const u8) ?[]const u8 {
269         const body = self.body orelse return null;
270         const name_index = std.mem.indexOf(u8, body, name) orelse return null;
271         const eql_index = std.mem.indexOfScalarPos(u8, body, name_index, '=') orelse return null;
272         if (std.mem.indexOfScalarPos(u8, body, name_index, '&')) |amp_index| {
273             const result = body[eql_index + 1 .. amp_index];
274             return result;
275         } else {
276             const result = body[eql_index + 1 .. body.len];
277             return result;
278         }
279     }
280 };
281
282 pub const Response = struct {
283     const ExtraHeadersMax = 16;
284     const HeaderList = std.BoundedArray(Header, ExtraHeadersMax);
285
286     fd: posix.fd_t,
287     stream_head: std.io.FixedBufferStream([]u8),
288     stream_body: std.io.FixedBufferStream([]u8),
289     status: Status = .ok,
290     extra_headers: HeaderList = HeaderList.init(0) catch unreachable,
291
292     pub fn init(fd: posix.fd_t, buf_head: []u8, buf_body: []u8) Response {
293         return .{
294             .fd = fd,
295             .stream_head = std.io.fixedBufferStream(buf_head),
296             .stream_body = std.io.fixedBufferStream(buf_body),
297         };
298     }
299
300     pub fn redirect(self: *Response, location: []const u8) !void {
301         self.status = .see_other;
302         try self.add_header("Location", .{ "{s}", .{location} });
303     }
304
305     pub fn add_header(self: *Response, name: []const u8, value: anytype) !void {
306         const header = try self.extra_headers.addOne();
307         try header.name.writer().writeAll(name);
308         if (@typeInfo(@TypeOf(value)).Struct.fields.len < 2 or @sizeOf(@TypeOf(value[1])) == 0) {
309             try header.value.writer().writeAll(value[0]);
310         } else {
311             try std.fmt.format(header.value.writer(), value[0], value[1]);
312         }
313     }
314
315     pub fn has_header(self: Response, name: []const u8) bool {
316         for (self.extra_headers.constSlice()) |h| {
317             if (std.mem.eql(u8, h.name.constSlice(), name)) {
318                 return true;
319             }
320         }
321         return false;
322     }
323
324     pub fn write(self: *Response, comptime fmt: []const u8, args: anytype) !void {
325         const writer = self.stream_body.writer();
326
327         if (@sizeOf(@TypeOf(args)) == 0) {
328             try writer.writeAll(fmt);
329         } else {
330             try std.fmt.format(writer, fmt, args);
331         }
332     }
333
334     pub fn send(self: *Response) !void {
335         // TODO: Provisorium
336         const compress = false;
337         var compress_buffer = try std.BoundedArray(u8, 1024 * 32).init(0);
338
339         // write head
340         const writer = self.stream_head.writer();
341
342         if (compress) {
343             var cfbs = std.io.fixedBufferStream(self.stream_body.getWritten());
344             var compressor = try std.compress.gzip.compressor(compress_buffer.writer(), .{ .level = .default });
345             try compressor.compress(cfbs.reader());
346             // try compressor.flush();
347             try compressor.finish();
348             try std.fmt.format(writer, "HTTP/1.1 {} {?s}\r\n" ++
349                 "Content-Length: {}\r\n" ++
350                 "Content-Encoding: gzip\r\n", .{ @intFromEnum(self.status), self.status.phrase(), compress_buffer.constSlice().len });
351         } else {
352             try std.fmt.format(writer, "HTTP/1.1 {} {?s}\r\n" ++
353                 "Content-Length: {}\r\n", .{ @intFromEnum(self.status), self.status.phrase(), self.stream_body.pos });
354         }
355
356         for (self.extra_headers.constSlice()) |header| {
357             try std.fmt.format(writer, "{s}: {s}\r\n", .{ header.name.constSlice(), header.value.constSlice() });
358         }
359
360         try std.fmt.format(writer, "\r\n", .{});
361
362         // write body to head
363         if (compress) {
364             try std.fmt.format(writer, "{s}", .{compress_buffer.constSlice()});
365         } else {
366             try std.fmt.format(writer, "{s}", .{self.stream_body.getWritten()});
367         }
368
369         // send
370         const res = self.stream_head.getWritten();
371         var written: usize = 0;
372         while (written < res.len) {
373             written += posix.write(self.fd, res[written..res.len]) catch |err| {
374                 std.debug.print("posix.write: {}\n", .{err});
375                 continue;
376             };
377         }
378     }
379 };