By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 git_http.py

View raw Download
text/x-script.python • 5.99 kiB
Python script, ASCII text executable
        
            
1
import uuid
2
3
from models import *
4
from app import app, db, bcrypt
5
from misc_utils import *
6
import os
7
import shutil
8
import config
9
import flask
10
import git
11
import subprocess
12
from flask_httpauth import HTTPBasicAuth
13
import zlib
14
import re
15
import datetime
16
17
auth = HTTPBasicAuth(realm=config.AUTH_REALM)
18
19
auth_required = flask.Response("Unauthorized Access", 401,
20
{"WWW-Authenticate": 'Basic realm="Login Required"'})
21
22
23
@auth.verify_password
24
def verify_password(username, password):
25
user = User.query.filter_by(username=username).first()
26
27
if user and bcrypt.check_password_hash(user.password_hashed, password):
28
flask.g.user = username
29
return True
30
31
return False
32
33
34
@app.route("/<username>/<repository>/git-upload-pack", methods=["POST"])
35
@app.route("/git/<username>/<repository>/git-upload-pack", methods=["POST"])
36
@auth.login_required(optional=True)
37
def git_upload_pack(username, repository):
38
if auth.current_user() is None and not get_visibility(username, repository):
39
return auth_required
40
if not (get_visibility(username, repository) or get_permission_level(flask.g.user, username,
41
repository) is not None):
42
flask.abort(403)
43
44
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
45
text = git_command(server_repo_location, flask.request.data, "upload-pack",
46
"--stateless-rpc", ".")
47
48
return flask.Response(text, content_type="application/x-git-upload-pack-result")
49
50
51
@app.route("/<username>/<repository>/git-receive-pack", methods=["POST"])
52
@app.route("/git/<username>/<repository>/git-receive-pack", methods=["POST"])
53
@auth.login_required
54
def git_receive_pack(username, repository):
55
if not get_permission_level(flask.g.user, username, repository):
56
flask.abort(403)
57
58
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
59
text = git_command(server_repo_location, flask.request.data, "receive-pack",
60
"--stateless-rpc", ".")
61
62
if flask.request.data == b"0000":
63
return flask.Response("", content_type="application/x-git-receive-pack-result")
64
65
push_info = flask.request.data.split(b"\x00")[0].decode()
66
if not push_info:
67
return flask.Response(text, content_type="application/x-git-receive-pack-result")
68
69
old_sha, new_sha, _ = push_info[4:].split() # discard first 4 characters, used for line length
70
71
if old_sha == "0" * 40:
72
commits_list = subprocess.check_output(["git", "rev-list", new_sha],
73
cwd=server_repo_location).decode().strip().split("\n")
74
else:
75
commits_list = subprocess.check_output(["git", "rev-list", f"{old_sha}..{new_sha}"],
76
cwd=server_repo_location).decode().strip().split("\n")
77
78
for sha in reversed(commits_list):
79
info = git_command(server_repo_location, None, "show", "-s",
80
"--format='%H%n%at%n%cn <%ce>%n%B'", sha).decode()
81
82
sha, time, identity, body = info.split("\n", 3)
83
login = flask.g.user
84
85
if not Commit.query.filter_by(identifier=f"/{username}/{repository}/{sha}").first():
86
user = User.query.filter_by(username=login).first()
87
repo = Repo.query.filter_by(route=f"/{username}/{repository}").first()
88
89
commit = Commit(sha, user, repo, time, body, identity)
90
91
db.session.add(commit)
92
db.session.commit()
93
94
return flask.Response(text, content_type="application/x-git-receive-pack-result")
95
96
97
@app.route("/<username>/<repository>/info/refs", methods=["GET", "POST"])
98
@app.route("/git/<username>/<repository>/info/refs", methods=["GET", "POST"])
99
@auth.login_required(optional=True)
100
def git_info_refs(username, repository):
101
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
102
103
repo = git.Repo(server_repo_location)
104
repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first()
105
if not repo_data.default_branch:
106
if repo.heads:
107
repo_data.default_branch = repo.heads[0].name
108
repo.git.checkout("-f", repo_data.default_branch)
109
110
if auth.current_user() is None and (
111
not get_visibility(username, repository) or flask.request.args.get(
112
"service") == "git-receive-pack"):
113
return auth_required
114
try:
115
if not (get_visibility(username, repository) or get_permission_level(flask.g.user,
116
username,
117
repository) is not None):
118
flask.abort(403)
119
except AttributeError:
120
return auth_required
121
122
service = flask.request.args.get("service")
123
124
if service.startswith("git"):
125
service = service[4:]
126
else:
127
flask.abort(403)
128
129
if service == "receive-pack":
130
try:
131
if not get_permission_level(flask.g.user, username, repository):
132
flask.abort(403)
133
except AttributeError:
134
return auth_required
135
136
service_line = f"# service=git-{service}\n"
137
service_line = (f"{len(service_line) + 4:04x}" + service_line).encode()
138
139
if service == "upload-pack":
140
text = service_line + b"0000" + git_command(server_repo_location, None, "upload-pack",
141
"--stateless-rpc",
142
"--advertise-refs",
143
"--http-backend-info-refs", ".")
144
elif service == "receive-pack":
145
refs = git_command(server_repo_location, None, "receive-pack",
146
"--http-backend-info-refs", ".")
147
text = service_line + b"0000" + refs
148
else:
149
flask.abort(403)
150
151
response = flask.Response(text, content_type=f"application/x-git-{service}-advertisement")
152
response.headers["Cache-Control"] = "no-cache"
153
154
return response
155