U AT^c @shdZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlZddlZddlZdd d d d d ddddddg ZdadaddZddZddZddZeadade jddfdd Zd0d d Zd!d"Zd#d Z Gd$ddZ!Gd%d d Z"e jfd&d Z#d1d'dZ$e jfd(dZ%d)dZ&d*dZ'd+dZ(d,dZ)d-d.Z*e+d/krde#dS)2zSupport 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)MessageMiniFieldStorage FieldStorageparseparse_multipart parse_headertestprint_exception print_environ print_formprint_directoryprint_argumentsprint_environ_usagecGsFtr,ts,zttdaWntk r*YnXts6tantat|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). ZaN)logfilelogfpZopenOSErrornologlogdologZallargsr/usr/lib64/python3.8/cgi.pyinitlog8srcGst||ddS)z=Write a log message to the log file. See initlog() for docs. N)rwrite)Zfmtargsrrrr[rcGsdS)z9Dummy function, assigned to log when logging is disabled.Nrrrrrr_r!rcCsdatrtdatadS)zClose the log file.rN)rrcloserrrrrrcloselogcs r#c CsV|dkrtj}t|dr |j}nd}t|tr4|j}d|krDd|d<|ddkrt|d\}}|dkrtt||S|d krt |d }t r|t krt d | | |}nd }d |kr|r|d}||d }n(tjddr|r|d}|tjd}||d <nsz#parse_multipart..)r8ZformatrZset_typer)r;r@r$rFrDr?rErrIrr s    ccs|dddkr|dd}|d}|dkr`|dd||dd|dr`|d|d}q&|dkrpt|}|d|}|V||d}qdS)Nr.;r"\")findZcountlenstrip)sendfrrr _parseparams  (  rTcCstd|}|}i}|D]}|d}|dkr|d|}||dd}t|dkr|d|dkrdkrnn |dd}|d d d d}|||<q||fS) zfParse a Content-type like header. Return the main content-type and a dictionary of options. rJz=rNr.rMrKz\\z\rL)rTZ__next__rNrPZlowerrOrC)lineZpartskeyr@ZpZinamevaluerrrr s  ,  c@s@eZdZdZdZdZdZdZiZdZ iZ iZ ddZ ddZ dS)rz=Like FieldStorage, for use when no file uploads are possible.NcCs||_||_dS)z&Constructor from field name and value.NrXrYselfrXrYrrr__init__szMiniFieldStorage.__init__cCsd|j|jfS)z Return printable representation.zMiniFieldStorage(%r, %r)rZr\rrr__repr__r!zMiniFieldStorage.__repr__)__name__ __module__ __qualname____doc__filenamelisttypefile type_options dispositiondisposition_optionsrEr]r_rrrrrsc @seZdZdZdddejddddddf ddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ d:ddZd;ddZddZddZdd Zd!d"Zd#d$Zd%d&ZdZd'd(Zd)d*Zd+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zd8d9Z dS)max_num_fieldsZupper qs_on_postr/r9ZencodelocaleZgetpreferredencodingrr2rr TypeErrorrEr0r3r;rr1r$rFbytesrfr` outerboundary bytes_readlimitr rirjrXrd _binary_filerh innerboundaryr4r6r5lengthrergdoneread_urlencoded read_multi read_single)r\r;rErsr<r=r>rur$rFrnZmethodrAZcdispr@r?Zclenrrrr]8s/                          zFieldStorage.__init__cCs(z|jWntk r"YnXdSN)rgr"AttributeErrorr^rrr__del__szFieldStorage.__del__cCs|Sr}rr^rrr __enter__zFieldStorage.__enter__cGs|jdSr})rgr")r\r rrr__exit__rzFieldStorage.__exit__cCsd|j|j|jfS)z"Return a printable representation.zFieldStorage(%r, %r, %r))rXrdrYr^rrrr_s zFieldStorage.__repr__cC t|Sr})Ziterkeysr^rrr__iter__rzFieldStorage.__iter__cCsT|dkrt||jr:|jd|j}|jdn|jdk rL|j}nd}|S)NrYr)r~rgseekr7rer[rrr __getattr__s   zFieldStorage.__getattr__cCs^|jdkrtdg}|jD]}|j|kr||q|sBt|t|dkrV|dS|SdS)zDictionary style indexing.N not indexabler.r)rerqrXappendZKeyErrorrO)r\rWZfounditemrrr __getitem__s    zFieldStorage.__getitem__cCs8||kr0||}t|tr(dd|DS|jSn|SdS)z8Dictionary style get() method, including 'value' lookup.cSg|] }|jqSrrYrHZxrrr z)FieldStorage.getvalue..Nr2rerYr\rWZdefaultrYrrrgetvalue s  zFieldStorage.getvaluecCs4||kr,||}t|tr$|djS|jSn|SdS)z! Return the first value received.rNrrrrrgetfirsts   zFieldStorage.getfirstcCs:||kr2||}t|tr(dd|DS|jgSngSdS)z Return list of received values.cSrrrrrrrr&rz(FieldStorage.getlist..Nr)r\rWrYrrrrG!s   zFieldStorage.getlistcCs*|jdkrtdttdd|jDS)zDictionary style keys() method.Nrcss|] }|jVqdSr}rXrHrrrr 0z$FieldStorage.keys..)rerqZsetr^rrrr, zFieldStorage.keyscs*|jdkrtdtfdd|jDS)z%Dictionary style __contains__ method.Nrc3s|]}|jkVqdSr}rrrWrrr6rz,FieldStorage.__contains__..)rerqZany)r\rWrrr __contains__2rzFieldStorage.__contains__cCr)z Dictionary style len(x) support.)rOrr^rrr__len__8r!zFieldStorage.__len__cCs|jdkrtdt|jS)NzCannot be converted to bool.)rerqZboolr^rrr__bool__<s zFieldStorage.__bool__cCs|j|j}t|ts0td|jt|jf||j |j }|j rT|d|j 7}t j j||j|j|j |j |jd}dd|D|_|dS)z+Internal: read data in query string format.%s should return bytes, got %sr-r$rFrncSsg|]\}}t||qSrrrHrWrYrrrrNsz0FieldStorage.read_urlencoded..N)r;r7rxr2rrr6rfr`r8r$rFror:r parse_qslr=r>rnre skip_lines)r\rAqueryrrrrzAs$ zFieldStorage.read_urlencodedc Cs>|j}t|std|fg|_|jrbtjj|j|j|j |j |j |j d}|j dd|D|jpl|j}|j}t|tstd|jt|jf|jt|7_|d|jkr|r|j}|jt|7_q|j }|dk r|t|j8}t} d} |j} | | 7} | sq*q| s4q2|jt| 7_| | |j |j | } d | krt| d =|jdkrdn |j|j} ||j| ||||| |j |j | }|dk r|d 8}|jr|t|j8}|d krtd |j|j7_|j||js2|j|j kr(d krnqq2q|!dS) z/Internal: read a part that is itself multipart.z&Invalid boundary in multipart form: %rrcss|]\}}t||VqdSr}rrrrrr^sz*FieldStorage.read_multi..r--Nrkrlr.rzMax number of fields exceeded)"rwvalid_boundaryr6reror:r rr=r>r$rFrnZextendFieldStorageClassZ __class__r;rmr2rrrfr`rtrOrPrZfeedr8r"rurryrxr)r\r<r=r>ZibrZklassZ first_linernZparserZhdr_textdatarEruZpartrrrr{Ss~           &zFieldStorage.read_multicCs4|jdkr||n||jddS)zInternal: read an atomic part.rN)rx read_binaryr read_linesrgrr^rrrr|s   zFieldStorage.read_singlei cCs||_|j}|dkr|dkr|jt||j}t|tsVt d|jt |j f|j t |7_ |std|_q|j||t |}qdS)zInternal: read binary data.rrrUN) make_filergrxr;r7Zminbufsizer2rrr6rfr`rtrOryr)r\Ztodorrrrrs   zFieldStorage.read_binarycCs@|jrt|_|_nt|_|_|jr4|n|dS)z0Internal: read lines until EOF or outerboundary.N)rvrrg_FieldStorage__filerrsread_lines_to_outerboundaryread_lines_to_eofr^rrrrs  zFieldStorage.read_linescCsv|jdk rF|jt|dkrF||_|j}|j|d|_|jrZ|j|n|j||j |j dS)z line is always bytes, not stringNi) rZtellrOrrgrrrvr8r$rF)r\rVrrrrZ__writes    zFieldStorage.__writecCs:|jd}|jt|7_|s*d|_q6||qdS)zInternal: read lines until EOF.rUN)r;rmrtrOry_FieldStorage__write)r\rVrrrrs  zFieldStorage.read_lines_to_eofc Cs8d|j}|d}d}d}d}|jdk r6||jkr6q4|jd}|jt|7_|t|7}|snd|_q4|dkr||}d}|dr|r|}||krq4||krd |_q4|}| d rd }|dd }d}nJ| d rd }|dd}d}n*| drd}|dd}d }nd}d }| ||qdS)zInternal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons. rrkTrNrrUs r.s i F) rsrur;rmrtrOryZ startswithZrstripendswithr) r\ next_boundary last_boundaryZdelimlast_line_lfendZ_readrV strippedlineZodelimrrrrsN         z(FieldStorage.read_lines_to_outerboundarycCs|jr |jrdSd|j}|d}d}|jd}|jt|7_|sPd|_q|dr|r|}||krpq||krd|_q|d}q&dS)z5Internal: skip lines until outer boundary if defined.NrTrrUr.r)rsryr;rmrtrOrrP)r\rrrrVrrrrr s$   zFieldStorage.skip_linescCs&|jrtdStjd|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$ZnewlineN)rvtempfileZ TemporaryFiler$r^rrrrs  zFieldStorage.make_filer}r})!r`rarbrcosr<r]rrrr_rrrrrrGrrrrrzrr{r|rrrrrrrrrrrrr sJ) %   E   1cCstdttjt_zNt}ttt|t|t dd}|fdd}td|Wnt YnXtdda z&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?)ZexecrrrrrSRrztest..fcSs |dSr}r)rSrrrgTrztest..gz9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

i2N) printr/ZstdoutZstderrrrrrrrr r5)r<formrSrrrrr As4    c Csx|dkrt\}}}ddl}ttd||||||}tdtd|ddt|df~dS)Nrz+

Traceback (most recent call last):

z
%s%s
rrU) r/Zexc_info tracebackrZ format_tbZformat_exception_onlyhtmlescapeZjoin)rfrYZtbrurrerrrr hs   c Cs\t|}ttdtd|D]"}tdt|dt||q&tdtdS)z#Dump the shell environment as HTML.z

Shell Environment:





N)sortedrrrr)r<rrWrrrrvs  cCst|}ttd|s&tdtd|D]Z}tdt|ddd||}tdttt|d td tt|q2td td S) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.rrz:z )rRzzrrN)rrrrrZreprrf)rrrWrYrrrrs c Csjttdz t}Wn6tk rP}ztdtt|W5d}~XYnXtt|tdS)z#Dump the current directory as HTML.z#

Current Working Directory:

zOSError:N)rrZgetcwdrrrZstr)ZpwdZmsgrrrrs &cCs(ttdtttjtdS)Nz

Command Line Arguments:

)rr/r9rrrrrs  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)rrrrrrr!cCs(ddl}t|trd}nd}|||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rer2rrZmatch)rQrZ _vb_patternrrrrs  rZ__main__)rBrC)NNNN),rcZ __version__ZiorrrZcollections.abcrr/rZ urllib.parser:Z email.parserrZ email.messagerrrprZ__all__rrrrrr#rr5r<r r rTr rrr r rrrrrrr`rrrrZ sb   # B  8'   /