Repository navigation
Expand file tree
/
Copy pathimp-proxy
More file actions
executable file
·1719 lines (1479 loc) · 63.8 KB
/
Copy pathimp-proxy
File metadata and controls
executable file
·1719 lines (1479 loc) · 63.8 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""imp — lend a remote machine your Claude Max subscription without ever
giving it the credential.
The token stays on this machine. A local proxy holds it and injects it into
every request; the far side gets only a per-session capability string and a
URL that resolves to this machine's loopback. Stop the proxy and the far
side's access dies instantly — no watchdog, no teardown, nothing to scrub,
and no need to kill running `claude` processes to revoke.
Any host you can ssh to is the default, and ssh's own -R carries the
traffic:
this machine far side (ssh HOST)
------------------------------------------------------------
injecting proxy <------ ssh -R ------> claude
(real token) ANTHROPIC_BASE_URL=
http://127.0.0.1:22376
A Fly Sprite (-s) is supported too. `sprite proxy --ssh` supports neither -R
nor -A, so for a sprite we reimplement remote forwarding in userspace over
the one ssh stdio channel, which is 8-bit clean in both directions
(verified): a relay on the sprite, framed and multiplexed back to us.
Runs on macOS and Linux. Requires only python3 and ssh here. The far side
needs nothing for --no-settings, python3 to have its settings.json written,
and for a sprite, python3 there and the `sprite` CLI here.
"""
import argparse
import base64
import http.client
import json
import os
import platform
import posixpath
import queue
import re
import shlex
import signal
import socket
import socketserver
import struct
import subprocess
import sys
import tempfile
import threading
import time
import urllib.parse
UPSTREAM = "https://api.anthropic.com"
# Claude Code drops oauth-2025-04-20 from its beta list when it has no local
# OAuth credentials -- which is exactly the state the far side is in. Without it
# the Max entitlement is not honoured, so we put it back on the way out.
REQUIRED_BETAS = ("claude-code-20250219", "oauth-2025-04-20")
# A hostile far side gets to choose the request path, so the proxy is otherwise an
# open relay to your account for the length of the session. Only inference
# endpoints are worth reaching through here; everything else is refused before
# the credential is ever attached. Extend with --allow, escape with
# --allow-any-path.
DEFAULT_ALLOWED = (
"/v1/messages",
"/v1/messages/count_tokens",
"/v1/models",
"/v1/models/*",
)
# The port the far side listens on. Nothing but `claude` and imp ever dials
# it -- it is on that machine's loopback, reached only through our own ssh --
# so the only property that matters is that nothing else there wants it.
# 8080, which this was, is the first port a dev server takes, and a taken
# port is a relay that cannot bind or a -R that silently has no proxy behind
# it. This one is a random pick from the range above the dev-server crowd and
# below Linux's ephemeral ports, so neither a service nor an outbound socket
# is likely to have it first. Nothing depends on the number; -p changes it.
DEFAULT_REMOTE_PORT = 22376
HDR = struct.Struct("!IBI")
T_OPEN, T_DATA, T_CLOSE, T_PING = 1, 2, 3, 4
PING_EVERY = 10.0
LINK_TIMEOUT = 60.0
RELAY_IDLE_TIMEOUT = 30.0
# A hostile far side gets to declare how much we should allocate for it. None of
# these are tuning knobs -- they exist so that a number chosen on the far end
# cannot exhaust memory, threads or descriptors on this machine.
MAX_BODY = 64 * 1024 * 1024 # generous next to a large image request
MAX_FRAME = 1024 * 1024 # the relay never sends more than 64KB
MAX_STREAMS = 256 # concurrent proxied connections
# Per-stream write buffer before a consumer is written off as stuck. A claude
# that pauses to render a long response is slow, not stuck -- be generous.
MAX_STREAM_BUFFER = 8 * 1024 * 1024
SETTINGS_TIMEOUT = 30.0 # ssh round trip for settings.json
STATE_TTL = 24 * 3600.0 # how long a session is worth reattaching to
# A long inference call streams for minutes, so the socket timeout has to be
# generous; it exists to stop a wedged connection pinning a thread forever.
UPSTREAM_TIMEOUT = 600.0
# How long a kept connection may sit idle before we open a new one instead.
# A connection the far end closed while we were not looking costs a retry to
# discover; below the usual edge idle timeout, we mostly do not find out.
UPSTREAM_MAX_IDLE = 55.0
def log(*a):
sys.stderr.write("[imp] " + " ".join(str(x) for x in a) + "\n")
sys.stderr.flush()
def die(*lines):
for line in lines:
log(line)
raise SystemExit(2)
# --------------------------------------------------------------------------
# credential lookup (macOS + Linux)
# --------------------------------------------------------------------------
def _run(cmd):
try:
return subprocess.run(cmd, capture_output=True, text=True)
except FileNotFoundError:
return None
def _extract_token(blob):
"""A credential blob is either a bare token or JSON holding accessToken."""
blob = blob.strip()
if not blob:
return None
try:
data = json.loads(blob)
except ValueError:
return blob
found = []
def walk(o):
if isinstance(o, dict):
for k, v in o.items():
if k == "accessToken" and isinstance(v, str):
found.append(v)
else:
walk(v)
elif isinstance(o, list):
for v in o:
walk(v)
walk(data)
return found[0] if found else None
def load_credential():
"""Return (token, human-readable source). Never logged, never written out.
Preferred: the dedicated setup-token minted by imp-auth, which is
long-lived and inference-only. Falls back to this machine's live Claude
login, which works but carries a short-lived access token -- see --help.
"""
darwin = platform.system() == "Darwin"
user = os.environ.get("USER") or os.environ.get("LOGNAME") or ""
if darwin:
candidates = [
(["security", "find-generic-password", "-s", "imp-oauth",
"-a", user, "-w"], "macOS keychain (imp-oauth, setup-token)"),
(["security", "find-generic-password", "-s", "Claude Code-credentials",
"-a", user, "-w"], "macOS keychain (live Claude login)"),
]
for cmd, source in candidates:
r = _run(cmd)
if r is not None and r.returncode == 0:
tok = _extract_token(r.stdout)
if tok:
return tok, source
else:
path = os.path.expanduser("~/.claude/.credentials.json")
if os.path.exists(path):
with open(path) as f:
tok = _extract_token(f.read())
if tok:
return tok, path
for service in ("imp-oauth", "Claude Code-credentials"):
r = _run(["secret-tool", "lookup", "service", service])
if r is not None and r.returncode == 0:
tok = _extract_token(r.stdout)
if tok:
return tok, "secret-tool (%s)" % service
env = os.environ.get("CLAUDE_CODE_OAUTH_TOKEN")
if env:
return env.strip(), "CLAUDE_CODE_OAUTH_TOKEN in this environment"
raise SystemExit(
"no Claude credential found.\n"
" Mint a dedicated one: claude setup-token (then store it as\n"
" 'imp-oauth' in your keychain), or just log in with `claude`."
)
# --------------------------------------------------------------------------
# the injecting proxy — the only thing that ever sees the real token
# --------------------------------------------------------------------------
# Decoding is repeated until it stops changing, so %252e%252e cannot hide a
# traversal behind one round of unescaping. A handful of rounds is far more
# than any real target needs; the cap only stops a pathological input.
MAX_DECODE_ROUNDS = 5
def _fully_decoded(path):
"""Percent-decode until stable, or None if it will not settle."""
for _ in range(MAX_DECODE_ROUNDS):
nxt = urllib.parse.unquote(path)
if nxt == path:
return path
path = nxt
return None
def normalize_path(raw):
"""Canonical path to authorize *and* to forward, or None if unsafe.
The value returned here is what actually goes upstream. Authorizing one
spelling and forwarding another is how an allowlist gets walked past:
%2e%2e survives posixpath.normpath untouched, so a check on the raw target
sees nothing wrong while whatever decodes it downstream sees `..`.
So: decode first, refuse anything whose decoded form is not already
normal, and re-encode that decoded form for the wire. What is checked and
what is sent are then the same string by construction.
"""
if not raw.startswith("/"):
return None
path = raw.split("#", 1)[0].split("?", 1)[0]
decoded = _fully_decoded(path)
if decoded is None or not decoded.startswith("/"):
return None
# Backslashes and control bytes have no place in a target and are a
# standard way to confuse whatever parses it next.
if "\\" in decoded or any(c < " " or c == "\x7f" for c in decoded):
return None
norm = posixpath.normpath(decoded)
if norm != decoded and norm != decoded.rstrip("/"):
return None
return urllib.parse.quote(norm, safe="/")
def _glob_to_re(pat):
"""`*` matches within one path segment, `**` spans segments.
fnmatch's `*` crosses `/`, which makes /v1/models/* mean "anything under
/v1/models" rather than "one model id" -- a much wider grant than it
looks. Path globs should behave the way shell globs do.
"""
out, i = [], 0
while i < len(pat):
c = pat[i]
if c == "*":
if pat.startswith("**", i):
out.append(".*")
i += 2
else:
out.append("[^/]*")
i += 1
elif c == "?":
out.append("[^/]")
i += 1
else:
out.append(re.escape(c))
i += 1
return re.compile("".join(out) + r"\Z")
_GLOB_CACHE = {}
def path_allowed(path, patterns):
if not patterns: # --allow-any-path
return True
for pat in patterns:
rx = _GLOB_CACHE.get(pat)
if rx is None:
rx = _GLOB_CACHE[pat] = _glob_to_re(pat)
if rx.match(path):
return True
return False
HOP = {"host", "accept-encoding", "content-length", "connection", "keep-alive",
"proxy-authenticate", "proxy-authorization", "te", "trailers",
"transfer-encoding", "upgrade"}
class Upstream(object):
"""One kept-alive connection to the API per handler thread.
http.client rather than urllib.request, for two reasons.
Redirects: urllib's default handler copies Authorization into the
redirected request without checking the origin, so a 3xx would hand the
real token to whatever host the Location names. It took a handler
subclass to say no. http.client does not follow redirects at all -- the
3xx comes back like any other response and goes to the far side verbatim,
for it to decide about without our credential.
Reuse: urllib opens a fresh connection per request, so every message paid
a full TLS handshake to api.anthropic.com. That handshake was most of
what imp added on top of talking to the API directly. Threads here are
one per client connection, so a thread-local connection lines the two
lifetimes up: one `claude` conversation, one connection at each end, and
nothing shared between threads to lock.
"""
def __init__(self):
self._local = threading.local()
def _target(self):
u = urllib.parse.urlsplit(UPSTREAM)
return u.scheme, u.hostname, u.port
def _open(self):
scheme, host, port = self._target()
cls = (http.client.HTTPSConnection if scheme == "https"
else http.client.HTTPConnection)
conn = cls(host, port, timeout=UPSTREAM_TIMEOUT)
self._local.conn = conn
self._local.key = (scheme, host, port)
self._local.used = time.time()
return conn
def discard(self):
"""Throw the kept connection away. Safe to call at any point."""
conn = getattr(self._local, "conn", None)
self._local.conn = None
if conn is not None:
try:
conn.close()
except Exception:
pass
def send(self, method, target, body, headers):
"""Return (response, error); exactly one of the two is None.
A kept connection the far end has already closed is indistinguishable
from a live one until we write to it. That failure costs one retry on
a fresh connection -- safe to repeat regardless of method, because a
request that died on the way out was never seen upstream.
"""
conn = getattr(self._local, "conn", None)
if conn is not None and (
getattr(self._local, "key", None) != self._target()
or time.time() - getattr(self._local, "used", 0.0) > UPSTREAM_MAX_IDLE):
self.discard()
conn = None
reused = conn is not None
if conn is None:
conn = self._open()
while True:
try:
conn.request(method, target, body=body, headers=headers)
resp = conn.getresponse()
self._local.used = time.time()
return resp, None
except Exception as e:
self.discard()
if not reused:
return None, e
reused = False
conn = self._open()
def release(self, resp, complete):
"""Hand the connection back, or throw it away.
Only a response read to the end leaves the connection at a message
boundary. A client that hung up mid-stream, or an upstream that said
`Connection: close`, leaves bytes we would otherwise read as the head
of the next response.
"""
if resp is None:
return
will_close = getattr(resp, "will_close", True)
try:
resp.close()
except Exception:
pass
if will_close or not complete:
self.discard()
UPSTREAM_CONN = Upstream()
def _drop(conn):
"""Close a proxied socket that another thread may be blocked reading.
Same reason as the relay's drop(): close() alone does not reliably wake a
thread parked in recv(), nor guarantee the peer sees EOF.
"""
try:
conn.shutdown(socket.SHUT_RDWR)
except OSError:
pass
try:
conn.close()
except OSError:
pass
class Credential(object):
"""Holds the live token. Re-read on a 401 so a long session survives the
access token rolling underneath it -- Claude Code on this machine refreshes
the keychain entry, we just notice."""
def __init__(self):
self.token, self.source = load_credential()
self.lock = threading.Lock()
def refresh(self):
with self.lock:
old = self.token
try:
self.token, self.source = load_credential()
except (Exception, SystemExit) as e:
# SystemExit is "no credential found", but the keychain and
# ~/.claude/.credentials.json can also be unreadable or
# half-written under us. Losing a refresh is survivable;
# letting it out of this method is not -- it would surface in
# the handler thread as a dropped connection, where passing
# the upstream 401 back was the answer.
log("credential refresh failed: %s" % e)
return False
return self.token != old
def make_proxy_handler(cred, capability, verbose, allowed):
import http.server
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, fmt, *args):
pass
def finish(self):
# A thread here is one client connection, so when it ends the
# kept upstream connection has no next request to serve. Closed
# on the way out rather than left to the garbage collector --
# which is where it otherwise surfaced, as a ResourceWarning and
# a socket held open for as long as the collector felt like it.
try:
http.server.BaseHTTPRequestHandler.finish(self)
finally:
UPSTREAM_CONN.discard()
# The target is the far side's to choose, so it reaches our terminal
# only as printable ASCII, clipped: a request line can carry 64 KB of
# escape sequences, and a rejection is exactly when it is unvetted.
def _safe_target(self):
raw = getattr(self, "path", None) or "-"
clean = "".join(c if " " <= c <= "~" else "?" for c in raw)
return clean if len(clean) <= 120 else clean[:120] + "..."
def _reject(self, code, why):
# Logged, not returned: the body says what was wrong, and the
# far side already knows what it asked for.
log("rejected: %s (%s %s)" % (why, self.command, self._safe_target()))
body = json.dumps({"type": "error", "error": {
"type": "authentication_error", "message": why}}).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
# We may be refusing before reading the request body, so this
# connection cannot be reused -- whatever is still in flight would
# be parsed as the next request line.
self.send_header("Connection", "close")
self.close_connection = True
self.end_headers()
self.wfile.write(body)
def _proxy(self):
path = normalize_path(self.path)
if path is None:
self._reject(400, "malformed request path")
return
if not path_allowed(path, allowed):
self._reject(403, "path is not on the allowlist")
return
# Forward the target we authorized, not the one we were handed.
target = path
q = self.path.split("#", 1)[0].split("?", 1)
if len(q) == 2:
target += "?" + q[1]
# Folded to lower case on the way in. Header names are
# case-insensitive but a dict is not, and every lookup below is a
# dict lookup: with the far side's spelling kept, an
# `Anthropic-Beta` slid past the `anthropic-beta` merge and its
# betas were dropped on the floor. One spelling from here on, so
# a repeated header collapses here rather than somewhere further
# down -- and so popping two keys strips every credential header
# the far side sent, whatever case it chose for them.
fwd = {}
for k, v in self.headers.items():
k = k.lower()
if k not in HOP:
fwd[k] = v
fwd["accept-encoding"] = "identity"
presented = ""
for k in ("authorization", "x-api-key"):
v = fwd.pop(k, None)
if v is not None:
presented = presented or v
presented = presented[7:] if presented.lower().startswith("bearer ") else presented
# Before the body is read, not after: Content-Length is chosen by
# the far side, and reading it first hands an unauthenticated caller
# a blocking allocation of whatever size it likes.
if not presented or presented.strip() != capability:
self._reject(403, "bad or missing session capability")
return
n = self.headers.get("Content-Length")
try:
length = int(n) if n else 0
except ValueError:
self._reject(400, "malformed Content-Length")
return
if length < 0:
# rfile.read(-1) would read to EOF -- unbounded, by way of a
# value that merely looks like a number.
self._reject(400, "negative Content-Length")
return
if length > MAX_BODY:
self._reject(413, "request body of %d bytes exceeds the %d byte limit"
% (length, MAX_BODY))
return
body = self.rfile.read(length) if length else b""
fwd["authorization"] = "Bearer " + cred.token
betas = [b.strip() for b in (fwd.get("anthropic-beta") or "").split(",")]
betas = [b for b in betas if b]
for b in REQUIRED_BETAS:
if b not in betas:
betas.insert(0, b)
if betas:
fwd["anthropic-beta"] = ",".join(betas)
if verbose:
log("%s %s (%d bytes up)" % (self.command, target, len(body)))
resp, err = UPSTREAM_CONN.send(self.command, target, body, fwd)
if err is None and resp.status == 401 and cred.refresh():
log("upstream 401 -- reloaded credential, retrying")
# Read the 401 body out before reusing the connection; an
# unread body is the next response as far as the socket knows.
try:
resp.read()
drained = True
except Exception:
drained = False
UPSTREAM_CONN.release(resp, drained)
fwd["authorization"] = "Bearer " + cred.token
resp, err = UPSTREAM_CONN.send(self.command, target, body, fwd)
if err is not None:
log("upstream error: %r" % (err,))
self._reject(502, "upstream error")
return
self.send_response(resp.status)
for k, v in resp.getheaders():
if k.lower() not in HOP:
self.send_header(k, v)
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
# Streamed verbatim so SSE arrives token-by-token, not buffered.
# `complete` is set the moment upstream is drained, before the
# terminating chunk goes out: a client that hangs up on that last
# write has cost us nothing, and the connection is still good.
complete = False
try:
while True:
chunk = resp.read(4096)
if not chunk:
break
self.wfile.write(b"%x\r\n" % len(chunk) + chunk + b"\r\n")
self.wfile.flush()
complete = True
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
finally:
UPSTREAM_CONN.release(resp, complete)
do_GET = do_POST = do_PUT = do_DELETE = _proxy
return Handler
class ProxyServer(socketserver.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
def handle_error(self, request, client_address):
"""A client hanging up mid-request is routine -- `claude` does it on
every Ctrl-C. socketserver's default would dump a traceback for it.
Anything genuinely unexpected gets one line, never headers or bodies."""
exc = sys.exc_info()[1]
if isinstance(exc, (ConnectionResetError, BrokenPipeError,
ConnectionAbortedError, socket.timeout)):
return
log("connection error: %r" % (exc,))
# --------------------------------------------------------------------------
# the relay that runs on the sprite (shipped as base64 in argv, never a file)
# --------------------------------------------------------------------------
RELAY_SRC = r'''
import os, queue, socket, struct, sys, threading, time
PORT = int(sys.argv[1])
IDLE = float(sys.argv[2])
# Per-stream buffer before a consumer is written off as stuck. Generous: a
# claude that pauses to render a long response is slow, not stuck.
MAX_BUF = 8 * 1024 * 1024
HDR = struct.Struct("!IBI")
T_OPEN, T_DATA, T_CLOSE, T_PING = 1, 2, 3, 4
out = sys.stdout.buffer
inp = sys.stdin.buffer
streams = {}
slock = threading.Lock()
last = [time.time()]
# A bounded queue drained by one writer thread. Producers are per-stream pump
# threads, so blocking one when the channel backs up is correct backpressure
# for that stream alone -- unlike holding a lock across the write, which
# stalled every stream at once.
outq = queue.Queue(maxsize=256)
def drop(conn):
# shutdown() before close(): another thread is blocked in recv() on this
# socket, and close() alone neither reliably wakes it nor guarantees the
# peer sees EOF. shutdown() does both.
try:
conn.shutdown(socket.SHUT_RDWR)
except OSError:
pass
try:
conn.close()
except OSError:
pass
def send(sid, t, payload=b""):
outq.put(HDR.pack(sid, t, len(payload)) + payload)
def chan_writer():
while True:
buf = outq.get()
try:
out.write(buf)
out.flush()
except (OSError, ValueError):
os._exit(0)
class Stream(object):
"""A socket plus its own writer thread.
The frame reader must never block: one consumer that stops draining would
otherwise stall every other stream, and -- because the reader is also what
refreshes the idle timestamp -- trip the watchdog into killing the whole
session 30s later.
"""
def __init__(self, sid, conn):
self.sid = sid
self.conn = conn
self.q = queue.Queue()
self.buffered = 0
self.lock = threading.Lock()
self.closed = False
threading.Thread(target=self.writer, daemon=True).start()
def feed(self, data):
"""Hand off without blocking. True if accepted."""
with self.lock:
if self.closed:
return False
if self.buffered + len(data) > MAX_BUF:
return False # genuinely stuck; caller drops the stream
self.buffered += len(data)
self.q.put(data)
return True
def writer(self):
while True:
data = self.q.get()
if data is None:
break
try:
self.conn.sendall(data)
except OSError:
break
with self.lock:
self.buffered -= len(data)
self.close()
def close(self):
with self.lock:
if self.closed:
return
self.closed = True
self.q.put(None)
drop(self.conn)
def pump(sid, st):
try:
while True:
b = st.conn.recv(65536)
if not b:
break
send(sid, T_DATA, b) # may block on outq; that is this stream's
except OSError: # backpressure, not everyone else's
pass
finally:
with slock:
streams.pop(sid, None)
send(sid, T_CLOSE)
st.close()
def acceptor():
srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
srv.bind(("127.0.0.1", PORT))
except OSError as e:
sys.stderr.write("relay: cannot bind 127.0.0.1:%d: %s\n" % (PORT, e))
sys.stderr.flush()
os._exit(1)
srv.listen(64)
sys.stderr.write("relay listening on 127.0.0.1:%d\n" % PORT)
sys.stderr.flush()
# Tell the other end the link is genuinely up. Nothing is "ready" before
# this frame arrives.
send(0, T_PING)
n = 0
while True:
conn, _ = srv.accept()
n += 1
st = Stream(n, conn)
with slock:
streams[n] = st
send(n, T_OPEN)
threading.Thread(target=pump, args=(n, st), daemon=True).start()
def watchdog():
# The sprite keeps remote commands alive after the link drops, so nothing
# tears us down for free. Silence means the operator is gone: exit, which
# closes every proxied connection and frees the port.
while True:
time.sleep(2)
if time.time() - last[0] > IDLE:
sys.stderr.write("relay: %.0fs silent, exiting\n" % IDLE)
os._exit(0)
def readexact(n):
buf = b""
while len(buf) < n:
c = inp.read(n - len(buf))
if not c:
return None
buf += c
return buf
threading.Thread(target=chan_writer, daemon=True).start()
threading.Thread(target=acceptor, daemon=True).start()
threading.Thread(target=watchdog, daemon=True).start()
while True:
h = readexact(HDR.size)
if h is None:
break
sid, t, ln = HDR.unpack(h)
payload = readexact(ln) if ln else b""
if payload is None:
break
last[0] = time.time()
if t == T_PING:
continue
with slock:
st = streams.get(sid)
if st is None:
continue
if t == T_DATA:
if not st.feed(payload):
# Buffered past MAX_BUF: this consumer is not coming back. Drop
# it alone rather than letting it hold up the demultiplexer.
with slock:
streams.pop(sid, None)
send(sid, T_CLOSE)
st.close()
elif t == T_CLOSE:
with slock:
streams.pop(sid, None)
st.close()
os._exit(0)
'''
# --------------------------------------------------------------------------
# this side of the mux
# --------------------------------------------------------------------------
class Stream(object):
"""A proxied socket plus its own writer thread.
The frame reader must never block on one of these. With a single `claude`
on the sprite a blocking write is just backpressure, but with several,
one that stops draining would stall every other stream -- and since the
reader is also what refreshes the relay's idle timestamp, the watchdog
would then tear the whole session down 30s later.
"""
def __init__(self, conn):
self.conn = conn
self.q = queue.Queue()
self.buffered = 0
self.lock = threading.Lock()
self.closed = False
threading.Thread(target=self._writer, daemon=True).start()
def feed(self, data):
"""Hand off without blocking. False means the peer is not draining."""
with self.lock:
if self.closed:
return False
if self.buffered + len(data) > MAX_STREAM_BUFFER:
return False
self.buffered += len(data)
self.q.put(data)
return True
def _writer(self):
while True:
data = self.q.get()
if data is None:
break
try:
self.conn.sendall(data)
except OSError:
break
with self.lock:
self.buffered -= len(data)
self.close()
def close(self):
with self.lock:
if self.closed:
return
self.closed = True
self.q.put(None)
_drop(self.conn)
class Mux(object):
"""Demultiplexes the sprite's framed stdout into local proxy connections."""
def __init__(self, proc, proxy_port, verbose):
self.proc = proc
self.proxy_port = proxy_port
self.verbose = verbose
self.socks = {}
self.lock = threading.Lock()
self.alive = True
self.ready = threading.Event()
# Bounded, drained by one writer thread. Producers are per-stream
# pump threads, so blocking one when the pipe backs up is that
# stream's backpressure -- not a lock every other stream waits on.
self.outq = queue.Queue(maxsize=256)
threading.Thread(target=self._chan_writer, daemon=True).start()
def send(self, sid, t, payload=b""):
try:
self.outq.put(HDR.pack(sid, t, len(payload)) + payload)
except Exception:
self.alive = False
def _chan_writer(self):
while True:
buf = self.outq.get()
if buf is None:
break
try:
self.proc.stdin.write(buf)
self.proc.stdin.flush()
except (OSError, ValueError):
self.alive = False
break
def _pump(self, sid, st):
try:
while True:
b = st.conn.recv(65536)
if not b:
break
self.send(sid, T_DATA, b)
except OSError:
pass
finally:
with self.lock:
self.socks.pop(sid, None)
self.send(sid, T_CLOSE)
st.close()
def _open(self, sid):
with self.lock:
if len(self.socks) >= MAX_STREAMS:
log("refusing stream %d: %d already open" % (sid, MAX_STREAMS))
self.send(sid, T_CLOSE)
return
stale = self.socks.pop(sid, None)
if stale is not None:
# A repeated SID used to overwrite the entry and leak the socket.
stale.close()
try:
conn = socket.create_connection(("127.0.0.1", self.proxy_port), timeout=10)
conn.settimeout(None)
except OSError as e:
log("could not reach local proxy: %r" % (e,))
self.send(sid, T_CLOSE)
return
st = Stream(conn)
with self.lock:
self.socks[sid] = st
threading.Thread(target=self._pump, args=(sid, st), daemon=True).start()
def pinger(self):
while self.alive:
time.sleep(PING_EVERY)
self.send(0, T_PING)
def _readexact(self, n):
# Chunks into a list rather than repeatedly concatenating: `buf += c`
# over a large frame is quadratic.
parts, got = [], 0
while got < n:
c = self.proc.stdout.read(n - got)
if not c:
return None
parts.append(c)
got += len(c)
return b"".join(parts)
def run(self):
threading.Thread(target=self.pinger, daemon=True).start()
while True:
h = self._readexact(HDR.size)
if h is None:
break
sid, t, ln = HDR.unpack(h)
if ln > MAX_FRAME:
# The length is a uint32 chosen by the far end. Allocating on
# its say-so is how the sprite OOMs this machine; the relay
# never legitimately sends more than 64KB.
log("frame of %d bytes exceeds the %d byte limit -- "
"closing the link" % (ln, MAX_FRAME))
break
payload = self._readexact(ln) if ln else b""
if payload is None:
break
self.ready.set()
if t == T_OPEN:
self._open(sid)
elif t == T_DATA:
with self.lock:
st = self.socks.get(sid)
if st is not None and not st.feed(payload):
log("stream %d buffered past %d bytes without draining -- "
"dropping it" % (sid, MAX_STREAM_BUFFER))
with self.lock:
self.socks.pop(sid, None)
self.send(sid, T_CLOSE)
st.close()