Spaces:
Running
Running
File size: 10,905 Bytes
78e7c43 | 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 | """Independent stdlib character parser and complete report reference; no JS core imports."""
from pathlib import Path
import json,hashlib,datetime,email.utils,re
VERSION='0.1.0';IDENTITY='work:http-range-desk:v1';P=Path(__file__).resolve().parent;CONTRACT_SHA=hashlib.sha256((P/'CONTRACT.md').read_bytes()).hexdigest();DAYS=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
def canonical(q):
def convert(v):
if isinstance(v,dict):return {k:convert(x) for k,x in v.items()}
if isinstance(v,list):return [convert(x) for x in v]
if isinstance(v,float) and v.is_integer():return int(v)
return v
s=json.dumps(convert(q),ensure_ascii=False,separators=(',',':'));return ''.join('\\u%04x'%ord(c) if 0xd800<=ord(c)<=0xdfff else c for c in s)
def tag(text):
if not isinstance(text,str):return None
weak=text[:2]=='W/';a=text[2:] if weak else text
if len(a)<2 or a[0]!='"' or a[-1]!='"':return None
for c in a[1:-1]:
n=ord(c)
if n<33 or n==34 or n==127 or n>255:return None
return weak,a[1:-1]
def date(text):
if not isinstance(text,str) or len(text)!=29:return None
try:
d=email.utils.parsedate_to_datetime(text)
if d.year<1601 or d.tzinfo is None:return None
expected=f'{DAYS[d.weekday()]}, {d.day:02d} {MONTHS[d.month-1]} {d.year:04d} {d.hour:02d}:{d.minute:02d}:{d.second:02d} GMT'
if expected!=text:return None
return int(d.timestamp())
except (TypeError,ValueError,OverflowError):return None
def interval(a,b):return {'first':str(a),'last':str(b-1) if b>a else None,'exclusive_end':str(b),'length':str(b-a)}
def unevaluated():return {'status':'not-evaluated','unit':None,'complete':False,'raw_token_count':None,'empty_member_count':None,'nonempty_member_count':None,'semantic_satisfiable_members':None,'members':[]}
def parse_range(raw,n):
a={'status':'malformed','unit':None,'complete':True,'raw_token_count':0,'empty_member_count':0,'nonempty_member_count':0,'semantic_satisfiable_members':None,'members':[]};text=raw.strip(' \t');parts=text.split('=')
if len(parts)!=2 or not parts[0]:return a
unit=parts[0];token=set("!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
if any(c not in token for c in unit):return a
a['unit']=unit
if unit.lower()!='bytes':a.update(status='unsupported-unit',complete=False,raw_token_count=None,empty_member_count=None,nonempty_member_count=None);return a
tokens=parts[1].split(',');a['raw_token_count']=len(tokens);malformed=False;outside=False;sat=0
for ordinal,rawmember in enumerate(tokens):
value=rawmember.strip(' \t');row={'ordinal':ordinal,'raw':rawmember,'trimmed':value,'kind':None,'status':None,'first':None,'last':None,'suffix':None,'satisfiable':None,'interval':None};a['members'].append(row)
if not value:
a['empty_member_count']+=1;row['status']='ignored-empty'
if a['empty_member_count']>64:row['status']='outside-profile-empty-cap';outside=True;break
continue
a['nonempty_member_count']+=1
if a['nonempty_member_count']>64:row['status']='outside-profile-range-cap';outside=True;break
# Walk characters instead of the candidate's range regular expression.
if value.count('-')!=1:row['status']='malformed';malformed=True;continue
left,right=value.split('-')
if not(left or right) or any(c not in '0123456789' for c in left+right):row['status']='malformed';malformed=True;continue
if max(len(left),len(right))>256:row['status']='outside-profile-digit-cap';outside=True;break
row['status']='valid'
if not left:
count=int(right);row['kind']='suffix';row['suffix']=str(count);row['satisfiable']=count>0
if count>0:
# Small-domain byte membership is an independent representation of bounds.
members=[i for i in range(n) if i>=n-count] if n<=1000 else None
first=members[0] if members else max(0,n-count);end=members[-1]+1 if members else n;row['interval']=interval(first,end)
else:
first=int(left);last=int(right) if right else None;row['kind']='closed' if last is not None else 'open';row['first']=str(first);row['last']=str(last) if last is not None else None
if last is not None and last<first:row['status']='malformed-reversed';malformed=True;continue
row['satisfiable']=first<n
if row['satisfiable']:
members=[i for i in range(n) if i>=first and(last is None or i<=last)] if n<=1000 else None
end=members[-1]+1 if members else n if last is None else min(n,last+1);row['interval']=interval(first,end)
sat+=bool(row['satisfiable'])
a['status']='outside-profile' if outside else 'malformed' if malformed or not a['nonempty_member_count'] else 'valid';a['complete']=not outside;a['semantic_satisfiable_members']=sat if a['status']=='valid' else None;return a
def ifrange(raw,r):
if raw is None:return {'kind':'not-present','status':'allow','matches':True,'provided':None,'comparison':None,'date_strength_is_caller_asserted':True}
v=raw.strip(' \t');t=tag(v)
if t is not None:
current=tag(r['etag']);matches=current is not None and not t[0] and not current[0] and t[1]==current[1]
return {'kind':'entity-tag','status':'match' if matches else 'nonmatch','matches':matches,'provided':raw,'comparison':'strong-exact','request_is_weak':t[0],'current_is_weak':current[0] if current else None,'date_strength_is_caller_asserted':True}
d=date(v)
if d is not None:
matches=r['date_is_strong'] and r['last_modified'] is not None and d==date(r['last_modified']);return {'kind':'http-date','status':'match' if matches else 'nonmatch','matches':matches,'provided':raw,'comparison':'exact-seconds-not-earlier-or-equal','date_strength_is_caller_asserted':True,'date_asserted_strong':r['date_is_strong'],'current_last_modified':r['last_modified']}
old=any(v.startswith(d+',') for d in ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']) or len(v.split(' '))>=2 and v.split(' ')[0] in ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] and v.split(' ')[1] in MONTHS or bool(re.fullmatch(r'[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:60 GMT',v))
return {'kind':'outside-profile' if old else 'invalid-validator','status':'outside-profile' if old else 'nonmatch','matches':None if old else False,'provided':raw,'comparison':None,'date_strength_is_caller_asserted':True}
def reference(q,payload=None):
raw=canonical(q);q=json.loads(raw);n=int(q['resource']['length']);a=unevaluated();c={'kind':'not-evaluated','status':'not-evaluated','matches':None,'provided':q['if_range'],'comparison':None,'date_strength_is_caller_asserted':True};status=None;reason='';trace=[];selected=[]
def full(why):return (200,why,[{'member_ordinal':None,**interval(0,n)}] if q['method']=='GET' and n else [])
if q['base_status']!=200:status=q['base_status'];reason='base-status';trace.append('Caller-supplied other-precondition outcome takes precedence; Range and If-Range not evaluated.')
elif q['method']!='GET':status=200;reason='method';trace.append('Range semantics not defined for HEAD; no selected representation body.')
elif q['range'] is None:status,reason,selected=full('no-range');trace.append('No Range header; If-Range ignored.')
else:
a=parse_range(q['range'],n);trace.append('Range analysis: '+a['status']+'.')
if a['status']=='outside-profile':reason='outside-profile'
elif a['status']=='unsupported-unit':status,reason,selected=full('unsupported-unit')
elif a['status']=='malformed':status,reason,selected=full('malformed-range-policy')
else:
c=ifrange(q['if_range'],q['resource']);trace.append('If-Range: '+c['status']+'.')
if c['status']=='outside-profile':reason='outside-profile'
elif not c['matches']:status,reason,selected=full('if-range-failed')
elif n==0:status,reason,selected=full('empty-representation-policy');trace.append('RFC permits ignoring ranges on an empty representation; a nonzero suffix remains semantically satisfiable in analysis.')
elif not a['semantic_satisfiable_members']:status=416;reason='all-unsatisfiable'
else:status=206;reason='partial-ranges';selected=[{'member_ordinal':r['ordinal'],**r['interval']} for r in a['members'] if r['status']=='valid' and r['satisfiable']]
# Sorted sweep over events, not the candidate's interval-merging loop.
events={}
for r in selected:
start=int(r['first']);end=int(r['exclusive_end']);events[start]=events.get(start,0)+1;events[end]=events.get(end,0)-1
union=[];active=0;begin=None
for endpoint,delta in sorted(events.items()):
before=active;active+=delta
if before==0 and active>0:begin=endpoint
if before>0 and active==0:union.append(interval(begin,endpoint))
total=sum(int(r['length']) for r in selected);unique=sum(int(r['length']) for r in union);parts=[{'part_ordinal':i,**r,'content_range':f"bytes {r['first']}-{r['last']}/{n}" if status==206 else None} for i,r in enumerate(selected)];actual=None
if payload is not None:
assert len(payload)==n and n<=1048576;slices=[]
for part in parts:
bs=payload[int(part['first']):int(part['exclusive_end'])];slices.append({'part_ordinal':part['part_ordinal'],'observed_byte_length':str(len(bs)),'sha256':hashlib.sha256(bs).hexdigest(),'preview_first32_hex':bs[:32].hex(),'preview_truncated':len(bs)>32})
actual={'whole_observed_byte_length':str(n),'whole_sha256':hashlib.sha256(payload).hexdigest(),'slices':slices,'local_only_no_upload':True}
return {'schema':'http-range-desk-report-v1','version':VERSION,'author':'Renchao Wu','work_identity':IDENTITY,'provenance':{'contract_sha256':CONTRACT_SHA,'request_snapshot_sha256':hashlib.sha256(raw.encode()).hexdigest(),'snapshot_digest_not_raw_JSON_bytes':True},'request':q,'scope':{'declared_bounded_profile_not_universal_server':True,'resource_metadata_is_caller_asserted':True,'other_preconditions_are_caller_supplied':True,'date_strength_is_caller_asserted':True,'representation_is_encoded_octets_not_characters':True,'no_network_request_made':True,'no_training':True,'payload_observed':payload is not None,'multipart_wire_body_not_constructed':True},'decision_trace':trace,'range_analysis':a,'if_range':c,'plan':{'status':status,'reason':reason,'range_response_policy':'optional-range-support-ignore-malformed-and-empty-keep-all-satisfiable-parts','kind':('single-range' if len(parts)==1 else 'multipart-plan') if status==206 else 'full-representation' if status==200 and q['method']=='GET' else 'outside-profile' if status is None else 'no-selected-representation-data','content_range':f'bytes */{n}' if status==416 else parts[0]['content_range'] if status==206 and len(parts)==1 else None,'planned_content_length':parts[0]['length'] if status==206 and len(parts)==1 else str(n) if status==200 and q['method']=='GET' else None,'wire_body_length_unknown':True,'selected_payload_bytes':str(total),'unique_payload_bytes':str(unique),'overlap_payload_bytes':str(total-unique),'selected_intervals':parts,'diagnostic_union_intervals':union,'request_order_and_duplicate_parts_preserved':True},'actual_payload':actual}
|