3 \@sdZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlmZddlZddlZddlZd d d d d ddddddddddgZdadaddZddZddZdd Zeadade jddfd!d Zd5d"d Z d6d#d Z!d$dZ"d%d&Z#d'dZ$Gd(d d Z%Gd)d d Z&e jfd*dZ'd7d+dZ(e jfd,dZ)d-dZ*d.dZ+d/dZ,d0dZ-d8d1dZ.d2d3Z/e0d4kre'dS)9zSupport module for CGI (Common Gateway Interface) scripts. This module defines a number of utilities for use by CGI scripts written in Python. z2.6)StringIOBytesIO TextIOWrapper)MappingN) FeedParser)Message)warnMiniFieldStorage FieldStorageparseparse_qs parse_qslparse_multipart parse_headertestprint_exception print_environ print_formprint_directoryprint_argumentsprint_environ_usageescapec GsHtr.t r.yttdaWntk r,YnXts8tantat|dS)aWrite a log message, if there is a log file. Even though this function is called initlog(), you should always use log(); log is a variable that is set either to initlog (initially), to dolog (once the log file has been opened), or to nolog (when logging is disabled). The first argument is a format string; the remaining arguments (if any) are arguments to the % operator, so e.g. log("%s: %s", "a", "b") will write "a: b" to the log file, followed by a newline. If the global logfp is not None, it should be a file object to which log data is written. If the global logfp is None, the global logfile may be a string giving a filename to open, in append mode. This file should be world writable!!! If the file can't be opened, logging is silently disabled (since there is no safe place where we could send an error message). aN)logfilelogfpopenOSErrornologlogdolog)allargsr"/usr/lib64/python3.6/cgi.pyinitlog:s r$cGstj||ddS)z=Write a log message to the log file. See initlog() for docs. N)rwrite)Zfmtargsr"r"r#r ]sr cGsdS)z9Dummy function, assigned to log when logging is disabled.Nr")r!r"r"r#rasrcCsdatrtjdatadS)zClose the log file.rN)rrcloser$rr"r"r"r#closeloges r)c CsX|dkrtj}t|dr |j}nd}t|tr4|j}d|krDd|d<|ddkrt|d\}}|dkrtt||S|d krt |d }t r|t krt d |j |j |}nd }d |kr|r|d}||d }n*tjddr|r|d}|tjd}||d <nr r )rFrArBr"r"r#r scCstdtdtjj|||S)z)Parse a query given as a string argument.z?cgi.parse_qsl is deprecated, use urllib.parse.parse_qsl insteadrG)rrHr>r r )rFrArBr"r"r#r sc Csddl}d}d|kr|d}t|s2td|fd|}d|d}i}d}x||krd}d} |r|jj|} | jd} | ry t| }Wntk rYnX|dkrtr|tkrtd |j|} nd} g} xD|j } | s|}P| j dr | j }|||fkr P| j | qW| dkr&qR|dkr| r| d} | ddd kr^| dd} n| ddd kr|| dd} | | d<dj | } | d } | sqRt| \}}|dkrqRd|krR|d}nqR||kr||j | qR| g||<qRW|S)aParse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. Also, FieldStorage protects itself better against certain DoS attacks by limiting the size of the data read in one chunk. The API here does not support that kind of protection. This also affects parse() since it can call parse_multipart(). rNboundaryz&Invalid boundary in multipart form: %rs--r2zcontent-lengthzMaximum content length exceededrGs  zcontent-dispositionz form-datanamerMrNrMrMrM)Z http.clientvalid_boundaryr:ZclientZ parse_headersgetr8r9r;readline startswithrstripappendjoinr)r?rDZhttprJZnextpartZlastpartZpartdict terminatorbytesdataheadersrElineslinekeyZparamsrLr"r"r#rs|                ccsx|dddkr|dd}|jd}x<|dkrd|jdd||jdd|drd|jd|d}q*W|dkrvt|}|d|}|jV||d}qWdS)Nr2;r"z\"rG)findcountlenstrip)sendfr"r"r# _parseparam-s  *  rfcCstd|}|j}i}x|D]}|jd}|dkr|d|jj}||ddj}t|dkr|d|d kodknr|dd }|jdd jd d}|||<qW||fS) zfParse a Content-type like header. Return the main content-type and a dictionary of options. r]=rNr2rGr^z\\\z\"rMrM)rf__next__r_rblowerrareplace)r[partsr\rDpirLvaluer"r"r#r9s   ,  c@s@eZdZdZdZdZdZdZiZdZ iZ iZ ddZ ddZ dS)r z=Like FieldStorage, for use when no file uploads are possible.NcCs||_||_dS)z&Constructor from field name and value.N)rLro)selfrLror"r"r#__init___szMiniFieldStorage.__init__cCsd|j|jfS)z Return printable representation.zMiniFieldStorage(%r, %r))rLro)rpr"r"r#__repr__eszMiniFieldStorage.__repr__)__name__ __module__ __qualname____doc__filenamelisttypefile type_options dispositiondisposition_optionsrYrqrrr"r"r"r#r Qsc @seZdZdZdddejddddddf ddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ d;ddZdr aStore a sequence of fields, reading multipart/form-data. This class provides naming, typing, files stored on disk, and more. At the top level, it is accessible like a dictionary, whose keys are the field names. (Note: None can occur as a field name.) The items are either a Python list (if there's multiple values) or another FieldStorage or MiniFieldStorage object. If it's a single object, it has the following attributes: name: the field name, if specified; otherwise None filename: the filename, if specified; otherwise None; this is the client side filename, *not* the file name on which it is stored (that's a temporary file you don't deal with) value: the value as a *string*; for file uploads, this transparently reads the file every time you request the value and returns *bytes* file: the file(-like) object from which you can read the data *as bytes* ; None if the data is stored a simple string type: the content-type, or None if not specified type_options: dictionary of options specified on the content-type line disposition: content-disposition, or None if not specified disposition_options: dictionary of corresponding options headers: a dictionary(-like) object (sometimes email.message.Message or a subclass thereof) containing *all* headers The class is subclassable, mostly for the purpose of overriding the make_file() method, which is called internally to come up with a file open for reading and writing. This makes it possible to override the default choice of storing all files in a temporary directory and unlinking them as soon as they have been opened. NrIrzutf-8rkc  CsLd} ||_||_| |_d|kr*|dj} d|_| dks@| dkrd|krR|d} ntjddrltjd} nd} | jtj d} t | }|dkrd d i}|dkri}| d krd |d <d |kr|d |d <d|kr|d|_d |kr|d |d<nt |t t fstd||_|dkr$tjj|_nszFieldStorage.__enter__cGs|jjdS)N)rzr()rpr'r"r"r#__exit__AszFieldStorage.__exit__cCsd|j|j|jfS)z"Return a printable representation.zFieldStorage(%r, %r, %r))rLrwro)rpr"r"r#rrDszFieldStorage.__repr__cCs t|jS)N)iterkeys)rpr"r"r#__iter__IszFieldStorage.__iter__cCsT|dkrt||jr:|jjd|jj}|jjdn|jdk rL|j}nd}|S)Nror)rrzseekr;rx)rprLror"r"r# __getattr__Ls   zFieldStorage.__getattr__cCsb|jdkrtdg}x"|jD]}|j|kr|j|qW|sFt|t|dkrZ|dS|SdS)zDictionary style indexing.Nz not indexabler2r)rxrrLrTKeyErrorra)rpr\founditemr"r"r# __getitem__Ys    zFieldStorage.__getitem__cCs8||kr0||}t|tr(dd|DS|jSn|SdS)z8Dictionary style get() method, including 'value' lookup.cSsg|] }|jqSr")ro).0xr"r"r# lsz)FieldStorage.getvalue..N)r6rxro)rpr\defaultror"r"r#getvaluegs  zFieldStorage.getvaluecCs4||kr,||}t|tr$|djS|jSn|SdS)z! Return the first value received.rN)r6rxro)rpr\rror"r"r#getfirstrs   zFieldStorage.getfirstcCs:||kr2||}t|tr(dd|DS|jgSngSdS)z Return list of received values.cSsg|] }|jqSr")ro)rrr"r"r#rsz(FieldStorage.getlist..N)r6rxro)rpr\ror"r"r#getlist}s   zFieldStorage.getlistcCs*|jdkrtdttdd|jDS)zDictionary style keys() method.Nz not indexablecss|] }|jVqdS)N)rL)rrr"r"r# sz$FieldStorage.keys..)rxrset)rpr"r"r#rs zFieldStorage.keyscs*|jdkrtdtfdd|jDS)z%Dictionary style __contains__ method.Nz not indexablec3s|]}|jkVqdS)N)rL)rr)r\r"r#rsz,FieldStorage.__contains__..)rxrany)rpr\r")r\r# __contains__s zFieldStorage.__contains__cCs t|jS)z Dictionary style len(x) support.)rar)rpr"r"r#__len__szFieldStorage.__len__cCs|jdkrtdt|jS)NzCannot be converted to bool.)rxrbool)rpr"r"r#__bool__s zFieldStorage.__bool__cCs|jj|j}t|ts0td|jt|jf|j|j |j }|j rT|d|j 7}t j j||j|j|j |j |jd}dd|D|_|jdS)z+Internal: read data in query string format.z%s should return bytes, got %sr1)r*rrcSsg|]\}}t||qSr")r )rr\ror"r"r#rsz0FieldStorage.read_urlencoded..N)r?r;rr6rWr:ryrsr<r*rrr>r r rArBrrx skip_lines)rprFqueryr"r"r#rs   zFieldStorage.read_urlencodedc Cs8|j}t|std|fg|_|jrbtjj|j|j|j |j |j |j d}|jj dd|D|jpl|j}|jj}t|tstd|jt|jf|jt|7_x6|jd|jkr|r|jj}|jt|7_qW|j }|dk r|t|j8}x&t} d} x$|jj} | | 7} | jsPqW| s>P|jt| 7_| j| j|j |j | j} d | kr~| d =||j| |||||j|j|j |j | } |dk r|d 8}| jr|t| j8}|d krtd |j| j7_|jj| | js$|j|j kod knrPqW|j!dS) z/Internal: read a part that is itself multipart.z&Invalid boundary in multipart form: %r)r*rrcss|]\}}t||VqdS)N)r )rr\ror"r"r#rsz*FieldStorage.read_multi..z%s should return bytes, got %ss--NrIzcontent-lengthr2rzMax number of fields exceeded)"rrOr:rxrr>r r rArBr*rrextendFieldStorageClass __class__r?rQr6rWryrsrrarbrZfeedr<r(rrTrrr)rpr@rArBZibrklassZ first_linerparserZhdr_textrXrYpartr"r"r#rsh              (zFieldStorage.read_multicCs4|jdkr|j|jn|j|jjddS)zInternal: read an atomic part.rN)r read_binaryr read_linesrzr)rpr"r"r#rs   zFieldStorage.read_singleicCs|j|_|j}|dkrxx|dkr|jjt||j}t|tsXt d|jt |j f|j t |7_ |svd|_P|jj||t |}qWdS)zInternal: read binary data.rz%s should return bytes, got %sr2NrM) make_filerzrr?r;minbufsizer6rWr:ryrsrrarr&)rpZtodorXr"r"r#rs    zFieldStorage.read_binarycCs@|jrt|_|_nt|_|_|jr4|jn|jdS)z0Internal: read lines until EOF or outerboundary.N)rrrz_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eof)rpr"r"r#rs  zFieldStorage.read_linescCsv|jdk rF|jjt|dkrF|j|_|jj}|jj|d|_|jrZ|jj|n|jj|j|j |j dS)z line is always bytes, not stringNi) rtellrarrzrr&rr<r*r)rpr[rXr"r"r#Z__writes    zFieldStorage.__writecCs>x8|jjd}|jt|7_|s,d|_P|j|qWdS)zInternal: read lines until EOF.r2NirM)r?rQrrar_FieldStorage__write)rpr[r"r"r#r(s zFieldStorage.read_lines_to_eofc Cs,d|j}|d}d}d}d}x||jkr.P|jjd }|jt|7_|t|7}|sdd|_P|dkrx||}d}|jdr|r|j}||krP||krd|_P|}|j drd}|d d}d}nJ|j d rd }|d d}d}n*|j drd}|d d}d }nd}d }|j ||q"Wd S)zInternal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons. s--rITrr2r s NrGrKFirMrNrMrM) rrr?rQrrarrRrSendswithr) rp next_boundary last_boundaryZdelimlast_line_lfendZ_readr[ strippedlineZodelimr"r"r#r2sP          z(FieldStorage.read_lines_to_outerboundarycCs|j s|jrdSd|j}|d}d}xh|jjd}|jt|7_|sTd|_P|jdr|r|j}||krtP||krd|_P|jd}q*WdS) z5Internal: skip lines until outer boundary if defined.Ns--Tr2rrKirM)rrr?rQrrarrb)rprrrr[rr"r"r#rcs&  zFieldStorage.skip_linescCs&|jrtjdStjd|jddSdS)aOverridable: return a readable & writable file. The file will be used as follows: - data is written to it - seek(0) - data is read from it The file is opened in binary mode for files, in text mode for other fields This version opens a temporary file for reading and writing, and immediately deletes (unlinks) it. The trick (on Unix!) is that the file can still be used, but it can't be opened by another process, and it will automatically be deleted when it is closed or when the current process terminates. If you want a more permanent file, you derive a class which overrides this method. If you want a visible temporary file that is nevertheless automatically deleted when the script terminates, try defining a __del__ method in a derived class which unlinks the temporary files you have created. zwb+zw+r%)r*newlineN)rtempfileZ TemporaryFiler*)rpr"r"r#rys zFieldStorage.make_file)N)Ni )!rsrtrurvosr@rqrrrrrrrrrrrrrrrrrrrrrrrrrrrr"r"r"r#r js@* !   C   1cCstdttjt_yNt}ttt|t|t dd}|fdd}td|Wnt YnXtdda y&t}ttt|t|Wnt YnXd S) zRobust test CGI script, usable as main program. Write minimal HTTP headers and dump all information provided to the script in HTML form. zContent-type: text/htmlcSs tddS)Nz,testing print_exception() -- italics?)execr"r"r"r#resztest..fcSs |dS)Nr")rer"r"r#gsztest..gz9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

2N) printr3stdoutstderrr rrrrrrr9)r@formrerr"r"r#rs4    cCsx|dkrtj\}}}ddl}ttd|j|||j||}tdtjdj|ddtj|df~dS)Nrz+

Traceback (most recent call last):

z
%s%s
rr2rMrM) r3exc_info tracebackr format_tbformat_exception_onlyhtmlrrU)ryrotbrrrxr"r"r#rs cCs`t|j}ttdtdx*|D]"}tdtj|dtj||q(WtdtdS)z#Dump the shell environment as HTML.z

Shell Environment:

z
z
z
z
N)sortedrrrr)r@rr\r"r"r#rs  "cCst|j}ttd|s&tdtdxb|D]Z}tdtj|ddd||}tdtjtt|d td tjt|q4Wtd td S) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.z

z
: )rdzzz
z
N)rrrrrreprry)rrr\ror"r"r#rs  cCsjttdy tj}Wn6tk rP}ztdtjt|WYdd}~XnXttj|tdS)z#Dump the current directory as HTML.z#

Current Working Directory:

zOSError:N)rrgetcwdrrrstr)pwdmsgr"r"r#rs &cCs(ttdtttjtdS)Nz

Command Line Arguments:

)rr3r=r"r"r"r#rs  cCs tddS)z9Dump a list of environment variables used by CGI as HTML.a

These environment variables could have been set:

  • AUTH_TYPE
  • CONTENT_LENGTH
  • CONTENT_TYPE
  • DATE_GMT
  • DATE_LOCAL
  • DOCUMENT_NAME
  • DOCUMENT_ROOT
  • DOCUMENT_URI
  • GATEWAY_INTERFACE
  • LAST_MODIFIED
  • PATH
  • PATH_INFO
  • PATH_TRANSLATED
  • QUERY_STRING
  • REMOTE_ADDR
  • REMOTE_HOST
  • REMOTE_IDENT
  • REMOTE_USER
  • REQUEST_METHOD
  • SCRIPT_NAME
  • SERVER_NAME
  • SERVER_PORT
  • SERVER_PROTOCOL
  • SERVER_ROOT
  • SERVER_SOFTWARE
In addition, HTTP headers sent by the server may be passed in the environment as well. Here are some common variable names:
  • HTTP_ACCEPT
  • HTTP_CONNECTION
  • HTTP_HOST
  • HTTP_PRAGMA
  • HTTP_REFERER
  • HTTP_USER_AGENT
N)rr"r"r"r#rs'cCsFtdtdd|jdd}|jdd}|jdd }|rB|jd d }|S) zDeprecated API.z1cgi.escape is deprecated, use html.escape insteadrG) stacklevelr1z&z>r^z")rrHrk)rcZquoter"r"r#r-s     cCs(ddl}t|trd}nd}|j||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rer6rWmatch)rcrZ _vb_patternr"r"r#rO9s  rO__main__)rr)rr)NNNN)N)1rv __version__iorrr collectionsrr3rZ urllib.parser>Z email.parserrZ email.messagerwarningsrrrr__all__rrr$r rr)rr9r@r r r rrfrr r rrrrrrrrrOrsr"r"r"r#s`     # E  d 5'   /