| 1 |
""" |
| 2 |
Common code supporting functionality described in DALI. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
from twisted.web import resource |
| 12 |
from twisted.web import server |
| 13 |
|
| 14 |
from gavo import base |
| 15 |
from gavo import formats |
| 16 |
from gavo import svcs |
| 17 |
from gavo import utils |
| 18 |
from gavo.base import sqlmunge |
| 19 |
from gavo.votable import V |
| 20 |
|
| 21 |
# Upload stuff -- note that TAP uploads are somewhat different from the |
| 22 |
# DALI ones, as TAP allows multiple uploads in one string. Hence, we |
| 23 |
# have a different (and simpler) implementation here. |
| 24 |
|
| 25 |
|
| 26 |
def getUploadKeyFor(inputKey): |
| 27 |
"""returns an input key for file items in "PQL". |
| 28 |
|
| 29 |
This is actually specified by DALI. In that scheme, the parameter |
| 30 |
is always called UPLOAD (there can thus only be one such parameter, |
| 31 |
but it can be present multiple times in calls if necessary, except we've |
| 32 |
not figured out how to do the description right in that case). |
| 33 |
|
| 34 |
It contains a comma-separated (key,source) pair, where |
| 35 |
source is a URL; there's a special scheme param: for referring to |
| 36 |
inline uploads by their name. |
| 37 |
|
| 38 |
This is used exclusively for metadata generation, and there's special |
| 39 |
code to handle it there. There's also special code in |
| 40 |
mangleUploads (called by, e.g., the ApiRenderer) to magcially make UPLOAD |
| 41 |
into the file parameters we use within DaCHS. Sigh. |
| 42 |
""" |
| 43 |
return inputKey.change( |
| 44 |
name="UPLOAD", |
| 45 |
type="pql-upload", |
| 46 |
description="An upload of the form '%s,URL'; the input for this" |
| 47 |
" parameter is then taken from URL, which may be param:name" |
| 48 |
" for pulling the content from the inline upload name. Purpose" |
| 49 |
" of the upload: %s"%(inputKey.name, inputKey.description), |
| 50 |
values=None) |
| 51 |
|
| 52 |
# pql-uploads never contribute to SQL queries |
| 53 |
sqlmunge.registerSQLFactory("pql-upload", lambda field, val, sqlPars: None) |
| 54 |
|
| 55 |
|
| 56 |
def parseUploadString(uploadString): |
| 57 |
"""returns resourceName, uploadSource from a DALI upload string. |
| 58 |
""" |
| 59 |
try: |
| 60 |
destName, uploadSource = uploadString.split(",", 1) |
| 61 |
except (TypeError, ValueError): |
| 62 |
raise base.ValidationError("Invalid UPLOAD string", |
| 63 |
"UPLOAD", hint="UPLOADs look like my_upload,http://foo.bar/up" |
| 64 |
" or inline_upload,param:foo.") |
| 65 |
return destName, uploadSource |
| 66 |
|
| 67 |
|
| 68 |
class URLUpload(object): |
| 69 |
"""a somewhat FieldStorage-compatible facade to an upload coming from |
| 70 |
a URL. |
| 71 |
|
| 72 |
The filename for now is the complete upload URL, but that's likely |
| 73 |
to change. |
| 74 |
""" |
| 75 |
def __init__(self, uploadURL, uploadName): |
| 76 |
self.uploadURL, self.name = uploadURL, uploadName |
| 77 |
self.file_object = utils.urlopenRemote(self.uploadURL) |
| 78 |
self.file_name = uploadURL |
| 79 |
self.headers = self.file_object.info() |
| 80 |
major, minor, parSet = formats.getMIMEKey( |
| 81 |
self.headers.get("content-type", "*/*")) |
| 82 |
self.type = "%s/%s"%(major, minor) |
| 83 |
self.type_options = dict(parSet) |
| 84 |
|
| 85 |
@property |
| 86 |
def value(self): |
| 87 |
try: |
| 88 |
f = utils.urlopenRemote(self.uploadURL) |
| 89 |
return f.read() |
| 90 |
finally: |
| 91 |
f.close() |
| 92 |
|
| 93 |
|
| 94 |
def iterUploads(request): |
| 95 |
"""iterates over DALI uploads in request. |
| 96 |
|
| 97 |
This yields pairs of (file name, file object), where file name |
| 98 |
is the file name requested (sanitized to have no slashes and non-ASCII). |
| 99 |
The UPLOAD and inline-file keys are removed from request's args |
| 100 |
member. The file object is a cgi-style thing with file, filename, |
| 101 |
etc. attributes. |
| 102 |
""" |
| 103 |
# UWS auto-downcases things (it probably shouldn't) |
| 104 |
uploads = request.strargs.pop("UPLOAD", []) |
| 105 |
if not uploads: |
| 106 |
return |
| 107 |
|
| 108 |
for uploadString in uploads: |
| 109 |
paramName, uploadSource = parseUploadString(uploadString) |
| 110 |
try: |
| 111 |
if uploadSource.startswith("param:"): |
| 112 |
fileKey = uploadSource[6:] |
| 113 |
upload = request.files[fileKey][0] |
| 114 |
else: |
| 115 |
upload = URLUpload(uploadSource, paramName) |
| 116 |
|
| 117 |
yield paramName, upload |
| 118 |
except (KeyError, AttributeError): |
| 119 |
raise base.ui.logOldExc(base.ValidationError( |
| 120 |
"%s references a non-existing" |
| 121 |
" file upload."%uploadSource, "UPLOAD", |
| 122 |
hint="If you pass UPLOAD=foo,param:x," |
| 123 |
" you must pass a file upload under the key x.")) |
| 124 |
|
| 125 |
|
| 126 |
def mangleUploads(request): |
| 127 |
"""manipulates request such that DALI UPLOADs appear in strargs |
| 128 |
as pairs of name and file/URLUpload |
| 129 |
|
| 130 |
These are as in normal CGI: uploads are under "their names" (with |
| 131 |
DALI uploads, the resource names), with values being pairs of |
| 132 |
some name and a FieldStorage-compatible thing having name, filename, value, |
| 133 |
file, type, type_options, and headers. |
| 134 |
|
| 135 |
This will also overwrite upload with a sequence of (name, file) for |
| 136 |
all uploads for the benefit of uws. |
| 137 |
|
| 138 |
There's different code for this in TAP because regrettably TAP works a bit |
| 139 |
differently from this. |
| 140 |
""" |
| 141 |
newUploads = [] |
| 142 |
try: |
| 143 |
for paramName, fObject in iterUploads(request): |
| 144 |
request.strargs[paramName] = ( |
| 145 |
utils.defuseFileName(fObject.file_name), fObject.file_object) |
| 146 |
newUploads.append((paramName, request.strargs[paramName])) |
| 147 |
except base.Error: |
| 148 |
raise |
| 149 |
except Exception as ex: |
| 150 |
raise base.ui.logOldExc( |
| 151 |
base.ValidationError("Processing upload failed: %s"%ex, |
| 152 |
"UPLOAD", hint="If this was a URL upload, perhaps I" |
| 153 |
" just can't see the machine the URL is pointing to?")) |
| 154 |
|
| 155 |
request.strargs["upload"] = newUploads |
| 156 |
|
| 157 |
|
| 158 |
def getDALIError(errInfo, *, queryStatus="ERROR", request=None): |
| 159 |
"""returns a DALI-compliant error VOTable from an error info and |
| 160 |
a suggested http status code for the delivered document. |
| 161 |
|
| 162 |
errInfo can either be an exception, a UWS error info (a |
| 163 |
dict with keys msg and possibly hint and httpCode), or a |
| 164 |
pre-formatted string. |
| 165 |
""" |
| 166 |
if isinstance(errInfo, Exception): |
| 167 |
# don't touch redirects; they need more header manipulation than |
| 168 |
# we're willing to do here |
| 169 |
if isinstance(errInfo, svcs.RedirectBase): |
| 170 |
res = svcs.getDCErrorPage(errInfo) |
| 171 |
return res, res.status |
| 172 |
|
| 173 |
errInfo = { |
| 174 |
"msg": str(errInfo), |
| 175 |
"hint": getattr(errInfo, "hint", None), |
| 176 |
"httpCode": getattr(errInfo, "httpCode", 500)} |
| 177 |
|
| 178 |
elif isinstance(errInfo, str): |
| 179 |
errInfo = { |
| 180 |
"msg": errInfo, |
| 181 |
"hint": None} |
| 182 |
|
| 183 |
res = V.RESOURCE(type="results") [ |
| 184 |
V.INFO(name="QUERY_STATUS", value=queryStatus)[ |
| 185 |
errInfo["msg"]]] |
| 186 |
if request: |
| 187 |
res[V.INFO(name="request", value=request.asGETURI())] |
| 188 |
|
| 189 |
if errInfo.get("hint"): |
| 190 |
res[V.INFO(name="HINT", value="HINT")[ |
| 191 |
errInfo["hint"]]] |
| 192 |
|
| 193 |
return V.VOTABLE[res], errInfo.get("httpCode", 500) |
| 194 |
|
| 195 |
|
| 196 |
def serveDALIError(request, errInfo, *, httpStatus=None, queryStatus="ERROR"): |
| 197 |
"""serves a DALI-compliant error message from errInfo. |
| 198 |
|
| 199 |
See getDALIError for what errInfo can be. |
| 200 |
|
| 201 |
This closes the request and returns NOT_DONE_YET, so you |
| 202 |
can write ``return serveDALIError`` in normal render functions |
| 203 |
|
| 204 |
Regrettably, various protocols at times required 200 HTTP statuses |
| 205 |
even for error messages. If you need "odd" http statuses, pass |
| 206 |
one in here. Otherwise, we will try to infer something suitable |
| 207 |
from errInfo (httpCode key in a dict, httpCode attribute on an |
| 208 |
Exception, 500 for strings). |
| 209 |
""" |
| 210 |
if request._disconnected: |
| 211 |
# the other end has hung up; don't touch the connection any more, |
| 212 |
# they won't see our error anyway. |
| 213 |
return server.NOT_DONE_YET |
| 214 |
|
| 215 |
try: |
| 216 |
errVOT, errStatus = getDALIError(errInfo, |
| 217 |
queryStatus=queryStatus, request=request) |
| 218 |
if httpStatus is None: |
| 219 |
httpStatus = errStatus |
| 220 |
if isinstance(errVOT, resource.Resource): |
| 221 |
return errVOT.render(request, finish=False) |
| 222 |
|
| 223 |
request.setHeader("content-type", "text/xml") |
| 224 |
request.setResponseCode(httpStatus) |
| 225 |
request.write( |
| 226 |
utils.xmlrender(errVOT, |
| 227 |
prolog="<?xml-stylesheet href='/static/xsl/" |
| 228 |
"dalierror-to-html.xsl' type='text/xsl'?>")) |
| 229 |
except Exception as ex: |
| 230 |
request.write(b"Ouch. Can't even produce an error any more.\n") |
| 231 |
base.ui.notifyError(f"Exception while trying to serve error: {ex}") |
| 232 |
finally: |
| 233 |
request.finish() |
| 234 |
return server.NOT_DONE_YET |
| 235 |
|
| 236 |
|
| 237 |
class DALIErrorResource(resource.Resource): |
| 238 |
"""A DALI error (i.e., an INFO in a VOTable. |
| 239 |
|
| 240 |
This is constructed with an exception or a UWS errInfo (see getDALIError). |
| 241 |
|
| 242 |
Use this when you want to return a DALI error from within a getChild |
| 243 |
function. Otherwise, just use serveDALIError. |
| 244 |
""" |
| 245 |
isLeaf = True |
| 246 |
def __init__(self, errInfo, *, httpStatus=None, queryStatus="ERROR"): |
| 247 |
self.errInfo = errInfo |
| 248 |
self.httpStatus = httpStatus |
| 249 |
self.queryStatus = queryStatus |
| 250 |
|
| 251 |
def render(self, request): |
| 252 |
return serveDALIError( |
| 253 |
request, |
| 254 |
self.errInfo, |
| 255 |
httpStatus=self.httpStatus, |
| 256 |
queryStatus=self.queryStatus) |