Hi… I am well aware that this diff view is very suboptimal. It will be fixed when the refactored server comes along!
*: Replace some := with var
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
package main
import (
"bufio"
"context"
"errors"
"os"
"github.com/jackc/pgx/v5/pgxpool"
"go.lindenii.runxiyu.org/lindenii-common/scfg"
)
var database *pgxpool.Pool
var err_unsupported_database_type = errors.New("unsupported database type")
var config struct {
HTTP struct {
Net string `scfg:"net"`
Addr string `scfg:"addr"`
CookieExpiry int `scfg:"cookie_expiry"`
Root string `scfg:"root"`
} `scfg:"http"`
Hooks struct {
Socket string `scfg:"socket"`
Execs string `scfg:"execs"`
} `scfg:"hooks"`
SSH struct {
Net string `scfg:"net"`
Addr string `scfg:"addr"`
Key string `scfg:"key"`
Root string `scfg:"root"`
} `scfg:"ssh"`
General struct {
Title string `scfg:"title"`
} `scfg:"general"`
DB struct {
Type string `scfg:"type"`
Conn string `scfg:"conn"`
} `scfg:"db"`
}
func load_config(path string) (err error) {
config_file, err := os.Open(path)
if err != nil {
var config_file *os.File
var decoder *scfg.Decoder
if config_file, err = os.Open(path); err != nil {
return err } defer config_file.Close()
decoder := scfg.NewDecoder(bufio.NewReader(config_file))
err = decoder.Decode(&config)
if err != nil {
decoder = scfg.NewDecoder(bufio.NewReader(config_file))
if err = decoder.Decode(&config); err != nil {
return err
}
if config.DB.Type != "postgres" {
return err_unsupported_database_type
}
database, err = pgxpool.New(context.Background(), config.DB.Conn)
if err != nil {
if database, err = pgxpool.New(context.Background(), config.DB.Conn); err != nil {
return err } global_data["forge_title"] = config.General.Title return nil }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "context"
"github.com/jackc/pgx/v5"
) // query_list is a helper function that executes a query and returns a list of // results.
func query_list[T any](ctx context.Context, query string, args ...any) ([]T, error) {
rows, err := database.Query(ctx, query, args...)
if err != nil {
func query_list[T any](ctx context.Context, query string, args ...any) (result []T, err error) {
var rows pgx.Rows
if rows, err = database.Query(ctx, query, args...); err != nil {
return nil, err } defer rows.Close()
var result []T
for rows.Next() {
var item T
if err := rows.Scan(&item); err != nil {
if err = rows.Scan(&item); err != nil {
return nil, err } result = append(result, item) }
if err := rows.Err(); err != nil {
if err = rows.Err(); err != nil {
return nil, err } return result, nil } // query_name_desc_list is a helper function that executes a query and returns a // list of name_desc_t results.
func query_name_desc_list(ctx context.Context, query string, args ...any) ([]name_desc_t, error) {
rows, err := database.Query(ctx, query, args...)
if err != nil {
func query_name_desc_list(ctx context.Context, query string, args ...any) (result []name_desc_t, err error) {
var rows pgx.Rows
if rows, err = database.Query(ctx, query, args...); err != nil {
return nil, err } defer rows.Close()
result := []name_desc_t{}
for rows.Next() {
var name, description string
if err := rows.Scan(&name, &description); err != nil {
if err = rows.Scan(&name, &description); err != nil {
return nil, err
}
result = append(result, name_desc_t{name, description})
}
return result, rows.Err()
}
// name_desc_t holds a name and a description.
type name_desc_t struct {
Name string
Description string
}
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "bytes" "fmt" "strings" "time" "github.com/go-git/go-git/v5/plumbing/object" ) // get_patch_from_commit formats a commit object as if it was returned by // git-format-patch.
func format_patch_from_commit(commit *object.Commit) (string, error) {
_, patch, err := get_patch_from_commit(commit)
if err != nil {
func format_patch_from_commit(commit *object.Commit) (final string, err error) {
var patch *object.Patch
var buf bytes.Buffer
var author object.Signature
var date string
var commit_msg_title, commit_msg_details string
if _, patch, err = get_patch_from_commit(commit); err != nil {
return "", err }
var buf bytes.Buffer
author = commit.Author date = author.When.Format(time.RFC1123Z)
author := commit.Author date := author.When.Format(time.RFC1123Z) commit_msg_title, commit_msg_details, _ := strings.Cut(commit.Message, "\n")
commit_msg_title, commit_msg_details, _ = strings.Cut(commit.Message, "\n")
// This date is hardcoded in Git.
fmt.Fprintf(&buf, "From %s Mon Sep 17 00:00:00 2001\n", commit.Hash)
fmt.Fprintf(&buf, "From: %s <%s>\n", author.Name, author.Email)
fmt.Fprintf(&buf, "Date: %s\n", date)
fmt.Fprintf(&buf, "Subject: [PATCH] %s\n\n", commit_msg_title)
if commit_msg_details != "" {
commit_msg_details_first_line, commit_msg_details_rest, _ := strings.Cut(commit_msg_details, "\n")
if strings.TrimSpace(commit_msg_details_first_line) == "" {
commit_msg_details = commit_msg_details_rest
}
buf.WriteString(commit_msg_details)
buf.WriteString("\n")
}
buf.WriteString("---\n")
fmt.Fprint(&buf, patch.Stats().String())
fmt.Fprintln(&buf)
buf.WriteString(patch.String())
fmt.Fprintf(&buf, "\n-- \n2.48.1\n")
return buf.String(), nil
}
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "errors" "io"
"io/fs"
"os"
"path/filepath"
)
// deploy_hooks_to_filesystem deploys the git hooks client to the filesystem.
// The git hooks client is expected to be embedded in resources_fs and must be
// pre-compiled during the build process; see the Makefile.
func deploy_hooks_to_filesystem() (err error) {
err = func() error {
src_fd, err := resources_fs.Open("git_hooks_client/git_hooks_client")
if err != nil {
err = func() (err error) {
var src_fd fs.File
var dst_fd *os.File
if src_fd, err = resources_fs.Open("git_hooks_client/git_hooks_client"); err != nil {
return err } defer src_fd.Close()
dst_fd, err := os.OpenFile(filepath.Join(config.Hooks.Execs, "git_hooks_client"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
if err != nil {
if dst_fd, err = os.OpenFile(filepath.Join(config.Hooks.Execs, "git_hooks_client"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755); err != nil {
return err } defer dst_fd.Close()
_, err = io.Copy(dst_fd, src_fd)
if err != nil {
if _, err = io.Copy(dst_fd, src_fd); err != nil {
return err
}
return nil
}()
if err != nil {
return err
}
// Go's embed filesystems do not store permissions; but in any case,
// they would need to be 0o755:
err = os.Chmod(filepath.Join(config.Hooks.Execs, "git_hooks_client"), 0o755)
if err != nil {
if err = os.Chmod(filepath.Join(config.Hooks.Execs, "git_hooks_client"), 0o755); err != nil {
return err
}
for _, hook_name := range []string{
"pre-receive",
} {
err = os.Symlink(filepath.Join(config.Hooks.Execs, "git_hooks_client"), filepath.Join(config.Hooks.Execs, hook_name))
if err != nil && !errors.Is(err, os.ErrExist) {
if err = os.Symlink(filepath.Join(config.Hooks.Execs, "git_hooks_client"), filepath.Join(config.Hooks.Execs, hook_name)); err != nil {
return err } } return nil }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "bytes" "context" "encoding/binary" "errors" "fmt" "io" "net" "os" "path/filepath" "strconv" "strings" "syscall" "github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/jackc/pgx/v5"
"go.lindenii.runxiyu.org/lindenii-common/ansiec"
)
var (
err_get_fd = errors.New("unable to get file descriptor")
err_get_ucred = errors.New("failed getsockopt")
)
// hooks_handle_connection handles a connection from git_hooks_client via the
// unix socket.
func hooks_handle_connection(conn net.Conn) {
var ctx context.Context var cancel context.CancelFunc var ucred *syscall.Ucred var err error var cookie []byte var pack_to_hook pack_to_hook_t var ssh_stderr io.Writer var ok bool var hook_return_value byte
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel = context.WithCancel(context.Background())
defer cancel() // There aren't reasonable cases where someone would run this as // another user.
ucred, err := get_ucred(conn)
if err != nil {
if _, err := conn.Write([]byte{1}); err != nil {
if ucred, err = get_ucred(conn); err != nil {
if _, err = conn.Write([]byte{1}); err != nil {
return
}
wf_error(conn, "\nUnable to get peer credentials: %v", err)
return
}
if ucred.Uid != uint32(os.Getuid()) {
if _, err := conn.Write([]byte{1}); err != nil {
if _, err = conn.Write([]byte{1}); err != nil {
return } wf_error(conn, "\nUID mismatch") return }
cookie := make([]byte, 64)
_, err = conn.Read(cookie)
if err != nil {
if _, err := conn.Write([]byte{1}); err != nil {
cookie = make([]byte, 64)
if _, err = conn.Read(cookie); err != nil {
if _, err = conn.Write([]byte{1}); err != nil {
return } wf_error(conn, "\nFailed to read cookie: %v", err) return }
pack_to_hook, ok := pack_to_hook_by_cookie.Load(string(cookie))
pack_to_hook, ok = pack_to_hook_by_cookie.Load(string(cookie))
if !ok {
if _, err := conn.Write([]byte{1}); err != nil {
if _, err = conn.Write([]byte{1}); err != nil {
return } wf_error(conn, "\nInvalid handler cookie") return }
ssh_stderr := pack_to_hook.session.Stderr()
ssh_stderr = pack_to_hook.session.Stderr()
ssh_stderr.Write([]byte{'\n'})
hook_return_value := func() byte {
hook_return_value = func() byte {
var argc64 uint64
err = binary.Read(conn, binary.NativeEndian, &argc64)
if err != nil {
if err = binary.Read(conn, binary.NativeEndian, &argc64); err != nil {
wf_error(ssh_stderr, "Failed to read argc: %v", err)
return 1
}
var args []string
for i := uint64(0); i < argc64; i++ {
var arg bytes.Buffer
for {
b := make([]byte, 1)
n, err := conn.Read(b)
if err != nil || n != 1 {
wf_error(ssh_stderr, "Failed to read arg: %v", err)
return 1
}
if b[0] == 0 {
break
}
arg.WriteByte(b[0])
}
args = append(args, arg.String())
}
var stdin bytes.Buffer
_, err = io.Copy(&stdin, conn)
if err != nil {
if _, err = io.Copy(&stdin, conn); err != nil {
wf_error(conn, "Failed to read to the stdin buffer: %v", err)
}
switch filepath.Base(args[0]) {
case "pre-receive":
if pack_to_hook.direct_access {
return 0
} else {
all_ok := true
for {
line, err := stdin.ReadString('\n')
var line, old_oid, rest, new_oid, ref_name string
var found bool
var old_hash, new_hash plumbing.Hash
var old_commit, new_commit *object.Commit
line, err = stdin.ReadString('\n')
if errors.Is(err, io.EOF) {
break
} else if err != nil {
wf_error(ssh_stderr, "Failed to read pre-receive line: %v", err)
return 1
} line = line[:len(line)-1]
old_oid, rest, found := strings.Cut(line, " ")
old_oid, rest, found = strings.Cut(line, " ")
if !found {
wf_error(ssh_stderr, "Invalid pre-receive line: %v", line)
return 1
}
new_oid, ref_name, found := strings.Cut(rest, " ")
new_oid, ref_name, found = strings.Cut(rest, " ")
if !found {
wf_error(ssh_stderr, "Invalid pre-receive line: %v", line)
return 1
}
if strings.HasPrefix(ref_name, "refs/heads/contrib/") {
if all_zero_num_string(old_oid) { // New branch
fmt.Fprintln(ssh_stderr, ansiec.Blue+"POK"+ansiec.Reset, ref_name)
var new_mr_id int
err = database.QueryRow(ctx,
"INSERT INTO merge_requests (repo_id, creator, source_ref, status) VALUES ($1, $2, $3, 'open') RETURNING id",
pack_to_hook.repo_id, pack_to_hook.user_id, strings.TrimPrefix(ref_name, "refs/heads/"),
).Scan(&new_mr_id)
if err != nil {
wf_error(ssh_stderr, "Error creating merge request: %v", err)
return 1
}
fmt.Fprintln(ssh_stderr, ansiec.Blue+"Created merge request at", generate_http_remote_url(pack_to_hook.group_name, pack_to_hook.repo_name)+"/contrib/"+strconv.FormatUint(uint64(new_mr_id), 10)+"/"+ansiec.Reset)
} else { // Existing contrib branch
var existing_merge_request_user_id int
var is_ancestor bool
err = database.QueryRow(ctx,
"SELECT COALESCE(creator, 0) FROM merge_requests WHERE source_ref = $1 AND repo_id = $2",
strings.TrimPrefix(ref_name, "refs/heads/"), pack_to_hook.repo_id,
).Scan(&existing_merge_request_user_id)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
wf_error(ssh_stderr, "No existing merge request for existing contrib branch: %v", err)
} else {
wf_error(ssh_stderr, "Error querying for existing merge request: %v", err)
}
return 1
}
if existing_merge_request_user_id == 0 {
all_ok = false
fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(branch belongs to unowned MR)")
continue
}
if existing_merge_request_user_id != pack_to_hook.user_id {
all_ok = false
fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(branch belongs another user's MR)")
continue
}
old_hash := plumbing.NewHash(old_oid)
old_hash = plumbing.NewHash(old_oid)
old_commit, err := pack_to_hook.repo.CommitObject(old_hash)
if err != nil {
if old_commit, err = pack_to_hook.repo.CommitObject(old_hash); err != nil {
wf_error(ssh_stderr, "Daemon failed to get old commit: %v", err) return 1 } // Potential BUG: I'm not sure if new_commit is guaranteed to be // detectable as they haven't been merged into the main repo's // objects yet. But it seems to work, and I don't think there's // any reason for this to only work intermitently.
new_hash := plumbing.NewHash(new_oid)
new_commit, err := pack_to_hook.repo.CommitObject(new_hash)
if err != nil {
new_hash = plumbing.NewHash(new_oid)
if new_commit, err = pack_to_hook.repo.CommitObject(new_hash); err != nil {
wf_error(ssh_stderr, "Daemon failed to get new commit: %v", err) return 1 }
is_ancestor, err := old_commit.IsAncestor(new_commit)
if err != nil {
if is_ancestor, err = old_commit.IsAncestor(new_commit); err != nil {
wf_error(ssh_stderr, "Daemon failed to check if old commit is ancestor: %v", err)
return 1
}
if !is_ancestor {
// TODO: Create MR snapshot ref instead
all_ok = false
fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(force pushes are not supported yet)")
continue
}
fmt.Fprintln(ssh_stderr, ansiec.Blue+"POK"+ansiec.Reset, ref_name)
}
} else { // Non-contrib branch
all_ok = false
fmt.Fprintln(ssh_stderr, ansiec.Red+"NAK"+ansiec.Reset, ref_name, "(you cannot push to branches outside of contrib/*)")
}
}
fmt.Fprintln(ssh_stderr)
if all_ok {
fmt.Fprintln(ssh_stderr, "Overall "+ansiec.Green+"ACK"+ansiec.Reset+" (all checks passed)")
return 0
} else {
fmt.Fprintln(ssh_stderr, "Overall "+ansiec.Red+"NAK"+ansiec.Reset+" (one or more branches failed checks)")
return 1
}
}
default:
fmt.Fprintln(ssh_stderr, ansiec.Red+"Invalid hook:", args[0]+ansiec.Reset)
return 1
}
}()
fmt.Fprintln(ssh_stderr)
_, _ = conn.Write([]byte{hook_return_value})
}
func serve_git_hooks(listener net.Listener) error {
for {
conn, err := listener.Accept()
if err != nil {
return err
}
go hooks_handle_connection(conn)
}
}
func get_ucred(conn net.Conn) (*syscall.Ucred, error) {
unix_conn := conn.(*net.UnixConn)
fd, err := unix_conn.File()
if err != nil {
func get_ucred(conn net.Conn) (ucred *syscall.Ucred, err error) {
var unix_conn *net.UnixConn = conn.(*net.UnixConn)
var fd *os.File
if fd, err = unix_conn.File(); err != nil {
return nil, err_get_fd } defer fd.Close()
ucred, err := syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
if err != nil {
if ucred, err = syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED); err != nil {
return nil, err_get_ucred
}
return ucred, nil
}
func all_zero_num_string(s string) bool {
for _, r := range s {
if r != '0' {
return false
}
}
return true
}
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "github.com/go-git/go-git/v5"
git_config "github.com/go-git/go-git/v5/config"
git_format_config "github.com/go-git/go-git/v5/plumbing/format/config"
)
// git_bare_init_with_default_hooks initializes a bare git repository with the
// forge-deployed hooks directory as the hooksPath.
func git_bare_init_with_default_hooks(repo_path string) (err error) {
repo, err := git.PlainInit(repo_path, true)
if err != nil {
var repo *git.Repository
var git_config *git_config.Config
if repo, err = git.PlainInit(repo_path, true); err != nil {
return err }
git_config, err := repo.Config()
if err != nil {
if git_config, err = repo.Config(); err != nil {
return err
}
git_config.Raw.SetOption("core", git_format_config.NoSubsection, "hooksPath", config.Hooks.Execs)
err = repo.SetConfig(git_config)
if err != nil {
if err = repo.SetConfig(git_config); err != nil {
return err } return nil }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "context" "errors" "io"
"os"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
)
// open_git_repo opens a git repository by group and repo name.
func open_git_repo(ctx context.Context, group_name, repo_name string) (repo *git.Repository, description string, repo_id int, err error) {
var fs_path string
err = database.QueryRow(ctx, "SELECT r.filesystem_path, COALESCE(r.description, ''), r.id FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1 AND r.name = $2;", group_name, repo_name).Scan(&fs_path, &description, &repo_id)
err = database.QueryRow(ctx, "SELECT r.filesystem_path, COALESCE(r.description, ''), r.id FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1 AND r.name = $2;", group_name, repo_name, ).Scan(&fs_path, &description, &repo_id)
if err != nil {
return
}
repo, err = git.PlainOpen(fs_path)
return
}
// go-git's tree entries are not friendly for use in HTML templates.
type display_git_tree_entry_t struct {
Name string
Mode string
Size int64
Is_file bool
Is_subtree bool
}
func build_display_git_tree(tree *object.Tree) []display_git_tree_entry_t {
display_git_tree := make([]display_git_tree_entry_t, 0)
func build_display_git_tree(tree *object.Tree) (display_git_tree []display_git_tree_entry_t) {
for _, entry := range tree.Entries {
display_git_tree_entry := display_git_tree_entry_t{}
os_mode, err := entry.Mode.ToOSFileMode()
if err != nil {
var err error
var os_mode os.FileMode
if os_mode, err = entry.Mode.ToOSFileMode(); err != nil {
display_git_tree_entry.Mode = "x---------"
} else {
display_git_tree_entry.Mode = os_mode.String()
}
display_git_tree_entry.Is_file = entry.Mode.IsFile()
display_git_tree_entry.Size, err = tree.Size(entry.Name)
if err != nil {
if display_git_tree_entry.Size, err = tree.Size(entry.Name); err != nil {
display_git_tree_entry.Size = 0 }
display_git_tree_entry.Name = strings.TrimPrefix(entry.Name, "/")
display_git_tree = append(display_git_tree, display_git_tree_entry)
}
return display_git_tree
}
func get_recent_commits(repo *git.Repository, head_hash plumbing.Hash, number_of_commits int) (recent_commits []*object.Commit, err error) {
commit_iter, err := repo.Log(&git.LogOptions{From: head_hash})
var commit_iter object.CommitIter
var this_recent_commit *object.Commit
commit_iter, err = repo.Log(&git.LogOptions{From: head_hash})
if err != nil {
return nil, err
}
recent_commits = make([]*object.Commit, 0)
defer commit_iter.Close()
if number_of_commits < 0 {
for {
this_recent_commit, err := commit_iter.Next()
this_recent_commit, err = commit_iter.Next()
if errors.Is(err, io.EOF) {
return recent_commits, nil
} else if err != nil {
return nil, err
}
recent_commits = append(recent_commits, this_recent_commit)
}
} else {
for range number_of_commits {
this_recent_commit, err := commit_iter.Next()
this_recent_commit, err = commit_iter.Next()
if errors.Is(err, io.EOF) {
return recent_commits, nil
} else if err != nil {
return nil, err
}
recent_commits = append(recent_commits, this_recent_commit)
}
}
return recent_commits, err
}
func get_patch_from_commit(commit_object *object.Commit) (parent_commit_hash plumbing.Hash, patch *object.Patch, ret_err error) {
parent_commit_object, err := commit_object.Parent(0)
func get_patch_from_commit(commit_object *object.Commit) (parent_commit_hash plumbing.Hash, patch *object.Patch, err error) {
var parent_commit_object *object.Commit
var commit_tree *object.Tree
parent_commit_object, err = commit_object.Parent(0)
if errors.Is(err, object.ErrParentNotFound) {
commit_tree, err := commit_object.Tree()
if err != nil {
ret_err = err
if commit_tree, err = commit_object.Tree(); err != nil {
return }
patch, err = (&object.Tree{}).Patch(commit_tree)
if err != nil {
ret_err = err
if patch, err = (&object.Tree{}).Patch(commit_tree); err != nil {
return
}
} else if err != nil {
ret_err = err
return
} else {
parent_commit_hash = parent_commit_object.Hash
patch, err = parent_commit_object.Patch(commit_object)
if err != nil {
ret_err = err
if patch, err = parent_commit_object.Patch(commit_object); err != nil {
return } } return }
// SPDX-License-Identifier: AGPL-3.0-only // SPDX-FileContributor: Runxi Yu <https://runxiyu.org> package main import ( "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" ) // get_ref_hash_from_type_and_name returns the hash of a reference given its // type and name as supplied in URL queries.
func get_ref_hash_from_type_and_name(repo *git.Repository, ref_type, ref_name string) (ref_hash plumbing.Hash, ret_err error) {
func get_ref_hash_from_type_and_name(repo *git.Repository, ref_type, ref_name string) (ref_hash plumbing.Hash, err error) {
var ref *plumbing.Reference
switch ref_type {
case "":
head, err := repo.Head()
if err != nil {
ret_err = err
if ref, err = repo.Head(); err != nil {
return }
ref_hash = head.Hash()
ref_hash = ref.Hash()
case "commit": ref_hash = plumbing.NewHash(ref_name) case "branch":
ref, err := repo.Reference(plumbing.NewBranchReferenceName(ref_name), true)
if err != nil {
ret_err = err
if ref, err = repo.Reference(plumbing.NewBranchReferenceName(ref_name), true); err != nil {
return } ref_hash = ref.Hash() case "tag":
ref, err := repo.Reference(plumbing.NewTagReferenceName(ref_name), true)
if err != nil {
ret_err = err
if ref, err = repo.Reference(plumbing.NewTagReferenceName(ref_name), true); err != nil {
return
}
ref_hash = ref.Hash()
default:
panic("Invalid ref type " + ref_type)
}
return
}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
package main
import (
"net/http"
)
func get_user_info_from_request(r *http.Request) (id int, username string, err error) {
session_cookie, err := r.Cookie("session")
if err != nil {
var session_cookie *http.Cookie
if session_cookie, err = r.Cookie("session"); err != nil {
return }
err = database.QueryRow(r.Context(), "SELECT user_id, COALESCE(username, '') FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.session_id = $1;", session_cookie.Value).Scan(&id, &username)
err = database.QueryRow( r.Context(), "SELECT user_id, COALESCE(username, '') FROM users u JOIN sessions s ON u.id = s.user_id WHERE s.session_id = $1;", session_cookie.Value, ).Scan(&id, &username)
return }
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
package main
import (
"net/http"
)
func handle_group_repos(w http.ResponseWriter, r *http.Request, params map[string]any) {
group_name := params["group_name"] repos, err := query_name_desc_list(r.Context(), "SELECT r.name, COALESCE(r.description, '') FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1;", group_name)
var group_name string var repos []name_desc_t var err error group_name = params["group_name"].(string) repos, err = query_name_desc_list(r.Context(), "SELECT r.name, COALESCE(r.description, '') FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1;", group_name)
if err != nil {
http.Error(w, "Error getting groups: "+err.Error(), http.StatusInternalServerError)
return
}
params["repos"] = repos
render_template(w, "group_repos", params)
}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
package main
import (
"net/http"
)
func handle_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
groups, err := query_name_desc_list(r.Context(), "SELECT name, COALESCE(description, '') FROM groups")
var err error var groups []name_desc_t groups, err = query_name_desc_list(r.Context(), "SELECT name, COALESCE(description, '') FROM groups")
if err != nil {
http.Error(w, "Error querying groups: "+err.Error(), http.StatusInternalServerError)
return
}
params["groups"] = groups
render_template(w, "index", params)
}
// SPDX-License-Identifier: AGPL-3.0-only
// SPDX-FileContributor: Runxi Yu <https://runxiyu.org>
package main
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"time"
"github.com/alexedwards/argon2id"
"github.com/jackc/pgx/v5"
)
func handle_login(w http.ResponseWriter, r *http.Request, params map[string]any) {
var username, password string var user_id int var password_hash string var err error var password_matches bool var cookie_value string var now time.Time var expiry time.Time var cookie http.Cookie
if r.Method != "POST" {
render_template(w, "login", params)
return
}
var user_id int
username := r.PostFormValue("username")
password := r.PostFormValue("password")
username = r.PostFormValue("username")
password = r.PostFormValue("password")
var password_hash string err := database.QueryRow(r.Context(), "SELECT id, COALESCE(password, '') FROM users WHERE username = $1", username).Scan(&user_id, &password_hash)
err = database.QueryRow(r.Context(), "SELECT id, COALESCE(password, '') FROM users WHERE username = $1", username, ).Scan(&user_id, &password_hash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
params["login_error"] = "Unknown username"
render_template(w, "login", params)
return
}
http.Error(w, "Error querying user information: "+err.Error(), http.StatusInternalServerError)
return
}
if password_hash == "" {
params["login_error"] = "User has no password"
render_template(w, "login", params)
return
}
match, err := argon2id.ComparePasswordAndHash(password, password_hash)
if err != nil {
if password_matches, err = argon2id.ComparePasswordAndHash(password, password_hash); err != nil {
http.Error(w, "Error comparing password and hash: "+err.Error(), http.StatusInternalServerError) return }
if !match {
if !password_matches {
params["login_error"] = "Invalid password" render_template(w, "login", params) return }
cookie_value, err := random_urlsafe_string(16)
if err != nil {
if cookie_value, err = random_urlsafe_string(16); err != nil {
http.Error(w, "Error getting random string: "+err.Error(), http.StatusInternalServerError) return }
now := time.Now() expiry := now.Add(time.Duration(config.HTTP.CookieExpiry) * time.Second)
now = time.Now() expiry = now.Add(time.Duration(config.HTTP.CookieExpiry) * time.Second)
cookie := http.Cookie{
cookie = http.Cookie{
Name: "session",
Value: cookie_value,
SameSite: http.SameSiteLaxMode,
HttpOnly: true,
Secure: false, // TODO
Expires: expiry,
Path: "/",
// TODO: Expire
}
http.SetCookie(w, &cookie)
_, err = database.Exec(r.Context(), "INSERT INTO sessions (user_id, session_id) VALUES ($1, $2)", user_id, cookie_value)
if err != nil {
http.Error(w, "Error inserting session: "+err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
// random_urlsafe_string generates a random string of the given entropic size
// using the URL-safe base64 encoding. The actual size of the string returned
// will be 4*sz.
func random_urlsafe_string(sz int) (string, error) {
r := make([]byte, 3*sz)
_, err := rand.Read(r)
if err != nil {
return "", fmt.Errorf("error generating random string: %w", err)
}
return base64.RawURLEncoding.EncodeToString(r), nil
}