10234: 10263: Use a GitoliteHome configuration entry instead of passing through gitol...
[arvados.git] / services / arv-git-httpd / git_handler.go
1 package main
2
3 import (
4         "log"
5         "net"
6         "net/http"
7         "net/http/cgi"
8         "os"
9 )
10
11 // gitHandler is an http.Handler that invokes git-http-backend (or
12 // whatever backend is configured) via CGI, with appropriate
13 // environment variables in place for git-http-backend or
14 // gitolite-shell.
15 type gitHandler struct {
16         cgi.Handler
17 }
18
19 func newGitHandler() http.Handler {
20         var env []string
21         path := os.Getenv("PATH")
22         if theConfig.GitoliteHome != "" {
23                 env = append(env,
24                         "GITOLITE_HTTP_HOME="+theConfig.GitoliteHome,
25                         "GL_BYPASS_ACCESS_CHECKS=1")
26                 path = path + ":" + theConfig.GitoliteHome + "/bin"
27         }
28         env = append(env,
29                 "GIT_PROJECT_ROOT="+theConfig.RepoRoot,
30                 "GIT_HTTP_EXPORT_ALL=",
31                 "SERVER_ADDR="+theConfig.Listen,
32                 "PATH="+path)
33         return &gitHandler{
34                 Handler: cgi.Handler{
35                         Path: theConfig.GitCommand,
36                         Dir:  theConfig.RepoRoot,
37                         Env:  env,
38                         Args: []string{"http-backend"},
39                 },
40         }
41 }
42
43 func (h *gitHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
44         remoteHost, remotePort, err := net.SplitHostPort(r.RemoteAddr)
45         if err != nil {
46                 log.Printf("Internal error: SplitHostPort(r.RemoteAddr==%q): %s", r.RemoteAddr, err)
47                 w.WriteHeader(http.StatusInternalServerError)
48                 return
49         }
50
51         // Copy the wrapped cgi.Handler, so these request-specific
52         // variables don't leak into the next request.
53         handlerCopy := h.Handler
54         handlerCopy.Env = append(handlerCopy.Env,
55                 // In Go1.5 we can skip this, net/http/cgi will do it for us:
56                 "REMOTE_HOST="+remoteHost,
57                 "REMOTE_ADDR="+remoteHost,
58                 "REMOTE_PORT="+remotePort,
59                 // Ideally this would be a real username:
60                 "REMOTE_USER="+r.RemoteAddr,
61         )
62         handlerCopy.ServeHTTP(w, r)
63 }