summaryrefslogtreecommitdiff
path: root/bin/gitano-command.cgi.in
blob: 2fa1db28b0954050659c83335eaed8ccf199ee52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
-- @@SHEBANG
-- -*- Lua -*-
-- command cgi
--
-- Git (with) Augmented network operations -- User authentication wrapper
--
-- Copyright 2014 Codethink Ltd
--
--

-- @@GITANO_LUA_PATH

local gitano = require "gitano"
local gall = require "gall"
local luxio = require "luxio"
local sio = require "luxio.simple"

-- @@GITANO_BIN_PATH
-- @@GITANO_SHARE_PATH
-- @@GITANO_PLUGIN_PATH

local stdout = sio.stdout

function url_decode(str)
  str = string.gsub (str, "+", " ")
  str = string.gsub (str, "%%(%x%x)",
      function(h) return string.char(tonumber(h,16)) end)
  str = string.gsub (str, "\r\n", "\n")
  return str
end

if os.getenv("QUERY_STRING") then
   local query_string = url_decode(os.getenv("QUERY_STRING"))
   local cmdline = query_string

   local _, e = string.find(query_string, "cmd=")

   if not e then
      stdout:write("Status: 400 Bad request\r\n\r\n")
      stdout:write("Malformed command line, format: ?cmd=arg0 arg1 ... argn\n")
      return
   end

   cmdline = string.sub(query_string, e + 1, #query_string)

   if cmdline == '' then
      stdout:write("Status: 400 Bad request\r\n\r\n")
      stdout:write("Malformed command line, format: ?cmd=arg0 arg1 ... argn\n")
      return
   end

   local user = os.getenv("REMOTE_USER") or "gitano/anonymous"

   gitano.log.buffer_output()

   local authorized, cmd, parsed_cmdline, config, env, repo =
      gitano.auth.is_authorized(user, "http", cmdline, os.getenv("GITANO_ROOT"))

   if authorized then
      local exit = gitano.util.run_command(cmd, cmdline, parsed_cmdline,
			       user, config, env, repo)

      stdout:write("Status: " .. (exit == 0 and "200 OK" or "400 Bad request")
         .. "\r\n\r\n")
      stdout:write(gitano.log.get_buffered_output() or "")
   else
      stdout:write("Status: 403 Forbidden\r\n\r\n")
      stdout:write(gitano.log.get_buffered_output() or "")
   end
else
   stdout:write("Status: 400 Bad request\r\n\r\n")
   stdout:write("Malformed command line, format: ?cmd=arg0 arg1 ... argn\n")
end