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