]> gitweb.ps.run Git - chirp/blobdiff - src/main.zig
update readme
[chirp] / src / main.zig
index 7aa34bb65751cae814053e5265628d5a5647da88..259f3dac0a3a3ea13dbf4d365f68de9cf9b81a56 100644 (file)
@@ -29,8 +29,11 @@ const User = struct {
     id: UserId,
     name: Username,
     display_name: DisplayName,
+    description: UserDescription,
     password_hash: PasswordHash,
+
     posts: PostList,
+
     following: UserList,
     followers: UserList,
 
@@ -82,6 +85,7 @@ const PostId = enum(u64) { _ };
 const Timestamp = i64;
 const Username = std.BoundedArray(u8, 32);
 const DisplayName = std.BoundedArray(u8, 64);
+const UserDescription = std.BoundedArray(u8, 1024);
 const PasswordHash = std.BoundedArray(u8, 128);
 const SessionToken = u64;
 const CookieValue = std.BoundedArray(u8, 128);
@@ -93,7 +97,7 @@ const PostListList = db.List(SavedPostList);
 const UserListList = db.List(SavedUserList);
 
 fn parse_enum(comptime E: type, buf: []const u8, base: u8) !E {
-    return @enumFromInt(try std.fmt.parseUnsigned(@typeInfo(E).Enum.tag_type, buf, base));
+    return @enumFromInt(try std.fmt.parseUnsigned(@typeInfo(E).@"enum".tag_type, buf, base));
 }
 
 // https://developer.mozilla.org/en-US/docs/Glossary/Percent-encoding
@@ -107,28 +111,19 @@ fn reencode(comptime T: type, text: []const u8) !T {
         const c = text[idx];
         if (c == '+') {
             try result.append(' ');
-        } else if (c == '%') {
-            // special case of &#...
-            // assume only &#, no &#x
-            if (idx + 6 < text.len and std.mem.eql(u8, text[idx .. idx + 6], "%26%23")) {
-                const num_start = idx + 6;
-                var num_end = num_start;
-                while (num_end < text.len and std.ascii.isDigit(text[num_end])) {
-                    num_end += 1;
-                }
+        } else if (c == '%' and idx + 2 < text.len) {
+            const allow = &[_]u8{ 0x26, 0x23, 0x3b, 0x0a };
 
-                if (num_end + 2 < text.len and
-                    text[num_end] == '%' and
-                    text[num_end + 1] == '3' and
-                    std.ascii.toLower(text[num_end + 2]) == 'b')
-                {
-                    try std.fmt.format(result.writer(), "&#{s};", .{text[num_start..num_end]});
-                    idx = num_end + 2;
-                    continue;
-                }
+            const escaped_value = std.fmt.parseUnsigned(u8, text[idx + 1 .. idx + 3], 16) catch continue;
+
+            if (escaped_value == 0x0d) {
+                try std.fmt.format(result.writer(), "<br />", .{});
+            } else if (std.mem.indexOfScalar(u8, allow, escaped_value) != null) {
+                try std.fmt.format(result.writer(), "{c}", .{escaped_value});
+            } else {
+                try std.fmt.format(result.writer(), "&#x{x};", .{escaped_value});
             }
 
-            try std.fmt.format(result.writer(), "&#x{s};", .{text[idx + 1 .. idx + 3]});
             idx += 2;
         } else {
             try result.append(c);
@@ -168,19 +163,18 @@ fn decode(text: []const u8) !std.BoundedArray(u8, 1024) {
 const Chirp = struct {
     const PostsPerPage = 10;
     const UsersPerPage = 10;
+    var HashBuffer = std.mem.zeroes([1024 * 1024 * 50]u8);
 
     pub fn hash_password(password: []const u8) !PasswordHash {
         var hash_buffer = try PasswordHash.init(128);
 
         // TODO: choose buffer size
-        // TODO: dont allocate on stack, maybe zero memory?
-        var buffer: [1024 * 10]u8 = undefined;
-        var alloc = std.heap.FixedBufferAllocator.init(&buffer);
+        var alloc = std.heap.FixedBufferAllocator.init(&HashBuffer);
 
         // TODO: choose limits
         const result = try std.crypto.pwhash.argon2.strHash(password, .{
             .allocator = alloc.allocator(),
-            .params = std.crypto.pwhash.argon2.Params.fromLimits(1000, 1024),
+            .params = std.crypto.pwhash.argon2.Params.owasp_2id,
         }, hash_buffer.slice());
 
         try hash_buffer.resize(result.len);
@@ -189,8 +183,7 @@ const Chirp = struct {
     }
 
     pub fn verify_password(password: []const u8, hash: PasswordHash) bool {
-        var buffer: [1024 * 10]u8 = undefined;
-        var alloc = std.heap.FixedBufferAllocator.init(&buffer);
+        var alloc = std.heap.FixedBufferAllocator.init(&HashBuffer);
 
         if (std.crypto.pwhash.argon2.strVerify(hash.constSlice(), password, .{
             .allocator = alloc.allocator(),
@@ -223,6 +216,7 @@ const Chirp = struct {
                 .id = user_id,
                 .name = username_array,
                 .display_name = display_name,
+                .description = try UserDescription.init(0),
                 .password_hash = try hash_password(password),
                 .posts = try PostList.init(txn),
                 .following = try UserList.init(txn),
@@ -471,7 +465,7 @@ pub fn Paginate(comptime T: type) type {
                 .starting_idx = it.idx,
             };
         }
-        pub fn next(self: *Self) IterateResult {
+        pub fn next(self: *Self) ?IterateResult {
             if (self.it.next()) |kv| {
                 if (self.count < self.per_page) {
                     self.count += 1;
@@ -513,10 +507,16 @@ fn html_form(res: *http.Response, action: []const u8, inputs: anytype) !void {
 
     inline for (inputs) |input| {
         switch (@typeInfo(@TypeOf(input))) {
-            .Struct => {
-                try res.write("<input ", .{});
-                try res.write(input[0], input[1]);
-                try res.write(" />", .{});
+            .@"struct" => |s| {
+                if (s.fields.len == 3) {
+                    try res.write("<{s} ", .{input[0]});
+                    try res.write(input[1], input[2]);
+                    try res.write("></{s}>", .{input[0]});
+                } else {
+                    try res.write("<input ", .{});
+                    try res.write(input[0], input[1]);
+                    try res.write(" />", .{});
+                }
             },
             else => {
                 try res.write("<input ", .{});
@@ -599,6 +599,10 @@ fn write_start(res: *http.Response) !void {
         \\  form {
         \\    display: inline-block;
         \\  }
+        \\  body {
+        \\    margin:40px auto;max-width:650px;line-height:1.6;font-size:18px;color:#444;padding:0 10px;
+        \\  }
+        \\  h1,h2,h3{line-height:1.2}
         \\</style>
         \\</head>
         \\<body>
@@ -703,8 +707,8 @@ fn write_post(res: *http.Response, txn: lmdb.Txn, logged_in: ?Login, post_id: Po
             try res.write("<option value=\"{x}\">{s}{s}</option>", .{ id, name.constSlice(), if (list_view.has(post_id) catch false) " *" else "" });
         }
         try res.write("</select>", .{});
-        try res.write("<input type=\"hidden\" name=\"post_id\" value=\"{x}\"></input>", .{@intFromEnum(post_id)});
-        try res.write("<input type=\"submit\" value=\"Save\"></input>", .{});
+        try res.write("<input type=\"hidden\" name=\"post_id\" value=\"{x}\" />", .{@intFromEnum(post_id)});
+        try res.write("<input type=\"submit\" value=\"Save\" />", .{});
         try res.write("</form>", .{});
     }
 
@@ -714,7 +718,7 @@ fn write_post(res: *http.Response, txn: lmdb.Txn, logged_in: ?Login, post_id: Po
         try res.write("<br /><br />", .{});
         try html_form(res, "/comment", .{
             .{ "type=\"hidden\" value=\"{x}\" name=\"post_id\"", .{@intFromEnum(post.id)} },
-            "type=\"text\" name=\"text\" placeholder=\"Text\"",
+            .{ "textarea", "type=\"text\" name=\"text\" placeholder=\"Text\"", .{} },
             "type=\"submit\" value=\"Comment\"",
         });
         try res.write("<br />", .{});
@@ -784,8 +788,8 @@ fn write_profile(res: *http.Response, txn: lmdb.Txn, logged_in: ?Login, user: Us
             try res.write("<option value=\"{x}\">{s}{s}</option>", .{ id, name.constSlice(), if (list_view.has(user.id) catch false) " *" else "" });
         }
         try res.write("</select>", .{});
-        try res.write("<input type=\"hidden\" name=\"user_id\" value=\"{x}\"></input>", .{@intFromEnum(user.id)});
-        try res.write("<input type=\"submit\" value=\"Add to feed\"></input>", .{});
+        try res.write("<input type=\"hidden\" name=\"user_id\" value=\"{x}\" />", .{@intFromEnum(user.id)});
+        try res.write("<input type=\"submit\" value=\"Add to feed\" />", .{});
         try res.write("</form>", .{});
     }
     try res.write(
@@ -814,6 +818,15 @@ fn write_profile(res: *http.Response, txn: lmdb.Txn, logged_in: ?Login, user: Us
         , .{});
     }
 
+    if (user.description.len > 0) {
+        try res.write(
+            \\<div style="padding-left: 5px; border-left: 1px solid grey;">
+            // \\&#x00AB; {s} &#x00BB;
+            \\<i>{s}</i>
+            \\</div>
+        , .{user.description.constSlice()});
+    }
+
     try res.write("<br />", .{});
 }
 fn write_posts(res: *http.Response, txn: lmdb.Txn, logged_in: ?Login, post_list: PostList, options: struct {
@@ -847,6 +860,10 @@ fn write_timeline(res: *http.Response, txn: lmdb.Txn, logged_in: ?Login, user_li
     var prev_newest_post: ?Post = null;
 
     const following = try user_list.open(txn);
+    if (following.len() == 0) {
+        try res.write("Empty timeline (no users)", .{});
+        return;
+    }
 
     while (true) {
         var newest_post: ?Post = null;
@@ -958,20 +975,20 @@ const GET = struct {
 
     fn handle(self: Self) !bool {
         const ti = @typeInfo(Self);
-        inline for (ti.Struct.decls) |f_decl| {
+        inline for (ti.@"struct".decls) |f_decl| {
             const has_arg = f_decl.name.len > 1 and f_decl.name[f_decl.name.len - 1] == '/';
             const match = if (has_arg) std.mem.startsWith(u8, self.req.target, f_decl.name) else std.mem.eql(u8, self.req.target, f_decl.name);
 
             if (match) {
                 const f = @field(Self, f_decl.name);
                 const fi = @typeInfo(@TypeOf(f));
-                if (fi.Fn.params.len == 1) {
+                if (fi.@"fn".params.len == 1) {
                     try @call(.auto, f, .{self});
                 } else {
-                    const arg_type = fi.Fn.params[1].type.?;
+                    const arg_type = fi.@"fn".params[1].type.?;
                     const arg_info = @typeInfo(arg_type);
                     var arg: arg_type = undefined;
-                    const field = arg_info.Struct.fields[0];
+                    const field = arg_info.@"struct".fields[0];
                     if (self.req.target.len <= f_decl.name.len) {
                         return error.NoArgProvided;
                     }
@@ -979,10 +996,10 @@ const GET = struct {
                     const field_ti = @typeInfo(field.type);
                     switch (field_ti) {
                         // TODO: maybe handle BoundedArray?
-                        .Int => {
+                        .int => {
                             @field(arg, field.name) = try std.fmt.parseUnsigned(field.type, str, 16);
                         },
-                        .Enum => {
+                        .@"enum" => {
                             @field(arg, field.name) = try parse_enum(field.type, str, 16);
                         },
                         else => {
@@ -1153,7 +1170,7 @@ const GET = struct {
             try html_form(self.res, "/quote", .{
                 .{ "type=\"hidden\" name=\"referer\" value=\"{s}\"", .{referer} },
                 .{ "type=\"hidden\" name=\"post_id\" value=\"{x}\"", .{@intFromEnum(post.id)} },
-                "type=\"text\" name=\"text\" placeholder=\"Text\" autofocus",
+                .{ "textarea", "type=\"text\" name=\"text\" placeholder=\"Text\" autofocus", .{} },
                 "type=\"submit\" value=\"Quote\"",
             });
             try self.res.write("<br />", .{});
@@ -1239,7 +1256,7 @@ const GET = struct {
 
             try html_form(self.res, "/post", .{
                 .{ "type=\"hidden\" name=\"referer\" value=\"{s}\"", .{referer} },
-                "type=\"text\" name=\"text\" placeholder=\"Text\" autofocus",
+                .{ "textarea", "type=\"text\" name=\"text\" placeholder=\"Text\" autofocus", .{} },
                 "type=\"submit\" value=\"Post\"",
             });
         } else {
@@ -1258,6 +1275,11 @@ const GET = struct {
                 .{ "type=\"text\" name=\"display_name\" placeholder=\"{s}\"", .{login.user.display_name.constSlice()} },
                 "type=\"submit\" value=\"Change\"",
             });
+            try self.res.write("<br />Description: ", .{});
+            try html_form(self.res, "/set_description", .{
+                .{ "textarea", "type=\"text\" name=\"description\" placeholder=\"{s}\"", .{login.user.description.constSlice()} },
+                "type=\"submit\" value=\"Change\"",
+            });
             try self.res.write("<br />Password: ", .{});
             try html_form(self.res, "/set_password", .{
                 "type=\"text\" name=\"password\"",
@@ -1289,24 +1311,24 @@ const POST = struct {
 
     pub fn handle(self: Self) !bool {
         const ti = @typeInfo(Self);
-        inline for (ti.Struct.decls) |f_decl| {
+        inline for (ti.@"struct".decls) |f_decl| {
             if (std.mem.eql(u8, f_decl.name, self.req.target)) {
                 const f = @field(Self, f_decl.name);
                 const fi = @typeInfo(@TypeOf(f));
-                if (fi.Fn.params.len == 1) {
+                if (fi.@"fn".params.len == 1) {
                     _ = try @call(.auto, f, .{self});
                 } else {
-                    const args_type = fi.Fn.params[fi.Fn.params.len - 1].type.?;
+                    const args_type = fi.@"fn".params[fi.@"fn".params.len - 1].type.?;
                     const argsi = @typeInfo(args_type);
                     var args: args_type = undefined;
-                    inline for (argsi.Struct.fields) |field| {
+                    inline for (argsi.@"struct".fields) |field| {
                         const str = self.req.get_value(field.name) orelse return error.ArgNotFound;
                         const field_ti = @typeInfo(field.type);
                         switch (field_ti) {
-                            .Int => {
+                            .int => {
                                 @field(args, field.name) = try std.fmt.parseUnsigned(field.type, str, 16);
                             },
-                            .Enum => {
+                            .@"enum" => {
                                 @field(args, field.name) = try parse_enum(field.type, str, 16);
                             },
                             else => {
@@ -1381,6 +1403,18 @@ const POST = struct {
         user.display_name = display_name;
         try users.put(login.user.id, user);
     }
+    pub fn @"/set_description"(self: Self, args: struct { description: []const u8 }) !void {
+        const login = self.logged_in orelse return error.NotLoggedIn;
+        const description = try reencode(UserDescription, args.description);
+
+        const txn = try self.env.txn();
+        defer txn.commit() catch {};
+
+        const users = try Db.users(txn);
+        var user = login.user;
+        user.description = description;
+        try users.put(login.user.id, user);
+    }
     pub fn @"/set_password"(self: Self, args: struct { password: []const u8 }) !void {
         const login = self.logged_in orelse return error.NotLoggedIn;