git-serve.py 6.93 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/python3

import configparser
import os
import re
import shlex
import sys

9
10
import db

11
config = configparser.RawConfigParser()
Lukas Fleischer's avatar
Lukas Fleischer committed
12
config.read(os.path.dirname(os.path.realpath(__file__)) + "/../conf/config")
13

14
repo_path = config.get('serve', 'repo-path')
15
16
repo_regex = config.get('serve', 'repo-regex')
git_shell_cmd = config.get('serve', 'git-shell-cmd')
17
git_update_cmd = config.get('serve', 'git-update-cmd')
18
ssh_cmdline = config.get('serve', 'ssh-cmdline')
19

Lukas Fleischer's avatar
Lukas Fleischer committed
20
enable_maintenance = config.getboolean('options', 'enable-maintenance')
21
maintenance_exc = config.get('options', 'maintenance-exceptions').split()
Lukas Fleischer's avatar
Lukas Fleischer committed
22

23

24
def pkgbase_from_name(pkgbase):
25
26
    conn = db.Connection()
    cur = conn.execute("SELECT ID FROM PackageBases WHERE Name = ?", [pkgbase])
27

28
29
    row = cur.fetchone()
    return row[0] if row else None
30

31

32
def pkgbase_exists(pkgbase):
Mark Weiman's avatar
Mark Weiman committed
33
    return pkgbase_from_name(pkgbase) is not None
34

35

36
def list_repos(user):
37
    conn = db.Connection()
38

39
    cur = conn.execute("SELECT ID FROM Users WHERE Username = ?", [user])
40
41
    userid = cur.fetchone()[0]
    if userid == 0:
42
        die('{:s}: unknown user: {:s}'.format(action, user))
43

44
45
    cur = conn.execute("SELECT Name, PackagerUID FROM PackageBases " +
                       "WHERE MaintainerUID = ?", [userid])
46
47
    for row in cur:
        print((' ' if row[1] else '*') + row[0])
48
    conn.close()
49

50

51
def create_pkgbase(pkgbase, user):
52
    if not re.match(repo_regex, pkgbase):
53
        die('{:s}: invalid repository name: {:s}'.format(action, pkgbase))
54
    if pkgbase_exists(pkgbase):
55
        die('{:s}: package base already exists: {:s}'.format(action, pkgbase))
56

57
    conn = db.Connection()
58

59
    cur = conn.execute("SELECT ID FROM Users WHERE Username = ?", [user])
60
61
    userid = cur.fetchone()[0]
    if userid == 0:
62
        die('{:s}: unknown user: {:s}'.format(action, user))
63

64
65
66
67
    cur = conn.execute("INSERT INTO PackageBases (Name, SubmittedTS, " +
                       "ModifiedTS, SubmitterUID, MaintainerUID) VALUES " +
                       "(?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), ?, ?)",
                       [pkgbase, userid, userid])
68
69
    pkgbase_id = cur.lastrowid

70
71
72
    cur = conn.execute("INSERT INTO PackageNotifications " +
                       "(PackageBaseID, UserID) VALUES (?, ?)",
                       [pkgbase_id, userid])
73

74
75
    conn.commit()
    conn.close()
76

77

78
def pkgbase_set_keywords(pkgbase, keywords):
79
80
81
82
    pkgbase_id = pkgbase_from_name(pkgbase)
    if not pkgbase_id:
        die('{:s}: package base not found: {:s}'.format(action, pkgbase))

83
    conn = db.Connection()
84

85
86
    conn.execute("DELETE FROM PackageKeywords WHERE PackageBaseID = ?",
                 [pkgbase_id])
87
    for keyword in keywords:
88
89
        conn.execute("INSERT INTO PackageKeywords (PackageBaseID, Keyword) " +
                     "VALUES (?, ?)", [pkgbase_id, keyword])
90

91
92
    conn.commit()
    conn.close()
93

94

95
def pkgbase_has_write_access(pkgbase, user):
96
97
98
99
100
101
102
103
104
105
    conn = db.Connection()

    cur = conn.execute("SELECT COUNT(*) FROM PackageBases " +
                       "LEFT JOIN PackageComaintainers " +
                       "ON PackageComaintainers.PackageBaseID = PackageBases.ID " +
                       "INNER JOIN Users " +
                       "ON Users.ID = PackageBases.MaintainerUID " +
                       "OR PackageBases.MaintainerUID IS NULL " +
                       "OR Users.ID = PackageComaintainers.UsersID " +
                       "WHERE Name = ? AND Username = ?", [pkgbase, user])
106
107
    return cur.fetchone()[0] > 0

108

109
def die(msg):
110
    sys.stderr.write("{:s}\n".format(msg))
111
112
    exit(1)

113

114
def die_with_help(msg):
115
    die(msg + "\nTry `{:s} help` for a list of commands.".format(ssh_cmdline))
116

117

118
119
120
121
def warn(msg):
    sys.stderr.write("warning: {:s}\n".format(msg))


122
123
124
125
126
127
user = os.environ.get('AUR_USER')
privileged = (os.environ.get('AUR_PRIVILEGED', '0') == '1')
ssh_cmd = os.environ.get('SSH_ORIGINAL_COMMAND')
ssh_client = os.environ.get('SSH_CLIENT')

if not ssh_cmd:
128
    die_with_help("Interactive shell is disabled.")
129
cmdargv = shlex.split(ssh_cmd)
130
action = cmdargv[0]
131
remote_addr = ssh_client.split(' ')[0] if ssh_client else None
132

Lukas Fleischer's avatar
Lukas Fleischer committed
133
if enable_maintenance:
134
    if remote_addr not in maintenance_exc:
135
        die("The AUR is down due to maintenance. We will be back soon.")
Lukas Fleischer's avatar
Lukas Fleischer committed
136

137
if action == 'git-upload-pack' or action == 'git-receive-pack':
138
    if len(cmdargv) < 2:
139
        die_with_help("{:s}: missing path".format(action))
140
141

    path = cmdargv[1].rstrip('/')
142
143
144
145
    if not path.startswith('/'):
        path = '/' + path
    if not path.endswith('.git'):
        path = path + '.git'
146
147
    pkgbase = path[1:-4]
    if not re.match(repo_regex, pkgbase):
148
        die('{:s}: invalid repository name: {:s}'.format(action, pkgbase))
149
150

    if not pkgbase_exists(pkgbase):
151
        create_pkgbase(pkgbase, user)
152

153
    if action == 'git-receive-pack':
154
        if not privileged and not pkgbase_has_write_access(pkgbase, user):
155
            die('{:s}: permission denied: {:s}'.format(action, user))
156

157
158
    os.environ["AUR_USER"] = user
    os.environ["AUR_PKGBASE"] = pkgbase
159
160
    os.environ["GIT_NAMESPACE"] = pkgbase
    cmd = action + " '" + repo_path + "'"
161
    os.execl(git_shell_cmd, git_shell_cmd, '-c', cmd)
162
elif action == 'set-keywords':
163
164
    if len(cmdargv) < 2:
        die_with_help("{:s}: missing repository name".format(action))
165
    pkgbase_set_keywords(cmdargv[1], cmdargv[2:])
166
167
elif action == 'list-repos':
    if len(cmdargv) > 1:
168
        die_with_help("{:s}: too many arguments".format(action))
169
    list_repos(user)
170
171
elif action == 'setup-repo':
    if len(cmdargv) < 2:
172
        die_with_help("{:s}: missing repository name".format(action))
173
    if len(cmdargv) > 2:
174
        die_with_help("{:s}: too many arguments".format(action))
175
    warn('{:s} is deprecated. Use `git push` to create new repositories.'.format(action))
176
    create_pkgbase(cmdargv[1], user)
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
elif action == 'restore':
    if len(cmdargv) < 2:
        die_with_help("{:s}: missing repository name".format(action))
    if len(cmdargv) > 2:
        die_with_help("{:s}: too many arguments".format(action))

    pkgbase = cmdargv[1]
    if not re.match(repo_regex, pkgbase):
        die('{:s}: invalid repository name: {:s}'.format(action, pkgbase))

    if pkgbase_exists(pkgbase):
        die('{:s}: package base exists: {:s}'.format(action, pkgbase))
    create_pkgbase(pkgbase, user)

    os.environ["AUR_USER"] = user
    os.environ["AUR_PKGBASE"] = pkgbase
    os.execl(git_update_cmd, git_update_cmd, 'restore')
194
195
elif action == 'help':
    die("Commands:\n" +
196
197
198
199
200
201
202
        "  help                         Show this help message and exit.\n" +
        "  list-repos                   List all your repositories.\n" +
        "  restore <name>               Restore a deleted package base.\n" +
        "  set-keywords <name> [...]    Change package base keywords.\n" +
        "  setup-repo <name>            Create an empty repository.\n" +
        "  git-receive-pack             Internal command used with Git.\n" +
        "  git-upload-pack              Internal command used with Git.")
203
else:
204
    die_with_help("invalid command: {:s}".format(action))