git-serve: Refactor environment variable access
[aur.git] / git-interface / git-serve.py
blobaa5f1c93f5e1a4b0832ee3f070ceff6dafca0857
1 #!/usr/bin/python3
3 import configparser
4 import mysql.connector
5 import os
6 import re
7 import shlex
8 import sys
10 config = configparser.RawConfigParser()
11 config.read(os.path.dirname(os.path.realpath(__file__)) + "/../conf/config")
13 aur_db_host = config.get('database', 'host')
14 aur_db_name = config.get('database', 'name')
15 aur_db_user = config.get('database', 'user')
16 aur_db_pass = config.get('database', 'password')
17 aur_db_socket = config.get('database', 'socket')
19 repo_path = config.get('serve', 'repo-path')
20 repo_regex = config.get('serve', 'repo-regex')
21 git_shell_cmd = config.get('serve', 'git-shell-cmd')
22 git_update_cmd = config.get('serve', 'git-update-cmd')
23 ssh_cmdline = config.get('serve', 'ssh-cmdline')
25 enable_maintenance = config.getboolean('options', 'enable-maintenance')
26 maintenance_exc = config.get('options', 'maintenance-exceptions').split()
29 def pkgbase_from_name(pkgbase):
30 db = mysql.connector.connect(host=aur_db_host, user=aur_db_user,
31 passwd=aur_db_pass, db=aur_db_name,
32 unix_socket=aur_db_socket)
33 cur = db.cursor()
34 cur.execute("SELECT ID FROM PackageBases WHERE Name = %s", [pkgbase])
35 db.close()
37 row = cur.fetchone()
38 return row[0] if row else None
41 def pkgbase_exists(pkgbase):
42 return pkgbase_from_name(pkgbase) is not None
45 def list_repos(user):
46 db = mysql.connector.connect(host=aur_db_host, user=aur_db_user,
47 passwd=aur_db_pass, db=aur_db_name,
48 unix_socket=aur_db_socket)
49 cur = db.cursor()
51 cur.execute("SELECT ID FROM Users WHERE Username = %s ", [user])
52 userid = cur.fetchone()[0]
53 if userid == 0:
54 die('{:s}: unknown user: {:s}'.format(action, user))
56 cur.execute("SELECT Name, PackagerUID FROM PackageBases " +
57 "WHERE MaintainerUID = %s ", [userid])
58 for row in cur:
59 print((' ' if row[1] else '*') + row[0])
60 db.close()
63 def create_pkgbase(pkgbase, user):
64 if not re.match(repo_regex, pkgbase):
65 die('{:s}: invalid repository name: {:s}'.format(action, pkgbase))
66 if pkgbase_exists(pkgbase):
67 die('{:s}: package base already exists: {:s}'.format(action, pkgbase))
69 db = mysql.connector.connect(host=aur_db_host, user=aur_db_user,
70 passwd=aur_db_pass, db=aur_db_name,
71 unix_socket=aur_db_socket)
72 cur = db.cursor()
74 cur.execute("SELECT ID FROM Users WHERE Username = %s ", [user])
75 userid = cur.fetchone()[0]
76 if userid == 0:
77 die('{:s}: unknown user: {:s}'.format(action, user))
79 cur.execute("INSERT INTO PackageBases (Name, SubmittedTS, ModifiedTS, " +
80 "SubmitterUID, MaintainerUID) VALUES (%s, UNIX_TIMESTAMP(), " +
81 "UNIX_TIMESTAMP(), %s, %s)", [pkgbase, userid, userid])
82 pkgbase_id = cur.lastrowid
84 cur.execute("INSERT INTO PackageNotifications (PackageBaseID, UserID) " +
85 "VALUES (%s, %s)", [pkgbase_id, userid])
87 db.commit()
88 db.close()
91 def pkgbase_set_keywords(pkgbase, keywords):
92 pkgbase_id = pkgbase_from_name(pkgbase)
93 if not pkgbase_id:
94 die('{:s}: package base not found: {:s}'.format(action, pkgbase))
96 db = mysql.connector.connect(host=aur_db_host, user=aur_db_user,
97 passwd=aur_db_pass, db=aur_db_name,
98 unix_socket=aur_db_socket)
99 cur = db.cursor()
101 cur.execute("DELETE FROM PackageKeywords WHERE PackageBaseID = %s",
102 [pkgbase_id])
103 for keyword in keywords:
104 cur.execute("INSERT INTO PackageKeywords (PackageBaseID, Keyword) "
105 "VALUES (%s, %s)", [pkgbase_id, keyword])
107 db.commit()
108 db.close()
111 def pkgbase_has_write_access(pkgbase, user):
112 db = mysql.connector.connect(host=aur_db_host, user=aur_db_user,
113 passwd=aur_db_pass, db=aur_db_name,
114 unix_socket=aur_db_socket, buffered=True)
115 cur = db.cursor()
117 cur.execute("SELECT COUNT(*) FROM PackageBases " +
118 "LEFT JOIN PackageComaintainers " +
119 "ON PackageComaintainers.PackageBaseID = PackageBases.ID " +
120 "INNER JOIN Users ON Users.ID = PackageBases.MaintainerUID " +
121 "OR PackageBases.MaintainerUID IS NULL " +
122 "OR Users.ID = PackageComaintainers.UsersID " +
123 "WHERE Name = %s AND Username = %s", [pkgbase, user])
124 return cur.fetchone()[0] > 0
127 def die(msg):
128 sys.stderr.write("{:s}\n".format(msg))
129 exit(1)
132 def die_with_help(msg):
133 die(msg + "\nTry `{:s} help` for a list of commands.".format(ssh_cmdline))
136 user = os.environ.get('AUR_USER')
137 privileged = (os.environ.get('AUR_PRIVILEGED', '0') == '1')
138 ssh_cmd = os.environ.get('SSH_ORIGINAL_COMMAND')
139 ssh_client = os.environ.get('SSH_CLIENT')
141 if not ssh_cmd:
142 die_with_help("Interactive shell is disabled.")
143 cmdargv = shlex.split(ssh_cmd)
144 action = cmdargv[0]
145 remote_addr = ssh_client.split(' ')[0] if ssh_client else None
147 if enable_maintenance:
148 if remote_addr not in maintenance_exc:
149 die("The AUR is down due to maintenance. We will be back soon.")
151 if action == 'git-upload-pack' or action == 'git-receive-pack':
152 if len(cmdargv) < 2:
153 die_with_help("{:s}: missing path".format(action))
155 path = cmdargv[1].rstrip('/')
156 if not path.startswith('/'):
157 path = '/' + path
158 if not path.endswith('.git'):
159 path = path + '.git'
160 pkgbase = path[1:-4]
161 if not re.match(repo_regex, pkgbase):
162 die('{:s}: invalid repository name: {:s}'.format(action, pkgbase))
164 if not pkgbase_exists(pkgbase):
165 create_pkgbase(pkgbase, user)
167 if action == 'git-receive-pack':
168 if not privileged and not pkgbase_has_write_access(pkgbase, user):
169 die('{:s}: permission denied: {:s}'.format(action, user))
171 os.environ["AUR_USER"] = user
172 os.environ["AUR_PKGBASE"] = pkgbase
173 os.environ["GIT_NAMESPACE"] = pkgbase
174 cmd = action + " '" + repo_path + "'"
175 os.execl(git_shell_cmd, git_shell_cmd, '-c', cmd)
176 elif action == 'set-keywords':
177 if len(cmdargv) < 2:
178 die_with_help("{:s}: missing repository name".format(action))
179 pkgbase_set_keywords(cmdargv[1], cmdargv[2:])
180 elif action == 'list-repos':
181 if len(cmdargv) > 1:
182 die_with_help("{:s}: too many arguments".format(action))
183 list_repos(user)
184 elif action == 'setup-repo':
185 if len(cmdargv) < 2:
186 die_with_help("{:s}: missing repository name".format(action))
187 if len(cmdargv) > 2:
188 die_with_help("{:s}: too many arguments".format(action))
189 create_pkgbase(cmdargv[1], user)
190 elif action == 'restore':
191 if len(cmdargv) < 2:
192 die_with_help("{:s}: missing repository name".format(action))
193 if len(cmdargv) > 2:
194 die_with_help("{:s}: too many arguments".format(action))
196 pkgbase = cmdargv[1]
197 if not re.match(repo_regex, pkgbase):
198 die('{:s}: invalid repository name: {:s}'.format(action, pkgbase))
200 if pkgbase_exists(pkgbase):
201 die('{:s}: package base exists: {:s}'.format(action, pkgbase))
202 create_pkgbase(pkgbase, user)
204 os.environ["AUR_USER"] = user
205 os.environ["AUR_PKGBASE"] = pkgbase
206 os.execl(git_update_cmd, git_update_cmd, 'restore')
207 elif action == 'help':
208 die("Commands:\n" +
209 " help Show this help message and exit.\n" +
210 " list-repos List all your repositories.\n" +
211 " restore <name> Restore a deleted package base.\n" +
212 " set-keywords <name> [...] Change package base keywords.\n" +
213 " setup-repo <name> Create an empty repository.\n" +
214 " git-receive-pack Internal command used with Git.\n" +
215 " git-upload-pack Internal command used with Git.")
216 else:
217 die_with_help("invalid command: {:s}".format(action))