Lindenii Project Forge
Commit info | |
---|---|
ID | dd95e2dbfad7f39060dc70f145d0e1478770e454 |
Author | Runxi Yu<me@runxiyu.org> |
Author date | Tue, 18 Feb 2025 10:23:44 +0800 |
Committer | Runxi Yu<me@runxiyu.org> |
Committer date | Tue, 18 Feb 2025 10:23:44 +0800 |
Actions | Get patch |
*.go: Add some comments for docs
package main import ( "context" )
// get_path_perm_by_group_repo_key returns the filesystem path and direct // access permission for a given repo and a provided ssh public key.
func get_path_perm_by_group_repo_key(ctx context.Context, group_name, repo_name, ssh_pubkey string) (filesystem_path string, access bool, err error) { err = database.QueryRow(ctx, `SELECT r.filesystem_path, CASE WHEN ugr.user_id IS NOT NULL THEN TRUE ELSE FALSE END AS has_role_in_group FROM groups g JOIN repos r ON r.group_id = g.id LEFT JOIN ssh_public_keys s ON s.key_string = $3 LEFT JOIN users u ON u.id = s.user_id LEFT JOIN user_group_roles ugr ON ugr.group_id = g.id AND ugr.user_id = u.id WHERE g.name = $1 AND r.name = $2;`, group_name, repo_name, ssh_pubkey, ).Scan(&filesystem_path, &access) return }
package main import ( "context" )
// 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 { return nil, err } defer rows.Close() var result []T for rows.Next() { var item T if err := rows.Scan(&item); err != nil { return nil, err } result = append(result, item) } 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 { 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 { 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 }
package main import ( "bytes" "fmt" "strings" "time" "github.com/go-git/go-git/v5/plumbing/object" "go.lindenii.runxiyu.org/lindenii-common/misc" )
// 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 { return "", misc.Wrap_one_error(err_getting_patch_of_commit, err) } var buf bytes.Buffer author := commit.Author date := author.When.Format(time.RFC1123Z) 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 }
package main import ( "errors" "io" "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 { 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 { return err } defer dst_fd.Close() _, err = io.Copy(dst_fd, src_fd) if 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 { 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) { return err } } return nil }
package main import ( "bytes" "encoding/binary" "errors" "fmt" "io" "net" "os" "path/filepath" "strings" "syscall" ) 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) { defer conn.Close()
// There aren't reasonable cases where someone would run this as // another user.
ucred, err := get_ucred(conn) if err != nil { conn.Write([]byte{1}) fmt.Fprintln(conn, "Unable to get peer credentials:", err.Error()) return } if ucred.Uid != uint32(os.Getuid()) { conn.Write([]byte{1}) fmt.Fprintln(conn, "UID mismatch") return } cookie := make([]byte, 64) _, err = conn.Read(cookie) if err != nil { conn.Write([]byte{1}) fmt.Fprintln(conn, "Failed to read cookie:", err.Error()) return } pack_to_hook, ok := pack_to_hook_by_cookie.Load(string(cookie)) if !ok { conn.Write([]byte{1}) fmt.Fprintln(conn, "Invalid handler cookie") return } var argc64 uint64 err = binary.Read(conn, binary.NativeEndian, &argc64) if err != nil { conn.Write([]byte{1}) fmt.Fprintln(conn, "Failed to read argc:", err.Error()) return } 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 { conn.Write([]byte{1}) fmt.Fprintln(conn, "Failed to read arg:", err.Error()) return } 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 { fmt.Fprintln(conn, "Failed to read to the stdin buffer:", err.Error()) } switch filepath.Base(args[0]) { case "pre-receive": if pack_to_hook.direct_access { conn.Write([]byte{0}) } else { ref_ok := make(map[string]uint8) // 0 for ok // 1 for rejection due to not a contrib branch // 2 for rejection due to not being a new branch for { line, err := stdin.ReadString('\n') if errors.Is(err, io.EOF) { break } line = line[:len(line)-1] old_oid, rest, found := strings.Cut(line, " ") if !found { conn.Write([]byte{1}) fmt.Fprintln(conn, "Invalid pre-receive line:", line) break } new_oid, ref_name, found := strings.Cut(rest, " ") if !found { conn.Write([]byte{1}) fmt.Fprintln(conn, "Invalid pre-receive line:", line) break } _ = new_oid if strings.HasPrefix(ref_name, "refs/heads/contrib/") { if all_zero_num_string(old_oid) { ref_ok[ref_name] = 0 } else { ref_ok[ref_name] = 2 } } else { ref_ok[ref_name] = 1 } } if or_all_in_map(ref_ok) == 0 { conn.Write([]byte{0}) fmt.Fprintln(conn, "Stuff") } else { conn.Write([]byte{1}) for ref, status := range ref_ok { switch status { case 0: fmt.Fprintln(conn, "Acceptable", ref) case 1: fmt.Fprintln(conn, "Not in the contrib/ namespace", ref) case 2: fmt.Fprintln(conn, "Branch already exists", ref) default: panic("Invalid branch status") } } } } default: conn.Write([]byte{1}) fmt.Fprintln(conn, "Invalid hook:", args[0]) } } 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 { return nil, err_get_fd } defer fd.Close() ucred, err := syscall.GetsockoptUcred(int(fd.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED) if 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 } func or_all_in_map[K comparable, V uint8 | uint16 | uint32 | uint64](m map[K]V) (result V) { for _, value := range m { result |= value } return }
package main import ( "github.com/go-git/go-git/v5" 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 { return err } git_config, err := repo.Config() if 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 { return err } return nil }
package main import ( "context" "errors" "io" "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" "go.lindenii.runxiyu.org/lindenii-common/misc" ) var ( err_getting_commit_tree = errors.New("Error getting commit tree") err_getting_patch_of_commit = errors.New("Error getting patch of commit") err_getting_parent_commit_object = errors.New("Error getting parent commit 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, err error) { var fs_path string err = database.QueryRow(ctx, "SELECT r.filesystem_path, COALESCE(r.description, '') 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) if err != nil { return nil, "", err } 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) for _, entry := range tree.Entries { display_git_tree_entry := display_git_tree_entry_t{} os_mode, err := entry.Mode.ToOSFileMode() if err != nil {
display_git_tree_entry.Mode = "x---"
display_git_tree_entry.Mode = "x---------"
} else {
display_git_tree_entry.Mode = os_mode.String()[:4]
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 { 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 } var err_get_recent_commits = errors.New("Error getting recent commits") 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}) if err != nil { err = misc.Wrap_one_error(err_get_recent_commits, err) 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() if errors.Is(err, io.EOF) { return recent_commits, nil } else if err != nil { err = misc.Wrap_one_error(err_get_recent_commits, err) return nil, err } recent_commits = append(recent_commits, this_recent_commit) } } else { for range number_of_commits { this_recent_commit, err := commit_iter.Next() if errors.Is(err, io.EOF) { return recent_commits, nil } else if err != nil { err = misc.Wrap_one_error(err_get_recent_commits, err) 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) if errors.Is(err, object.ErrParentNotFound) { commit_tree, err := commit_object.Tree() if err != nil { ret_err = misc.Wrap_one_error(err_getting_commit_tree, err) return } patch, err = (&object.Tree{}).Patch(commit_tree) if err != nil { ret_err = misc.Wrap_one_error(err_getting_patch_of_commit, err) return } } else if err != nil { ret_err = misc.Wrap_one_error(err_getting_parent_commit_object, err) return } else { parent_commit_hash = parent_commit_object.Hash patch, err = parent_commit_object.Patch(commit_object) if err != nil { ret_err = misc.Wrap_one_error(err_getting_patch_of_commit, err) return } } return }
package main import ( "errors" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "go.lindenii.runxiyu.org/lindenii-common/misc" ) var ( err_getting_tag_reference = errors.New("Error getting tag reference") err_getting_branch_reference = errors.New("Error getting branch reference") err_getting_head = errors.New("Error getting HEAD") )
// 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) { switch ref_type { case "": head, err := repo.Head() if err != nil { ret_err = misc.Wrap_one_error(err_getting_head, err) return } ref_hash = head.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 = misc.Wrap_one_error(err_getting_branch_reference, err) return } ref_hash = ref.Hash() case "tag": ref, err := repo.Reference(plumbing.NewTagReferenceName(ref_name), true) if err != nil { ret_err = misc.Wrap_one_error(err_getting_tag_reference, err) return } ref_hash = ref.Hash() default: panic("Invalid ref type " + ref_type) } return }
package main
// global_data is passed as "global" when rendering HTML templates.
var global_data = map[string]any{ "server_public_key_string": &server_public_key_string, "server_public_key_fingerprint": &server_public_key_fingerprint, "forge_version": VERSION, // Some other ones are populated after config parsing }
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) { if r.Method != "POST" { render_template(w, "login", params) return } var user_id int username := r.PostFormValue("username") password := r.PostFormValue("password") var password_hash string err := database.QueryRow(r.Context(), "SELECT id, 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 } match, err := argon2id.ComparePasswordAndHash(password, password_hash) if err != nil { http.Error(w, "Error comparing password and hash: "+err.Error(), http.StatusInternalServerError) return } if !match { params["login_error"] = "Invalid password" render_template(w, "login", params) return } cookie_value, err := random_urlsafe_string(16) if 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) 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 }
package main import ( "fmt" "net/http" "strings" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/format/diff" "go.lindenii.runxiyu.org/lindenii-common/misc" )
// The file patch type from go-git isn't really usable in HTML templates // either.
type usable_file_patch struct { From diff.File To diff.File Chunks []usable_chunk } type usable_chunk struct { Operation diff.Operation Content string } func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]any) { group_name, repo_name, commit_id_specified_string := params["group_name"].(string), params["repo_name"].(string), params["commit_id"].(string) repo, description, err := open_git_repo(r.Context(), group_name, repo_name) if err != nil { http.Error(w, "Error opening repo: "+err.Error(), http.StatusInternalServerError) return } params["repo_description"] = description commit_id_specified_string_without_suffix := strings.TrimSuffix(commit_id_specified_string, ".patch") commit_id := plumbing.NewHash(commit_id_specified_string_without_suffix) commit_object, err := repo.CommitObject(commit_id) if err != nil { http.Error(w, "Error getting commit object: "+err.Error(), http.StatusInternalServerError) return } if commit_id_specified_string_without_suffix != commit_id_specified_string { patch, err := format_patch_from_commit(commit_object) if err != nil { http.Error(w, "Error formatting patch: "+err.Error(), http.StatusInternalServerError) return } fmt.Fprintln(w, patch) return } commit_id_string := commit_object.Hash.String() if commit_id_string != commit_id_specified_string { http.Redirect(w, r, commit_id_string, http.StatusSeeOther) return } params["commit_object"] = commit_object params["commit_id"] = commit_id_string parent_commit_hash, patch, err := get_patch_from_commit(commit_object) if err != nil { http.Error(w, "Error getting patch from commit: "+err.Error(), http.StatusInternalServerError) return } params["parent_commit_hash"] = parent_commit_hash.String() params["patch"] = patch // TODO: Remove unnecessary context // TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color usable_file_patches := make([]usable_file_patch, 0) for _, file_patch := range patch.FilePatches() { from, to := file_patch.Files() if from == nil { from = fake_diff_file_null } if to == nil { to = fake_diff_file_null } chunks := []usable_chunk{} for _, chunk := range file_patch.Chunks() { content := chunk.Content() if len(content) > 0 && content[0] == '\n' { content = "\n" + content } // Horrible hack to fix how browsers newlines that immediately proceed <pre> chunks = append(chunks, usable_chunk{ Operation: chunk.Type(), Content: content, }) } usable_file_patch := usable_file_patch{ Chunks: chunks, From: from, To: to, } usable_file_patches = append(usable_file_patches, usable_file_patch) } params["file_patches"] = usable_file_patches render_template(w, "repo_commit", params) } type fake_diff_file struct { hash plumbing.Hash mode filemode.FileMode path string } func (f fake_diff_file) Hash() plumbing.Hash { return f.hash } func (f fake_diff_file) Mode() filemode.FileMode { return f.mode } func (f fake_diff_file) Path() string { return f.path } var fake_diff_file_null = fake_diff_file{ hash: plumbing.NewHash("0000000000000000000000000000000000000000"), mode: misc.First_or_panic(filemode.New("100644")), path: "", }
package main import "net/http"
// render_template abstracts out the annoyances of reporting template rendering // errors.
func render_template(w http.ResponseWriter, template_name string, params map[string]any) { err := templates.ExecuteTemplate(w, template_name, params) if err != nil { http.Error(w, "Error rendering template: "+err.Error(), http.StatusInternalServerError) } }
package main import ( "net/url" "strings" )
// We don't use path.Join because it collapses multiple slashes into one.
func generate_ssh_remote_url(group_name, repo_name string) string { return strings.TrimSuffix(config.SSH.Root, "/") + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name) } func generate_http_remote_url(group_name, repo_name string) string { return strings.TrimSuffix(config.HTTP.Root, "/") + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name) }
package main import ( "embed" "html/template" "io/fs" "net/http" )
// We embed all source for easy AGPL compliance.
//go:embed .gitignore .gitattributes //go:embed LICENSE README.md //go:embed *.go go.mod go.sum //go:embed *.scfg //go:embed Makefile //go:embed schema.sql //go:embed static/* templates/* //go:embed git_hooks_client/*.c //go:embed vendor/* var source_fs embed.FS
var source_handler http.Handler func init() { source_handler = http.StripPrefix( "/:/source/", http.FileServer(http.FS(source_fs)), ) }
var source_handler = http.StripPrefix( "/:/source/", http.FileServer(http.FS(source_fs)), )
//go:embed templates/* static/* git_hooks_client/git_hooks_client var resources_fs embed.FS var templates *template.Template
func load_templates() (err error) { templates, err = template.New("templates").Funcs(template.FuncMap{ "first_line": first_line, "base_name": base_name, }).ParseFS(resources_fs, "templates/*") return err } var static_handler http.Handler func init() { static_fs, err := fs.Sub(resources_fs, "static") if err != nil { panic(err) } static_handler = http.StripPrefix("/:/static/", http.FileServer(http.FS(static_fs))) }
package main import (
"crypto/rand"
"errors" "fmt" "os" "os/exec" glider_ssh "github.com/gliderlabs/ssh" "go.lindenii.runxiyu.org/lindenii-common/cmap" ) var err_unauthorized_push = errors.New("You are not authorized to push to this repository") type pack_to_hook_t struct { session *glider_ssh.Session pubkey string direct_access bool repo_path string } var pack_to_hook_by_cookie = cmap.Map[string, pack_to_hook_t]{}
// ssh_handle_receive_pack handles attempts to push to repos.
func ssh_handle_receive_pack(session glider_ssh.Session, pubkey string, repo_identifier string) (err error) {
// Here "access" means direct maintainer access. access=false doesn't // necessarily mean the push is declined. This decision is delegated to // the pre-receive hook, which is then handled by git_hooks_handle.go // while being aware of the refs to be updated.
repo_path, access, err := get_repo_path_perms_from_ssh_path_pubkey(session.Context(), repo_identifier, pubkey) if err != nil { return err } cookie, err := random_urlsafe_string(16) if err != nil { fmt.Fprintln(session.Stderr(), "Error while generating cookie:", err) } pack_to_hook_by_cookie.Store(cookie, pack_to_hook_t{ session: &session, pubkey: pubkey, direct_access: access, repo_path: repo_path, }) defer pack_to_hook_by_cookie.Delete(cookie)
// The Delete won't execute until proc.Wait returns unless something // horribly wrong such as a panic occurs.
proc := exec.CommandContext(session.Context(), "git-receive-pack", repo_path) proc.Env = append(os.Environ(), "LINDENII_FORGE_HOOKS_SOCKET_PATH="+config.Hooks.Socket, "LINDENII_FORGE_HOOKS_COOKIE="+cookie, ) proc.Stdin = session proc.Stdout = session proc.Stderr = session.Stderr() err = proc.Start() if err != nil { fmt.Fprintln(session.Stderr(), "Error while starting process:", err) return err } err = proc.Wait() if exitError, ok := err.(*exec.ExitError); ok { fmt.Fprintln(session.Stderr(), "Process exited with error", exitError.ExitCode()) } else if err != nil { fmt.Fprintln(session.Stderr(), "Error while waiting for process:", err) } return err }
func random_string(sz int) (string, error) { r := make([]byte, sz) _, err := rand.Read(r) return string(r), err }
package main import ( "fmt" "os" "os/exec" glider_ssh "github.com/gliderlabs/ssh" )
// ssh_handle_upload_pack handles clones/fetches. It just uses git-upload-pack // and has no ACL checks.
func ssh_handle_upload_pack(session glider_ssh.Session, pubkey string, repo_identifier string) (err error) { repo_path, _, err := get_repo_path_perms_from_ssh_path_pubkey(session.Context(), repo_identifier, pubkey) if err != nil { return err } proc := exec.CommandContext(session.Context(), "git-upload-pack", repo_path) proc.Env = append(os.Environ(), "LINDENII_FORGE_HOOKS_SOCKET_PATH="+config.Hooks.Socket) proc.Stdin = session proc.Stdout = session proc.Stderr = session.Stderr() err = proc.Start() if err != nil { fmt.Fprintln(session.Stderr(), "Error while starting process:", err) return err } err = proc.Wait() if exitError, ok := err.(*exec.ExitError); ok { fmt.Fprintln(session.Stderr(), "Process exited with error", exitError.ExitCode()) } else if err != nil { fmt.Fprintln(session.Stderr(), "Error while waiting for process:", err) } return err }
package main import ( "context" "errors" "net/url" "strings" ) var err_ssh_illegal_endpoint = errors.New("Illegal endpoint during SSH access")
func get_repo_path_perms_from_ssh_path_pubkey(ctx context.Context, ssh_path string, ssh_pubkey string) (repo_path string, access bool, err error) {
func get_repo_path_perms_from_ssh_path_pubkey(ctx context.Context, ssh_path string, ssh_pubkey string) (repo_path string, direct_access bool, err error) {
segments := strings.Split(strings.TrimPrefix(ssh_path, "/"), "/") for i, segment := range segments { var err error segments[i], err = url.PathUnescape(segment) if err != nil { return "", false, err } } if segments[0] == ":" { return "", false, err_ssh_illegal_endpoint } separator_index := -1 for i, part := range segments { if part == ":" { separator_index = i break } } if segments[len(segments)-1] == "" { segments = segments[:len(segments)-1] } switch { case separator_index == -1: return "", false, err_ssh_illegal_endpoint case len(segments) <= separator_index+2: return "", false, err_ssh_illegal_endpoint } group_name := segments[0] module_type := segments[separator_index+1] module_name := segments[separator_index+2] switch module_type { case "repos": return get_path_perm_by_group_repo_key(ctx, group_name, module_name, ssh_pubkey) default: return "", false, err_ssh_illegal_endpoint } }