|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +import re |
| 3 | + |
| 4 | +import requests |
| 5 | +from flask import Flask, Response, redirect, request |
| 6 | +from requests.exceptions import ( |
| 7 | + ChunkedEncodingError, |
| 8 | + ContentDecodingError, ConnectionError, StreamConsumedError) |
| 9 | +from requests.utils import ( |
| 10 | + stream_decode_response_unicode, iter_slices, CaseInsensitiveDict) |
| 11 | +from urllib3.exceptions import ( |
| 12 | + DecodeError, ReadTimeoutError, ProtocolError) |
| 13 | +from urllib.parse import quote |
| 14 | + |
| 15 | +# config |
| 16 | +# 分支文件使用jsDelivr镜像的开关,0为关闭,默认关闭 |
| 17 | +jsdelivr = 0 |
| 18 | +size_limit = 1024 * 1024 * 1024 * 999 # 允许的文件大小,默认999GB,相当于无限制了 https://github.com/hunshcn/gh-proxy/issues/8 |
| 19 | + |
| 20 | +""" |
| 21 | + 先生效白名单再匹配黑名单,pass_list匹配到的会直接302到jsdelivr而忽略设置 |
| 22 | + 生效顺序 白->黑->pass,可以前往https://github.com/hunshcn/gh-proxy/issues/41 查看示例 |
| 23 | + 每个规则一行,可以封禁某个用户的所有仓库,也可以封禁某个用户的特定仓库,下方用黑名单示例,白名单同理 |
| 24 | + user1 # 封禁user1的所有仓库 |
| 25 | + user1/repo1 # 封禁user1的repo1 |
| 26 | + */repo1 # 封禁所有叫做repo1的仓库 |
| 27 | +""" |
| 28 | +white_list = ''' |
| 29 | +''' |
| 30 | +black_list = ''' |
| 31 | +''' |
| 32 | +pass_list = ''' |
| 33 | +''' |
| 34 | + |
| 35 | +HOST = '127.0.0.1' # 监听地址,建议监听本地然后由web服务器反代 |
| 36 | +PORT = 80 # 监听端口 |
| 37 | +ASSET_URL = 'https://hunshcn.github.io/gh-proxy' # 主页 |
| 38 | + |
| 39 | +white_list = [tuple([x.replace(' ', '') for x in i.split('/')]) for i in white_list.split('\n') if i] |
| 40 | +black_list = [tuple([x.replace(' ', '') for x in i.split('/')]) for i in black_list.split('\n') if i] |
| 41 | +pass_list = [tuple([x.replace(' ', '') for x in i.split('/')]) for i in pass_list.split('\n') if i] |
| 42 | +app = Flask(__name__) |
| 43 | +CHUNK_SIZE = 1024 * 10 |
| 44 | +index_html = requests.get(ASSET_URL, timeout=10).text |
| 45 | +icon_r = requests.get(ASSET_URL + '/favicon.ico', timeout=10).content |
| 46 | +exp1 = re.compile(r'^(?:https?://)?github\.com/(?P<author>.+?)/(?P<repo>.+?)/(?:releases|archive)/.*$') |
| 47 | +exp2 = re.compile(r'^(?:https?://)?github\.com/(?P<author>.+?)/(?P<repo>.+?)/(?:blob|raw)/.*$') |
| 48 | +exp3 = re.compile(r'^(?:https?://)?github\.com/(?P<author>.+?)/(?P<repo>.+?)/(?:info|git-).*$') |
| 49 | +exp4 = re.compile(r'^(?:https?://)?raw\.(?:githubusercontent|github)\.com/(?P<author>.+?)/(?P<repo>.+?)/.+?/.+$') |
| 50 | +exp5 = re.compile(r'^(?:https?://)?gist\.(?:githubusercontent|github)\.com/(?P<author>.+?)/.+?/.+$') |
| 51 | + |
| 52 | +requests.sessions.default_headers = lambda: CaseInsensitiveDict() |
| 53 | + |
| 54 | + |
| 55 | +@app.route('/') |
| 56 | +def index(): |
| 57 | + if 'q' in request.args: |
| 58 | + return redirect('/' + request.args.get('q')) |
| 59 | + return index_html |
| 60 | + |
| 61 | + |
| 62 | +@app.route('/favicon.ico') |
| 63 | +def icon(): |
| 64 | + return Response(icon_r, content_type='image/vnd.microsoft.icon') |
| 65 | + |
| 66 | + |
| 67 | +def iter_content(self, chunk_size=1, decode_unicode=False): |
| 68 | + """rewrite requests function, set decode_content with False""" |
| 69 | + |
| 70 | + def generate(): |
| 71 | + # Special case for urllib3. |
| 72 | + if hasattr(self.raw, 'stream'): |
| 73 | + try: |
| 74 | + for chunk in self.raw.stream(chunk_size, decode_content=False): |
| 75 | + yield chunk |
| 76 | + except ProtocolError as e: |
| 77 | + raise ChunkedEncodingError(e) |
| 78 | + except DecodeError as e: |
| 79 | + raise ContentDecodingError(e) |
| 80 | + except ReadTimeoutError as e: |
| 81 | + raise ConnectionError(e) |
| 82 | + else: |
| 83 | + # Standard file-like object. |
| 84 | + while True: |
| 85 | + chunk = self.raw.read(chunk_size) |
| 86 | + if not chunk: |
| 87 | + break |
| 88 | + yield chunk |
| 89 | + |
| 90 | + self._content_consumed = True |
| 91 | + |
| 92 | + if self._content_consumed and isinstance(self._content, bool): |
| 93 | + raise StreamConsumedError() |
| 94 | + elif chunk_size is not None and not isinstance(chunk_size, int): |
| 95 | + raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size)) |
| 96 | + # simulate reading small chunks of the content |
| 97 | + reused_chunks = iter_slices(self._content, chunk_size) |
| 98 | + |
| 99 | + stream_chunks = generate() |
| 100 | + |
| 101 | + chunks = reused_chunks if self._content_consumed else stream_chunks |
| 102 | + |
| 103 | + if decode_unicode: |
| 104 | + chunks = stream_decode_response_unicode(chunks, self) |
| 105 | + |
| 106 | + return chunks |
| 107 | + |
| 108 | + |
| 109 | +def check_url(u): |
| 110 | + for exp in (exp1, exp2, exp3, exp4, exp5): |
| 111 | + m = exp.match(u) |
| 112 | + if m: |
| 113 | + return m |
| 114 | + return False |
| 115 | + |
| 116 | + |
| 117 | +@app.route('/<path:u>', methods=['GET', 'POST']) |
| 118 | +def handler(u): |
| 119 | + u = u if u.startswith('http') else 'https://' + u |
| 120 | + if u.rfind('://', 3, 9) == -1: |
| 121 | + u = u.replace('s:/', 's://', 1) # uwsgi会将//传递为/ |
| 122 | + pass_by = False |
| 123 | + m = check_url(u) |
| 124 | + if m: |
| 125 | + m = tuple(m.groups()) |
| 126 | + if white_list: |
| 127 | + for i in white_list: |
| 128 | + if m[:len(i)] == i or i[0] == '*' and len(m) == 2 and m[1] == i[1]: |
| 129 | + break |
| 130 | + else: |
| 131 | + return Response('Forbidden by white list.', status=403) |
| 132 | + for i in black_list: |
| 133 | + if m[:len(i)] == i or i[0] == '*' and len(m) == 2 and m[1] == i[1]: |
| 134 | + return Response('Forbidden by black list.', status=403) |
| 135 | + for i in pass_list: |
| 136 | + if m[:len(i)] == i or i[0] == '*' and len(m) == 2 and m[1] == i[1]: |
| 137 | + pass_by = True |
| 138 | + break |
| 139 | + else: |
| 140 | + return Response('Invalid input.', status=403) |
| 141 | + |
| 142 | + if (jsdelivr or pass_by) and exp2.match(u): |
| 143 | + u = u.replace('/blob/', '@', 1).replace('github.com', 'cdn.jsdelivr.net/gh', 1) |
| 144 | + return redirect(u) |
| 145 | + elif (jsdelivr or pass_by) and exp4.match(u): |
| 146 | + u = re.sub(r'(\.com/.*?/.+?)/(.+?/)', r'\1@\2', u, 1) |
| 147 | + _u = u.replace('raw.githubusercontent.com', 'cdn.jsdelivr.net/gh', 1) |
| 148 | + u = u.replace('raw.github.com', 'cdn.jsdelivr.net/gh', 1) if _u == u else _u |
| 149 | + return redirect(u) |
| 150 | + else: |
| 151 | + if exp2.match(u): |
| 152 | + u = u.replace('/blob/', '/raw/', 1) |
| 153 | + if pass_by: |
| 154 | + url = u + request.url.replace(request.base_url, '', 1) |
| 155 | + if url.startswith('https:/') and not url.startswith('https://'): |
| 156 | + url = 'https://' + url[7:] |
| 157 | + return redirect(url) |
| 158 | + u = quote(u, safe='/:') |
| 159 | + return proxy(u) |
| 160 | + |
| 161 | + |
| 162 | +def proxy(u, allow_redirects=False): |
| 163 | + headers = {} |
| 164 | + r_headers = dict(request.headers) |
| 165 | + if 'Host' in r_headers: |
| 166 | + r_headers.pop('Host') |
| 167 | + try: |
| 168 | + url = u + request.url.replace(request.base_url, '', 1) |
| 169 | + if url.startswith('https:/') and not url.startswith('https://'): |
| 170 | + url = 'https://' + url[7:] |
| 171 | + r = requests.request(method=request.method, url=url, data=request.data, headers=r_headers, stream=True, allow_redirects=allow_redirects) |
| 172 | + headers = dict(r.headers) |
| 173 | + |
| 174 | + if 'Content-length' in r.headers and int(r.headers['Content-length']) > size_limit: |
| 175 | + return redirect(u + request.url.replace(request.base_url, '', 1)) |
| 176 | + |
| 177 | + def generate(): |
| 178 | + for chunk in iter_content(r, chunk_size=CHUNK_SIZE): |
| 179 | + yield chunk |
| 180 | + |
| 181 | + if 'Location' in r.headers: |
| 182 | + _location = r.headers.get('Location') |
| 183 | + if check_url(_location): |
| 184 | + headers['Location'] = '/' + _location |
| 185 | + else: |
| 186 | + return proxy(_location, True) |
| 187 | + |
| 188 | + return Response(generate(), headers=headers, status=r.status_code) |
| 189 | + except Exception as e: |
| 190 | + headers['content-type'] = 'text/html; charset=UTF-8' |
| 191 | + return Response('server error ' + str(e), status=500, headers=headers) |
| 192 | + |
| 193 | +app.debug = True |
| 194 | +if __name__ == '__main__': |
| 195 | + app.run(host=HOST, port=PORT) |
0 commit comments