Coverage for plugin/web.py: 86.3%

233 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 02:31 +0000

1"""Nonblocking HTTP transport for the legacy and JSON-RPC endpoints.""" 

2import json 

3import select 

4import socket 

5import time 

6import jsonschema 

7from . import util 

8from .protocol import Deferred, completed, ApiError, Dispatcher 

9from .contract import SCHEMA 

10 

11 

12# Historical servers accepted any body size. Legacy media may be 64 MiB before 

13# base64 encoding, so the legacy endpoint admits one such file with its envelope. 

14LEGACY_MAX_REQUEST_BYTES = 134217728 

15# Bytes read per poll; the timer interval otherwise throttles large uploads. 

16MAX_READ_PER_ADVANCE = 16777216 

17# Connections without a pending request are closed this long after they open. 

18IDLE_TIMEOUT_SECONDS = 10 

19 

20 

21def is_rpc_path(path): 

22 return path.split(b'?', 1)[0].rstrip(b'/') == b'/api/v1' 

23 

24 

25class WebRequest: 

26 def __init__(self, method, headers, body, path=b'/', too_large=False): 

27 self.method, self.headers, self.body, self.path = method, headers, body, path 

28 self.too_large = too_large 

29 

30 

31class WebClient: 

32 def __init__(self, sock, handler): 

33 self.sock, self.handler = sock, handler 

34 self.readBuff = bytearray() 

35 self.writeBuff = b'' 

36 self.pending = False 

37 self.expected = None 

38 self.started = time.monotonic() 

39 

40 def advance(self, recvSize=65536): 

41 if self.sock is None: 41 ↛ 42line 41 didn't jump to line 42 because the condition on line 41 was never true

42 return False 

43 if not self.pending and time.monotonic() - self.started > IDLE_TIMEOUT_SECONDS: 

44 self.close() 

45 return False 

46 # Windows select() rejects empty socket lists while accepted work waits. 

47 if self.pending and not self.writeBuff: 

48 return True 

49 rlist, wlist = select.select([self.sock] if not self.pending and not self.writeBuff else [], [self.sock] if self.writeBuff else [], [], 0)[:2] 

50 if rlist: 

51 try: 

52 req = None 

53 received = 0 

54 while req is None and received < MAX_READ_PER_ADVANCE: 

55 try: 

56 msg = self.sock.recv(recvSize) 

57 except BlockingIOError: 

58 if not received: 58 ↛ 59line 58 didn't jump to line 59 because the condition on line 58 was never true

59 raise 

60 break 

61 if not msg: 61 ↛ 62line 61 didn't jump to line 62 because the condition on line 61 was never true

62 self.close() 

63 return False 

64 received += len(msg) 

65 self.started = time.monotonic() 

66 self.readBuff += msg 

67 # Parse once the announced body is complete, not for every chunk. 

68 if self.expected is None or len(self.readBuff) >= self.expected: 

69 req, length = self.parseRequest(bytes(self.readBuff)) 

70 if req is not None: 

71 self.readBuff = bytearray() 

72 self.expected = None 

73 self.pending = True 

74 try: 

75 reply = self.handler(req) 

76 except Exception as error: 

77 # Includes serialization failures of synchronous results. 

78 reply = completed(error=error) 

79 def finish(source): 

80 self.pending = False 

81 self.started = time.monotonic() 

82 if self.sock is not None: 82 ↛ exitline 82 didn't return from function 'finish' because the condition on line 82 was always true

83 self.writeBuff = source.value if not source.error else b'HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n' 

84 (reply if isinstance(reply, Deferred) else completed(reply)).then(finish) 

85 except BlockingIOError: 

86 pass 

87 except (ValueError, UnicodeError): 

88 self.writeBuff = b'HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n' 

89 except OSError: 

90 self.close() 

91 return False 

92 if wlist and self.writeBuff: 

93 try: 

94 length = self.sock.send(self.writeBuff) 

95 if length: 95 ↛ 97line 95 didn't jump to line 97 because the condition on line 95 was always true

96 self.started = time.monotonic() 

97 self.writeBuff = self.writeBuff[length:] 

98 if not self.writeBuff: 

99 self.close() 

100 return False 

101 except BlockingIOError: 

102 pass 

103 except OSError: 

104 self.close() 

105 return False 

106 return True 

107 

108 def close(self): 

109 if self.sock is not None: 

110 self.sock.close() 

111 self.sock = None 

112 self.readBuff, self.writeBuff = bytearray(), b'' 

113 

114 def parseRequest(self, data): 

115 parts = data.split(b'\r\n\r\n', 1) 

116 if len(parts[0]) > 65536: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true

117 raise ValueError('Headers too large') 

118 if len(parts) == 1: 

119 return None, 0 

120 lines = parts[0].split(b'\r\n') 

121 method, path, version = lines[0].split(b' ') 

122 if version not in (b'HTTP/1.0', b'HTTP/1.1'): 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true

123 raise ValueError('Unsupported HTTP version') 

124 headers = {} 

125 for line in lines[1:]: 

126 key, value = line.split(b':', 1) 

127 key = key.strip().lower() 

128 # Older servers kept the last value; ambiguous framing or identity still fails. 

129 if key in headers and key in (b'content-length', b'transfer-encoding', b'origin', b'authorization', b'host'): 

130 raise ValueError('Duplicate header') 

131 headers[key] = value.strip() 

132 if b'transfer-encoding' in headers: 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true

133 raise ValueError('Chunked requests unsupported') 

134 size = int(headers.get(b'content-length', b'0')) 

135 offset = len(parts[0]) + 4 

136 limit = SCHEMA['x-limits']['maxRequestBytes'] if is_rpc_path(path) else LEGACY_MAX_REQUEST_BYTES 

137 if size > limit: 

138 # Reply without reading the body, but with CORS headers for browsers. 

139 return WebRequest(method.upper(), headers, b'', path, too_large=True), offset 

140 if size < 0: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true

141 raise ValueError('Invalid body length') 

142 if len(data) < offset + size: 

143 self.expected = offset + size 

144 return None, 0 

145 return WebRequest(method.upper(), headers, data[offset:offset + size], path), offset + size 

146 

147 

148class WebServer: 

149 def __init__(self, handler, rpc_handler=None): 

150 self.handler, self.rpc_handler = handler, rpc_handler 

151 self.clients, self.sock = [], None 

152 

153 def advance(self): 

154 if self.sock is not None: 154 ↛ exitline 154 didn't return from function 'advance' because the condition on line 154 was always true

155 self.acceptClients() 

156 self.advanceClients() 

157 

158 def acceptClients(self): 

159 if not select.select([self.sock], [], [], 0)[0]: 

160 return 

161 sock = self.sock.accept()[0] 

162 sock.setblocking(False) 

163 self.clients.append(WebClient(sock, self.handlerWrapper)) 

164 

165 def advanceClients(self): 

166 self.clients = [client for client in self.clients if client.advance()] 

167 

168 def listen(self): 

169 self.close() 

170 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

171 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

172 self.sock.setblocking(False) 

173 self.sock.bind((util.setting('webBindAddress'), util.setting('webBindPort'))) 

174 self.sock.listen(util.setting('webBacklog')) 

175 

176 def handlerWrapper(self, req): 

177 allowed, origin = self.allowOrigin(req) 

178 def response(value, status='200 OK', empty=False): 

179 body = b'' if empty else json.dumps(value, allow_nan=False).encode('utf-8') 

180 headers = self.buildHeaders(origin, body) 

181 headers[0][0] = 'HTTP/1.1 ' + status 

182 if req.method == b'OPTIONS' and req.headers.get(b'access-control-request-private-network') == b'true': 

183 headers.append(['Access-Control-Allow-Private-Network', 'true']) 

184 return self.buildResponse(headers, body) 

185 if req.method == b'OPTIONS': 

186 # Preflight has no JSON body, so it cannot identify permission discovery. 

187 # Let browsers send the POST; origin admission below still protects actions. 

188 origin = req.headers.get(b'origin', b'').decode() or origin 

189 return response(None, empty=True) 

190 # Historical servers ignored the request target; only /api/v1 is reserved. 

191 rpc = is_rpc_path(req.path) 

192 if req.too_large: 

193 if rpc: 

194 return response(None, '413 Payload Too Large', empty=True) 

195 # Legacy clients commonly parse the body without checking the status. 

196 return response(format_exception_reply(util.setting('apiVersion'), ValueError( 

197 'request body exceeds {} bytes'.format(LEGACY_MAX_REQUEST_BYTES))), '413 Payload Too Large') 

198 if rpc and req.method != b'POST': 198 ↛ 199line 198 didn't jump to line 199 because the condition on line 198 was never true

199 return response(None, '405 Method Not Allowed', empty=True) 

200 try: 

201 def reject_constant(value): 

202 raise ValueError('Non-finite JSON number') 

203 params = json.loads(req.body.decode('utf-8'), parse_constant=reject_constant) 

204 if not rpc: 

205 from .legacy import legacy_request 

206 params = legacy_request(params) 

207 jsonschema.validate(params, request_schema) 

208 except (ValueError, UnicodeError, jsonschema.ValidationError, ApiError) as error: 

209 if not allowed: 209 ↛ 210line 209 didn't jump to line 210 because the condition on line 209 was never true

210 return response(None, '403 Forbidden', empty=True) 

211 if rpc: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true

212 return response(Dispatcher.reply(None, error=ApiError('parseError', 'Invalid JSON.'))) 

213 if not req.body: 213 ↛ 214line 213 didn't jump to line 214 because the condition on line 213 was never true

214 return response({'apiVersion': 'AnkiConnect v.{}'.format(util.setting('apiVersion'))}) 

215 return response(format_exception_reply(util.setting('apiVersion'), error)) 

216 permission = isinstance(params, dict) and params.get('method' if rpc else 'action') == ('access.requestPermission' if rpc else 'requestPermission') 

217 if not allowed and not permission: 

218 return response(None, '403 Forbidden', empty=True) 

219 if permission: 

220 origin = req.headers.get(b'origin', b'').decode() 

221 if rpc: 

222 key = util.setting('apiKey') 

223 if key and not permission and req.headers.get(b'authorization') != ('Bearer ' + key).encode(): 

224 return response(None, '401 Unauthorized', empty=True) 

225 if self.rpc_handler is None: 225 ↛ 226line 225 didn't jump to line 226 because the condition on line 225 was never true

226 return response(None, '404 Not Found', empty=True) 

227 pending = self.rpc_handler(params, {'origin': req.headers.get(b'origin', b'').decode(), 'allowed': allowed}) 

228 return pending.map(lambda value: response(value, '204 No Content' if value is None else '200 OK', 

229 empty=value is None)) 

230 if permission: 

231 params.setdefault('params', {}).update(allowed=allowed, origin=origin) 

232 value = self.handler(params) 

233 return value.map(response) if isinstance(value, Deferred) else response(value) 

234 

235 def allowOrigin(self, req): 

236 origins = list(util.setting('webCorsOriginList')) 

237 deprecated = util.setting('webCorsOrigin') 

238 if deprecated: 

239 origins.append(deprecated) 

240 origin = req.headers.get(b'origin', b'').decode() 

241 if '*' in origins: 

242 return True, '*' 

243 allowed = not origin or origin in origins 

244 if 'http://localhost' in origins and origin.startswith(('http://127.0.0.1:', 'https://127.0.0.1:', 'chrome-extension://', 'moz-extension://', 'safari-web-extension://')): 

245 allowed = True 

246 if 'http://localhost' in origins and origin in ('http://127.0.0.1', 'https://127.0.0.1'): 246 ↛ 247line 246 didn't jump to line 247 because the condition on line 246 was never true

247 allowed = True 

248 return allowed, origin if allowed and origin else 'http://localhost' 

249 

250 def buildHeaders(self, corsOrigin, body): 

251 return [['HTTP/1.1 200 OK', None], ['Content-Type', 'application/json'], 

252 ['Access-Control-Allow-Origin', corsOrigin], ['Vary', 'Origin'], 

253 ['Access-Control-Allow-Headers', 'Content-Type, Authorization, *'], 

254 ['Access-Control-Allow-Methods', 'POST, OPTIONS'], ['Connection', 'close'], 

255 ['Content-Length', str(len(body))]] 

256 

257 def buildResponse(self, headers, body): 

258 return ''.join(key + (': ' + value if value is not None else '') + '\r\n' for key, value in headers).encode() + b'\r\n' + body 

259 

260 def close(self): 

261 if self.sock is not None: 

262 self.sock.close() 

263 self.sock = None 

264 for client in self.clients: 264 ↛ 265line 264 didn't jump to line 265 because the loop on line 264 never started

265 client.close() 

266 self.clients = [] 

267 

268 

269def format_success_reply(api_version, result): 

270 if api_version <= 4: 

271 return result 

272 return {"result": result, "error": None} 

273 

274 

275def format_exception_reply(_api_version, exception): 

276 if isinstance(exception, ApiError) and exception.kind == 'collectionUnavailable': 

277 return {"result": None, "error": 'collection is not available'} 

278 return {"result": None, "error": str(exception)} 

279 

280 

281request_schema = { 

282 "type": "object", 

283 "properties": { 

284 "action": {"type": "string", "minLength": 1}, 

285 "version": {"type": "integer"}, 

286 "params": {"type": "object"}, 

287 }, 

288 "required": ["action"], 

289}