bbj2/server/cmd/main.go

598 lines
12 KiB
Go
Raw Normal View History

2022-04-11 02:32:02 +00:00
package main
2022-04-11 03:45:33 +00:00
import (
2022-04-12 20:33:13 +00:00
"database/sql"
2022-04-21 02:19:01 +00:00
_ "embed"
2022-04-20 03:27:31 +00:00
"encoding/json"
2022-04-22 19:49:36 +00:00
"errors"
2022-04-11 03:45:33 +00:00
"flag"
"fmt"
"io"
2022-04-12 00:16:06 +00:00
"net/http"
2022-04-11 03:45:33 +00:00
"os"
2022-04-22 19:49:36 +00:00
"strings"
2022-04-28 19:08:05 +00:00
"time"
2022-04-12 20:33:13 +00:00
2022-04-28 19:08:05 +00:00
"github.com/google/uuid"
2022-04-12 20:33:13 +00:00
_ "github.com/mattn/go-sqlite3"
2022-04-11 03:45:33 +00:00
)
2022-05-22 05:50:34 +00:00
// TODO tests
2022-04-21 02:19:01 +00:00
//go:embed schema.sql
var schemaSQL string
2022-04-12 20:33:13 +00:00
type Config struct {
Admins []string
Port int
Host string
InstanceName string `yaml:"instance_name"`
AllowAnon bool `yaml:"allow_anon"`
Debug bool
DBPath string `yaml:"db_path"`
}
2022-04-11 03:45:33 +00:00
type iostreams struct {
Err io.Writer
Out io.Writer
}
2022-05-04 01:24:08 +00:00
type options struct {
2022-04-11 03:45:33 +00:00
ConfigPath string
IO iostreams
2022-04-12 00:16:06 +00:00
Log func(string)
Logf func(string, ...interface{})
2022-04-12 20:33:13 +00:00
Config Config
DB *sql.DB
2022-04-22 19:49:36 +00:00
Reset bool
2022-04-11 03:45:33 +00:00
}
2022-04-11 02:32:02 +00:00
func main() {
2022-04-11 03:45:33 +00:00
var configFlag = flag.String("config", "config.yml", "A path to a config file.")
2022-04-22 19:49:36 +00:00
var resetFlag = flag.Bool("reset", false, "reset the database. WARNING this wipes everything.")
2022-04-11 03:45:33 +00:00
flag.Parse()
2022-04-12 00:16:06 +00:00
io := iostreams{
Err: os.Stderr,
Out: os.Stdout,
}
2022-05-04 01:24:08 +00:00
opts := &options{
2022-04-11 03:45:33 +00:00
ConfigPath: *configFlag,
2022-04-22 19:49:36 +00:00
Reset: *resetFlag,
2022-04-12 00:16:06 +00:00
IO: io,
// TODO use real logger
Log: func(s string) {
fmt.Fprintln(io.Out, s)
},
Logf: func(s string, args ...interface{}) {
fmt.Fprintf(io.Out, s, args...)
2022-04-20 03:27:31 +00:00
fmt.Fprintf(io.Out, "\n")
2022-04-11 03:45:33 +00:00
},
}
err := _main(opts)
if err != nil {
fmt.Fprintf(os.Stderr, "failed: %s", err)
}
}
2022-04-12 20:33:13 +00:00
type Teardown func()
2022-05-04 01:24:08 +00:00
func setupDB(opts *options) (Teardown, error) {
2022-04-12 20:33:13 +00:00
db, err := sql.Open("sqlite3", opts.Config.DBPath)
opts.DB = db
return func() { db.Close() }, err
}
2022-05-04 01:24:08 +00:00
func _main(opts *options) error {
2022-04-11 03:45:33 +00:00
cfg, err := parseConfig(opts.ConfigPath)
if err != nil {
fmt.Fprintf(os.Stderr, "could not read config file '%s'", opts.ConfigPath)
os.Exit(1)
}
2022-04-12 20:33:13 +00:00
opts.Config = *cfg
teardown, err := setupDB(opts)
if err != nil {
return fmt.Errorf("could not initialize DB: %w", err)
}
defer teardown()
2022-04-22 19:49:36 +00:00
err = ensureSchema(*opts)
2022-04-21 02:19:01 +00:00
if err != nil {
return err
}
2022-04-12 20:33:13 +00:00
setupAPI(*opts)
2022-04-12 00:16:06 +00:00
// TODO TLS or SSL or something
2022-04-20 03:27:31 +00:00
opts.Logf("starting server at %s:%d", cfg.Host, cfg.Port)
2022-04-12 00:16:06 +00:00
if err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil); err != nil {
return fmt.Errorf("http server exited with error: %w", err)
}
2022-04-11 03:45:33 +00:00
return nil
}
2022-04-12 00:16:06 +00:00
2022-05-04 01:24:08 +00:00
func ensureSchema(opts options) error {
2022-04-22 19:49:36 +00:00
db := opts.DB
if opts.Reset {
err := os.Remove(opts.Config.DBPath)
if err != nil {
return fmt.Errorf("failed to delete database: %w", err)
}
}
rows, err := db.Query("select version from meta")
if err == nil {
2022-04-22 20:23:12 +00:00
defer rows.Close()
2022-04-22 19:49:36 +00:00
rows.Next()
var version string
err = rows.Scan(&version)
if err != nil {
return fmt.Errorf("failed to check database schema version: %w", err)
} else if version == "" {
return errors.New("database is in unknown state")
}
return nil
}
if !strings.Contains(err.Error(), "no such table") {
return fmt.Errorf("got error checking database state: %w", err)
}
_, err = db.Exec(schemaSQL)
2022-04-21 02:19:01 +00:00
if err != nil {
return fmt.Errorf("failed to initialize database schema: %w", err)
}
return nil
}
2022-05-04 01:24:08 +00:00
func handler(opts options, f http.HandlerFunc) http.HandlerFunc {
2022-04-12 00:16:06 +00:00
// TODO make this more real
return func(w http.ResponseWriter, req *http.Request) {
opts.Log(req.URL.Path)
// TODO add user info to opts
2022-04-12 00:16:06 +00:00
f(w, req)
}
}
2022-04-20 03:27:31 +00:00
// TODO I'm not entirely sold on this hash system; without transport
// encryption, it doesn't really help anything. I'd rather have plaintext +
// transport encryption and then, on the server side, proper salted hashing.
type User struct {
2022-05-18 02:09:17 +00:00
ID string
Username string
Hash string
2022-04-20 03:27:31 +00:00
}
type BBJResponse struct {
Error bool `json:"error"`
Data interface{} `json:"data"`
Usermap map[string]User `json:"usermap"`
}
func writeResponse(w http.ResponseWriter, resp BBJResponse) {
2022-04-24 17:09:56 +00:00
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
2022-04-20 03:27:31 +00:00
json.NewEncoder(w).Encode(resp)
}
2022-05-18 02:09:17 +00:00
// NB breaking: i'm not just returning 200 always but using http status codes
2022-04-24 17:09:56 +00:00
func writeErrorResponse(w http.ResponseWriter, code int, resp BBJResponse) {
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
2022-05-18 02:09:17 +00:00
func getUserFromReq(opts options, req *http.Request) (u User, err error) {
u.Username = req.Header.Get("User")
u.Hash = req.Header.Get("Auth")
if u.Username == "" {
2022-05-04 01:24:08 +00:00
err = errors.New("no User header set")
2022-05-18 02:09:17 +00:00
return
2022-05-04 01:24:08 +00:00
}
2022-05-18 02:09:17 +00:00
if u.Username == "anon" {
2022-05-04 01:24:08 +00:00
if !opts.Config.AllowAnon {
err = errors.New("anonymous access disabled")
2022-05-18 02:09:17 +00:00
return
}
2022-05-18 02:09:17 +00:00
}
db := opts.DB
stmt, err := db.Prepare("select auth_hash, id from users where user_name = ?")
if err != nil {
err = fmt.Errorf("db error: %w", err)
2022-05-04 01:24:08 +00:00
return
}
2022-05-18 02:09:17 +00:00
defer stmt.Close()
opts.Logf("querying for %s", u.Username)
var authHash string
if err = stmt.QueryRow(u.Username).Scan(&authHash, u.ID); err != nil {
if strings.Contains(err.Error(), "no rows in result") {
err = errors.New("no such user")
} else {
err = fmt.Errorf("db error: %w", err)
}
}
2022-05-04 01:24:08 +00:00
2022-05-18 02:09:17 +00:00
if authHash != u.Hash {
err = errors.New("bad credentials")
}
2022-05-04 01:24:08 +00:00
return
}
2022-04-20 03:27:31 +00:00
2022-05-18 02:09:17 +00:00
func checkAuth(opts options, username, hash string) error {
2022-05-04 01:24:08 +00:00
db := opts.DB
stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
return fmt.Errorf("db error: %w", err)
}
defer stmt.Close()
2022-05-18 02:09:17 +00:00
opts.Logf("querying for %s", username)
2022-05-04 01:24:08 +00:00
var authHash string
2022-05-18 02:09:17 +00:00
if err = stmt.QueryRow(username).Scan(&authHash); err != nil {
2022-05-04 01:24:08 +00:00
if strings.Contains(err.Error(), "no rows in result") {
return errors.New("no such user")
}
return fmt.Errorf("db error: %w", err)
}
2022-05-18 02:09:17 +00:00
if authHash != hash {
2022-05-04 01:24:08 +00:00
return errors.New("bad credentials")
}
return nil
}
func setupAPI(opts options) {
2022-04-28 19:08:05 +00:00
serverErr := func(w http.ResponseWriter, err error) {
opts.Logf(err.Error())
2022-04-28 18:40:48 +00:00
writeErrorResponse(w, 500, BBJResponse{
Error: true,
Data: "server error",
})
}
2022-04-24 17:33:19 +00:00
badMethod := func(w http.ResponseWriter) {
writeErrorResponse(w, 400, BBJResponse{
Error: true,
Data: "bad method",
})
}
invalidArgs := func(w http.ResponseWriter) {
writeErrorResponse(w, 400, BBJResponse{
Error: true,
Data: "invalid args",
})
}
2022-05-04 01:24:08 +00:00
http.HandleFunc("/instance_info", handler(opts, func(w http.ResponseWriter, req *http.Request) {
type instanceInfo struct {
InstanceName string `json:"instance_name"`
AllowAnon bool `json:"allow_anon"`
Admins []string
}
writeResponse(w, BBJResponse{
Data: instanceInfo{
InstanceName: opts.Config.InstanceName,
AllowAnon: opts.Config.AllowAnon,
Admins: opts.Config.Admins,
},
})
}))
2022-04-24 17:33:19 +00:00
http.HandleFunc("/user_register", handler(opts, func(w http.ResponseWriter, req *http.Request) {
2022-04-20 03:27:31 +00:00
if req.Method != "POST" {
2022-04-24 17:33:19 +00:00
badMethod(w)
2022-04-20 03:27:31 +00:00
return
}
2022-04-28 18:40:48 +00:00
type AuthArgs struct {
Username string `json:"user_name"`
2022-05-04 01:24:08 +00:00
Hash string `json:"auth_hash"`
2022-04-28 18:40:48 +00:00
}
2022-04-24 17:33:19 +00:00
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
2022-04-20 03:27:31 +00:00
}
2022-05-04 01:24:08 +00:00
if args.Hash == "" || args.Username == "" {
2022-04-28 19:08:05 +00:00
invalidArgs(w)
return
}
2022-04-28 18:40:48 +00:00
opts.Logf("querying for %s", args.Username)
2022-05-18 02:09:17 +00:00
if err := checkAuth(opts, args.Username, args.Hash); err == nil {
2022-04-28 18:40:48 +00:00
opts.Logf("found %s", args.Username)
// code 4 apparently
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "user already exists",
})
2022-05-04 01:24:08 +00:00
} else if err.Error() != "no such user" {
2022-04-28 19:08:05 +00:00
serverErr(w, err)
return
}
2022-05-04 01:24:08 +00:00
db := opts.DB
stmt, err := db.Prepare(`INSERT INTO users VALUES (?, ?, ?, "", "", 0, 0, ?)`)
2022-04-28 19:08:05 +00:00
id, err := uuid.NewRandom()
if err != nil {
serverErr(w, err)
2022-04-28 18:40:48 +00:00
return
}
2022-05-04 01:24:08 +00:00
_, err = stmt.Exec(id, args.Username, args.Hash, time.Now())
2022-04-28 19:08:05 +00:00
if err != nil {
serverErr(w, err)
}
2022-04-28 18:40:48 +00:00
writeResponse(w, BBJResponse{
Data: true, // TODO probably something else
// TODO prob usermap
})
2022-04-24 17:33:19 +00:00
}))
2022-04-20 03:27:31 +00:00
2022-04-24 17:33:19 +00:00
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
badMethod(w)
return
}
2022-04-20 03:27:31 +00:00
2022-04-28 18:40:48 +00:00
type AuthArgs struct {
Username string `json:"target_user"`
AuthHash string `json:"target_hash"`
}
2022-04-24 17:33:19 +00:00
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
2022-04-24 17:09:56 +00:00
return
2022-04-20 03:27:31 +00:00
}
2022-04-24 17:33:19 +00:00
opts.Logf("got %s %s", args.Username, args.AuthHash)
2022-04-20 03:27:31 +00:00
2022-04-22 20:23:12 +00:00
db := opts.DB
stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
2022-04-28 19:08:05 +00:00
serverErr(w, err)
2022-04-22 20:23:12 +00:00
return
}
defer stmt.Close()
var authHash string
2022-04-24 17:33:19 +00:00
err = stmt.QueryRow(args.Username).Scan(&authHash)
2022-04-22 20:23:12 +00:00
if err != nil {
2022-04-24 17:09:56 +00:00
if strings.Contains(err.Error(), "no rows in result") {
opts.Logf("user not found")
writeErrorResponse(w, 404, BBJResponse{
Error: true,
Data: "user not found",
})
} else {
2022-04-28 19:08:05 +00:00
serverErr(w, err)
2022-04-24 17:09:56 +00:00
}
2022-04-22 20:23:12 +00:00
return
}
// TODO unique constraint on user_name
2022-04-24 17:33:19 +00:00
if authHash != args.AuthHash {
2022-04-24 17:09:56 +00:00
http.Error(w, "incorrect password", 403)
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "incorrect password",
})
return
2022-04-22 20:23:12 +00:00
}
2022-04-20 03:27:31 +00:00
2022-04-28 18:40:48 +00:00
// TODO include usermap?
2022-04-20 03:27:31 +00:00
writeResponse(w, BBJResponse{
2022-04-24 17:09:56 +00:00
Data: true,
2022-04-20 03:27:31 +00:00
})
2022-04-12 00:16:06 +00:00
}))
http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) {
db := opts.DB
rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id")
if err != nil {
serverErr(w, err)
return
}
defer rows.Close()
for rows.Next() {
var id string
err = rows.Scan(&id)
if err != nil {
serverErr(w, err)
return
}
opts.Log(id)
}
writeResponse(w, BBJResponse{Data: "TODO"})
// TODO
}))
http.HandleFunc("/thread_create", handler(opts, func(w http.ResponseWriter, req *http.Request) {
2022-05-04 01:24:08 +00:00
if req.Method != "POST" {
badMethod(w)
return
}
2022-05-04 05:48:29 +00:00
// TODO make this getUserInfoFromReq or similar so we can use the user ID later
2022-05-18 02:09:17 +00:00
user, err := getUserFromReq(opts, req)
2022-05-04 01:24:08 +00:00
if err != nil {
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: err.Error(),
})
return
}
type threadCreateArgs struct {
2022-05-04 05:48:29 +00:00
Title string
Body string
SendRaw bool `json:"send_raw"`
2022-05-04 01:24:08 +00:00
}
2022-05-04 05:48:29 +00:00
var args threadCreateArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
if args.Title == "" || args.Body == "" {
invalidArgs(w)
return
}
db := opts.DB
tx, err := db.Begin()
if err != nil {
serverErr(w, err)
return
}
stmt, err := tx.Prepare("insert into threads VALUES ( ?, ?, ?, ?, ?, 0, 0, ? )")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
threadID, err := uuid.NewRandom()
if err != nil {
serverErr(w, err)
return
}
now := time.Now()
if _, err = stmt.Exec(
threadID,
2022-05-18 02:09:17 +00:00
user.ID,
2022-05-04 05:48:29 +00:00
args.Title,
now,
now,
2022-05-18 02:09:17 +00:00
user.Username,
2022-05-04 05:48:29 +00:00
); err != nil {
serverErr(w, err)
return
}
stmt, err = tx.Prepare("insert into messages values ( ?, 1, ?, ?, 0, ?, ? )")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
if _, err = stmt.Exec(
threadID,
2022-05-18 02:09:17 +00:00
user.ID,
2022-05-04 05:48:29 +00:00
now,
args.Body,
args.SendRaw,
); err != nil {
serverErr(w, err)
return
}
if err = tx.Commit(); err != nil {
serverErr(w, err)
return
}
2022-05-18 02:09:17 +00:00
stmt, err = db.Prepare("select * from threads where thread_id = ? limit 1")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
t := &Thread{}
// TODO fill in rest of thread
if err = stmt.QueryRow(threadID).Scan(
t.ID,
t.Author,
t.Title,
t.LastMod,
t.Created,
t.ReplyCount,
t.Pinned,
t.LastAuthor,
); err != nil {
serverErr(w, err)
return
}
2022-05-04 01:24:08 +00:00
2022-05-18 02:09:17 +00:00
stmt, err = db.Prepare("select * from messages where thread_id = ?")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
rows, err := stmt.Query(threadID)
if err != nil {
serverErr(w, err)
return
}
t.Messages = []Message{}
for rows.Next() {
m := &Message{}
if err := rows.Scan(
m.ThreadID,
m.PostID,
m.Author,
m.Created,
m.Edited,
m.Body,
m.SendRaw,
); err != nil {
serverErr(w, err)
return
}
t.Messages = append(t.Messages, *m)
}
writeResponse(w, BBJResponse{Data: t})
}))
2022-04-12 00:16:06 +00:00
}
2022-05-18 02:09:17 +00:00
type Thread struct {
ID string `json:"thread_id"`
Author string
Title string
LastMod time.Time `json:"last_mod"`
Created time.Time
ReplyCount int `json:"reply_count"`
Pinned int // TODO bool
LastAuthor string `json:"last_author"`
Messages []Message
}
type Message struct {
ThreadID string `json:"thread_id"`
PostID string `json:"post_id"`
Author string
Created time.Time
Edited int // TODO bool
Body string
SendRaw int `json:"send_raw"` // TODO bool
}