Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
333 lines (262 loc) · 10.1 KB
/
Copy pathserver.py
File metadata and controls
333 lines (262 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from accounts import AccountStore
from auth import TokenStore
from datetime import datetime, timezone
from xml.etree import ElementTree as ET
from threading import Lock
from urllib.parse import urlparse
import psutil, os
from logger import print, writelog, clearlogs
CLIENT_LOGIN_PATH = "/accounts/ClientLogin"
from config import MAX_REQUEST_SIZE, ALLOW_LOGS_CLEAR, IP, PORT
ATOM_NS = "http://www.w3.org/2005/Atom"
ET.register_namespace("", ATOM_NS)
if ALLOW_LOGS_CLEAR:
clearlogs()
def atom_tag(name):
return f"{{{ATOM_NS}}}{name}"
class BlogStore:
def __init__(self):
self.lock = Lock()
self.blogs = {
"demo": {
"id": "tag:fakeg.local,2026:blog/demo",
"title": "FakeG Demo Blog",
"author": "FakeG Demo",
"entries": [
{
"id": "tag:fakeg.local,2026:post/1",
"title": "Hello from FakeG",
"content": "This post is served by the local FakeG server.",
"updated": datetime.now(timezone.utc),
},
{
"id": "tag:fakeg.local,2026:post/2",
"title": "A second post",
"content": "Atom feeds, now with actual entries.",
"updated": datetime.now(timezone.utc),
},
],
}
}
def get_blogs(self):
with self.lock:
return [
{
"id": blog["id"],
"title": blog["title"],
"author": blog["author"],
}
for blog in self.blogs.values()
]
def build_blogs_feed(store):
feed = ET.Element(atom_tag("feed"))
ET.SubElement(feed, atom_tag("id")).text = (
"tag:fakeg.local,2026:blogs"
)
ET.SubElement(feed, atom_tag("title"), {"type": "text"}).text = (
"FakeG Blogs"
)
ET.SubElement(feed, atom_tag("updated")).text = (
datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
)
for blog in store.get_blogs():
entry = ET.SubElement(feed, atom_tag("entry"))
ET.SubElement(entry, atom_tag("id")).text = blog["id"]
ET.SubElement(
entry, atom_tag("title"), {"type": "text"}
).text = blog["title"]
ET.SubElement(entry, atom_tag("updated")).text = (
datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
)
author = ET.SubElement(entry, atom_tag("author"))
ET.SubElement(author, atom_tag("name")).text = blog["author"]
return ET.tostring(
feed,
encoding="utf-8",
xml_declaration=True,
)
class FakeGHTTPServer(ThreadingHTTPServer):
print("Initialized HTTP server")
daemon_threads = True
allow_reuse_address = True
def __init__(self, address, handler_class, accounts, tokens):
super().__init__(address, handler_class)
self.accounts = accounts
self.tokens = tokens
self.blog_store = BlogStore()
class FakeGHandler(BaseHTTPRequestHandler):
def handle_register(self):
import json
try:
length_header = self.headers.get("Content-Length")
if length_header is None:
self.send_text(411, "Error=LengthRequired\n")
return
length = int(length_header)
if length <= 0 or length > MAX_REQUEST_SIZE:
self.send_text(400, "Error=InvalidRequestSize\n")
return
body = self.rfile.read(length)
data = json.loads(body.decode("utf-8"))
if not isinstance(data, dict):
self.send_text(400, "Error=InvalidRequest\n")
return
email = data.get("email", "")
password = data.get("password", "")
if not isinstance(email, str) or not isinstance(password, str):
self.send_text(400, "Error=InvalidCredentials\n")
return
email = email.strip().lower()
if not email or not password:
self.send_text(400, "Error=MissingRequiredField\n")
return
# AccountStore should expose a thread-safe registration
# method for atomic duplicate checking and account creation.
if not self.server.accounts.register_account(email, password):
self.send_text(409, "Error=AccountAlreadyExists\n")
return
response = json.dumps({
"success": True,
"email": email,
})
self.send_text(201, response)
except (json.JSONDecodeError, UnicodeDecodeError):
self.send_text(400, "Error=InvalidRequest\n")
except ValueError:
self.send_text(400, "Error=InvalidRequest\n")
print("Initialized Winst FakeG handler")
server_version = "FakeG/0.1"
sys_version = ""
def log_message(self, format_string, *args):
pass
def send_text(self, status, body):
print(f"Sent {status}")
encoded = body.encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(encoded)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(encoded)
def do_GET(self):
auth = self.headers.get("Authorization", "")
token = None
if auth.startswith("GoogleLogin auth="):
token = auth.removeprefix("GoogleLogin auth=")
print(f"Got GET {self.path}")
if not token or not self.server.tokens.validate(token):
self.send_text(401, "Error=NotAuthenticated\n")
elif self.path == "/feeds/default/blogs":
body = build_blogs_feed(self.server.blog_store)
self.send_response(200)
self.send_header(
"Content-Type",
"application/atom+xml; charset=utf-8",
)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
print(f"Sent feed:\n--------\n{body.decode()}\n--------")
self.wfile.write(body)
elif self.path == "/accounts/ClientLogin":
self.send_text(405, "Method not allowed")
else:
self.send_text(404, "Not Found\n")
def do_POST(self):
if self.path == CLIENT_LOGIN_PATH:
content_type = self.headers.get("Content-Type", "")
media_type = content_type.split(";", 1)[0].strip().lower()
if media_type != "application/x-www-form-urlencoded":
self.send_text(
415,
"Error=UnsupportedMediaType\n",
)
return
try:
length_header = self.headers.get("Content-Length")
if length_header is None:
self.send_text(411, "Error=LengthRequired\n")
return
length = int(length_header)
if length < 0:
self.send_text(400, "Error=InvalidContentLength\n")
return
if length > MAX_REQUEST_SIZE:
self.send_text(413, "Error=RequestTooLarge\n")
return
body = self.rfile.read(length).decode("utf-8")
fields = parse_qs(body, keep_blank_values=True)
except (ValueError, UnicodeDecodeError):
self.send_text(400, "Error=InvalidRequest\n")
return
def field(name):
values = fields.get(name, [])
# Reject duplicate values instead of silently choosing one.
if len(values) != 1:
r = None
value = values[0]
r = value if value else None
return r
email = field("Email")
password = field("Passwd")
service = field("service")
source = field("source")
# ClientLogin's historical request fields are Email, Passwd,
# service, and source. This particular error label is a FakeG
# policy; exact legacy clients may expect different error details.
if not all((email, password, service, source)):
self.send_text(
400,
"Error=MissingRequiredField\n",
)
return
if not self.server.accounts.authenticate(email, password):
self.send_text(403, "Error=BadAuthentication\n")
return
token = self.server.tokens.issue(email)
# Minimal success response for this first compatibility slice.
# Historical deployments could return additional fields such as
# SID and LSID; those are not implemented in this prototype.
self.send_text(200, f"Auth={token}\n")
elif self.path == "/accounts/Register":
self.handle_register()
return
else:
self.send_text(404, "Not Found\n")
def make_server(
host=IP,
port=PORT,
accounts=None,
tokens=None,
):
if accounts is None:
# AccountStore.for_local_development()
accounts = AccountStore()
if tokens is None:
tokens = TokenStore()
return FakeGHTTPServer(
(host, port),
FakeGHandler,
accounts,
tokens,
)
def main():
server = make_server()
print(
"FakeG ClientLogin listening on "
f"http://{server.server_address[0]}:{server.server_address[1]}"
)
print("Press Ctrl+C to stop.")
try:
server.serve_forever()
except KeyboardInterrupt:
print("Stopping FakeG.")
finally:
server.tokens.clear()
server.server_close()
accounts.write()
writelog()
if __name__ == "__main__":
main()