def do_PUT(self): alog("PUT " + self.path) self.set_ipaddr() path = self.path if self.has_handler(path): self.exec_handler(path, "PUT") else: self.send_error(404)
def do_GET(self, serv): qs = get_qs(serv.path) if "accessToken" not in qs or ("path" not in qs and "id" not in qs): serv.send_error(400) return tok = qs["accessToken"][0] userid = do_auth(tok) if userid == None: serv.send_error(401) return if "path" in qs: fileid = resolve_path(qs["path"][0]) else: fileid = publicid_to_fileid(qs["id"][0])[1] if fileid == None: serv.send_error(404) return alog("fetching file %s" % fileid); f = fetch_file(fileid) if f == None: serv.send_error(400) return if is_folder(f): serv.send_error(401) return if f["userid"] != userid: serv.send_error(401) return try: file = open(f["diskpath"], "rb") except OSError: serv.send_error(404) return body = file.read() file.close() serv.gen_headers("GET", len(body), "application/octet-stream") serv.send_header("Content-Disposition", "attachment; filename=\"%s\"" % f["name"]) #Content-Disposition: attachment; filename=FILENAME serv.wfile.write(body)
def do_POST(self): self.set_ipaddr() path = self.path alog("POST " + self.path) if path == "/webgl_helper.webpy": self._handle_mesh_post() elif path == "/logger": self._handle_logger_post() elif self.has_handler(path): self.exec_handler(path, "POST") else: self.send_error(404)
def do_GET(self, serv): qs = get_qs(serv.path) if "refreshToken" not in qs: serv.send_error(400) return token = qs["refreshToken"][0] cur, con = mysql_connect() cur.execute("SELECT * FROM authtokens WHERE tokenid=" + estr(token)) ret = cur.fetchone() if ret == None: serv.send_error(401) return exprtime1 = ensure_datetime(ret["expiration"]) if exprtime1 < datetime.datetime.now(): alog("Expired token %s" % (token)) serv.send_error(408) return userid = ret["userid"] tok = gen_token("A", userid) exprtime = datetime.datetime.now() + datetime.timedelta(hours=2) alog("Generated session token %s for user %s" % (tok, str(userid))) cols = ["tokenid", "userid", "type", "permissions", "expiration"] values = [tok, userid, toktypes["A"], default_permission, exprtime] types = [sq.token, sq.int, sq.int, sq.int, sq.datetime] try: qstr = sql_insertinto("authtokens", cols, values, types) except SQLParamError: do_param_error("cols: " + str(cols) + ", values:" + str(values)) serv.send_error(401) return cur.execute(qstr) con.commit() body = json.dumps({"access_token": str(tok)}) body = bstr(body) serv.gen_headers("GET", len(body), json_mimetype) serv.wfile.write(body)
def do_GET(self, serv): qs = get_qs(serv.path) if "accessToken" not in qs or ("path" not in qs and "id" not in qs): serv.send_error(400) return tok = qs["accessToken"][0] userid = do_auth(tok) if userid == None: serv.send_error(401) return if "path" in qs: path = qs["path"][0] else: path = publicid_to_fileid(qs["id"][0]) if path == None: serv.send_error(404) return alog("fetching file %s" % path); f = File(path, userid) if f == None: serv.send_error(400) return if is_folder(f): serv.send_error(401) return print("diskpath:", f.diskpath) try: file = open(f.diskpath, "rb") except OSError: serv.send_error(404) return body = file.read() file.close() serv.gen_headers("GET", len(body), "application/octet-stream") serv.send_header("Content-Disposition", "attachment; filename=\"%s\"" % f.name) #Content-Disposition: attachment; filename=FILENAME serv.wfile.write(body)
def do_GET(self, serv): global OAUTH_SCOPES qs = get_qs(serv.path) qs2 = {} for k in qs: if type(qs[k]) in [list, tuple] and len(qs[k]) == 1: qs2[k] = qs[k][0] else: qs2[k] = qs[k] qs = qs2 if "response_type" not in qs or "client_id" not in qs: alog("Invaild oauth request 1") serv.send_error(400) return if qs["response_type"] != "code": alog("Invaild oauth request 2") serv.send_error(400) return if "redirect_uri" in qs: self.redirect_uri = qs["redirect_uri"] scope = "" if "scope" in qs: scope = qs["scope"] state = None if "state" in qs: state = qs["state"] restype = qs["response_type"] clientid = qs["client_id"] if clientid not in self.valid_clients: alog("Invaild client id in oauth request") serv.send_error(401) return body = "<html><body>login</body></html>" body = bstr(body) serv.gen_headers("GET", len(body), "text/html") serv.wfile.write(body)
def do_sql_error(t, d, extra=None): elog("Database security failure") alog("Database security failure") raise RuntimeError("Invalid data for database query: type " + str(t) + ", data: " + estr(d))
def do_param_error(str): alog("possible sql injection: \"" + str + "\"") elog("possible sql injection: \"" + str + "\"")
def do_GET(self, serv): qs = get_qs(serv.path) if not ("user" in qs and "password" in qs): serv.send_error(400) return user = qs["user"][0] password = qs["password"][0] #HACK: wsgi is turning +'s into spaces? how odd password = password.replace(" ", "+") if not valid_pass(password): alog("invalid pass format %s" % password) serv.send_error(401) return cur, con = mysql_connect() try: qstr = sql_selectall("users", ["username"], [user], [sq.user]) except SQLParamError: do_param_error(user) serv.send_error(401) return cur.execute(qstr) ret = cur.fetchone() if ret == None: alog("invalid user %s" % user) serv.send_error(401) return alog("Fetching refresh token for user %s. . ." % user) passwd = ret["password"] userid = ret["userid"] if passwd != password: alog("Invalid password for %s, got: '%s', pass: '******'" % (user, password, ret["password"])) serv.send_error(401) return tok = gen_token("R", userid) exprtime = datetime.datetime.now() + datetime.timedelta(days=12) alog("Refresh token for %s: %s" % (user, tok)) cols = ["tokenid", "userid", "type", "permissions", "expiration"] values = [tok, userid, toktypes["R"], default_permission, exprtime] types = [sq.token, sq.int, sq.int, sq.int, sq.datetime] try: qstr = sql_insertinto("authtokens", cols, values, types) except SQLParamError: do_param_error("cols: " + str(cols) + ", values:" + str(values)) serv.send_error(401) return """ qstr = "INSERT INTO authtokens (tokenid,userid,type,permissions,expiration) VALUES(" qstr += estr(tok)+","+estr(userid)+"," qstr += estr(toktypes["R"])+","+estr(default_permission)+"," qstr += estr(exprtime)+")" """ cur.execute(qstr) con.commit() body = json.dumps({"refresh_token": str(tok), "result": 1}) body = bstr(body) serv.gen_headers("GET", len(body), json_mimetype) serv.wfile.write(body)
def do_PUT(self, serv): alog("fileapi access" + serv.path) qs = get_qs(serv.path) if "accessToken" not in qs or "uploadToken" not in qs: elog("fileapi: invalid tokens") serv.send_error(400) return tok = qs["accessToken"][0] utoken = qs["uploadToken"][0] userid = do_auth(tok) if userid == None: elog("invalid authorization") serv.send_error(401) return status = UploadStatus(utoken) if status.invalid: elog("invalid upload token ", utoken) serv.send_error(401) return if "Content-Range" not in serv.headers: elog("missing header " + json.dumps(serv.headers)) serv.send_error(400) return r = serv.headers["Content-Range"].strip() if not r.startswith("bytes"): elog("malformed request 1") serv.send_error(400) return r = r[len("bytes"):].strip() r = r.split("/") if r == None or len(r) != 2: elog("malformed request 2") serv.send_error(400) return try: max_size = int(r[1]) except ValueError: elog("malformed request 3") serv.send_error(400) return r = r[0].split("-") if r == None or len(r) != 2: elog("malformed request 4") serv.send_error(400) return try: r = [int(r[0]), int(r[1])] except ValueError: elog("malformed request 4") serv.send_error(400) return if r[0] < 0 or r[1] < 0 or r[0] >= max_size or r[1] >= max_size \ or r[0] > r[1]: elog("malformed request 5") serv.send_error(400) return if status.size == -1: status.size = max_size buflen = r[1]-r[0]+1 buf = serv.rfile.read(buflen) if len(buf) != buflen: elog("malformed request 6") serv.send_error(400) return """ if not status.file_init: status.file = open(status.realpath, "wb") csize = 1024*1024*1024 ilen = math.ceil(max_size/csize); zerobuf = b""*csize; for i in range(ilen): if i == ilen-1: c = b""*(max_size%(csize+1)) else: c = zerobuf; status.file.write(c) status.file.flush() status.file.close() #""" if r[0] == 0: mode = "wb" else: mode = "ab" status.file = open(status.realpath, mode); status.file.seek(r[0]); status.file.write(buf); status.file.flush() status.file.close() status.commit() body = json.dumps({"success" : True}); body = bstr(body) serv.gen_headers("PUT", len(body), json_mimetype) serv.wfile.write(body)
def do_GET(self): self.set_ipaddr() alog("GET " + self.path) if "Connection" in self.headers: keep_alive = self.headers["Connection"].strip().lower( ) == "keep-alive" else: keep_alive = False wf = self.wfile body = [b"yay, tst"] print(self.path) path = os.path.normpath(doc_root + self.path) if not os.path.exists(path): print("ble") if self.has_handler(self.path): self.exec_handler(self.path, "GET") return self.send_error(404) return if not self.path.startswith("/js_build/"): print(self.path) self.send_error(401) return if debug_file(path): always = True errbuf = run_build(path, always_build_file=always) if "js_build" in path and path.strip().endswith(".html"): errbuf = run_build(path, do_all=True) else: errbuf = None if errbuf != None: body = [self.format_err(errbuf)] else: f = open(path, "rb") csize = 1024 * 1024 ret = f.read(csize) body = [ret] while ret not in ["", b'', None]: ret = f.read(csize) body.append(ret) f.close() if type(body) == str: body = [bytes.decode(body, "latin-1")] elif type(body) == bytes: body = [body] bodysize = 0 for chunk in body: bodysize += len(chunk) if path.strip().endswith(".js"): mm = "application/javascript" else: mm = mime(path)[0] self.gen_headers("GET", bodysize, mm) b = b"" for chunk in body: b += chunk wf.write(b) print(mm)