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 • 6.44 kiB
Python script, ASCII text executable
        
            
1
import uuid
2
from models import *
3
from app import app, db, bcrypt
4
from misc_utils import *
5
from common import git_command
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, ref = push_info[4:].split() # discard first 4 characters, used for line length which we don't need
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
if ref.startswith("refs/heads/"): # if the push is to a branch
95
ref = ref.rpartition("/")[2] # get the branch name only
96
repo_data = db.session.get(Repo, f"/{username}/{repository}")
97
if ref == repo_data.site_branch:
98
# Update the site
99
from celery_tasks import copy_site
100
copy_site.delay(repo_data.route)
101
102
return flask.Response(text, content_type="application/x-git-receive-pack-result")
103
104
105
@app.route("/<username>/<repository>/info/refs", methods=["GET", "POST"])
106
@app.route("/git/<username>/<repository>/info/refs", methods=["GET", "POST"])
107
@auth.login_required(optional=True)
108
def git_info_refs(username, repository):
109
server_repo_location = os.path.join(config.REPOS_PATH, username, repository, ".git")
110
111
repo = git.Repo(server_repo_location)
112
repo_data = Repo.query.filter_by(route=f"/{username}/{repository}").first()
113
if not repo_data.default_branch:
114
if repo.heads:
115
repo_data.default_branch = repo.heads[0].name
116
repo.git.checkout("-f", repo_data.default_branch)
117
118
if auth.current_user() is None and (
119
not get_visibility(username, repository) or flask.request.args.get(
120
"service") == "git-receive-pack"):
121
return auth_required
122
try:
123
if not (get_visibility(username, repository) or get_permission_level(flask.g.user,
124
username,
125
repository) is not None):
126
flask.abort(403)
127
except AttributeError:
128
return auth_required
129
130
service = flask.request.args.get("service")
131
132
if service.startswith("git"):
133
service = service[4:]
134
else:
135
flask.abort(403)
136
137
if service == "receive-pack":
138
try:
139
if not get_permission_level(flask.g.user, username, repository):
140
flask.abort(403)
141
except AttributeError:
142
return auth_required
143
144
service_line = f"# service=git-{service}\n"
145
service_line = (f"{len(service_line) + 4:04x}" + service_line).encode()
146
147
if service == "upload-pack":
148
text = service_line + b"0000" + git_command(server_repo_location, None, "upload-pack",
149
"--stateless-rpc",
150
"--advertise-refs",
151
"--http-backend-info-refs", ".")
152
elif service == "receive-pack":
153
refs = git_command(server_repo_location, None, "receive-pack",
154
"--http-backend-info-refs", ".")
155
text = service_line + b"0000" + refs
156
else:
157
flask.abort(403)
158
159
response = flask.Response(text, content_type=f"application/x-git-{service}-advertisement")
160
response.headers["Cache-Control"] = "no-cache"
161
162
return response
163