3 fc@sdZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlmZddlZddlZddlZd d d d d ddddddddddgZdadaddZddZddZdd Zeadade jdddfd!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 Cs\|dkrtj}t|dr |j}nd}t|tr4|j}d|krDd|d<|ddkr t|d\}}|dkrxt|||d S|d krt |d }t r|t krt d |j |j |} nd } d|kr| r| d} | |d} n*tjddr| r| d} | tjd} | |d<nr 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. NrJrzutf-8rlc  CsRd} ||_||_| |_| |_d|kr0|dj} d|_| dksF| dkrd|krX|d} ntjddrrtjd} nd} | jt j d} t | }|dkrd d i}|dkri}| d krd |d <d |kr|d |d <d|kr|d|_d |kr|d |d<nt |t tfstd||_|dkr*tjj|_nencodelocalegetpreferredencodingrr7rr TypeErrorrZr5r8r@rr6r*errorsrXrzrt outerboundary bytes_readlimitrr}r~rMrx _binary_filer| innerboundaryr9r;r:lengthryr{doneread_urlencoded read_multi read_single)rqr@rZrrArBrCrr*rrr/methodrGZcdisprErDZclenr"r"r#rrs/                         zFieldStorage.__init__c Cs(y|jjWntk r"YnXdS)N)r{r(AttributeError)rqr"r"r#__del__;szFieldStorage.__del__cCs|S)Nr")rqr"r"r# __enter__AszFieldStorage.__enter__cGs|jjdS)N)r{r()rqr'r"r"r#__exit__DszFieldStorage.__exit__cCsd|j|j|jfS)z"Return a printable representation.zFieldStorage(%r, %r, %r))rMrxrp)rqr"r"r#rsGszFieldStorage.__repr__cCs t|jS)N)iterkeys)rqr"r"r#__iter__LszFieldStorage.__iter__cCsT|dkrt||jr:|jjd|jj}|jjdn|jdk rL|j}nd}|S)Nrpr)rr{seekr<ry)rqrMrpr"r"r# __getattr__Os   zFieldStorage.__getattr__cCsb|jdkrtdg}x"|jD]}|j|kr|j|qW|sFt|t|dkrZ|dS|SdS)zDictionary style indexing.Nz not indexabler3r)ryrrMrUKeyErrorrb)rqr]founditemr"r"r# __getitem__\s    zFieldStorage.__getitem__cCs8||kr0||}t|tr(dd|DS|jSn|SdS)z8Dictionary style get() method, including 'value' lookup.cSsg|] }|jqSr")rp).0xr"r"r# osz)FieldStorage.getvalue..N)r7ryrp)rqr]defaultrpr"r"r#getvaluejs  zFieldStorage.getvaluecCs4||kr,||}t|tr$|djS|jSn|SdS)z! Return the first value received.rN)r7ryrp)rqr]rrpr"r"r#getfirstus   zFieldStorage.getfirstcCs:||kr2||}t|tr(dd|DS|jgSngSdS)z Return list of received values.cSsg|] }|jqSr")rp)rrr"r"r#rsz(FieldStorage.getlist..N)r7ryrp)rqr]rpr"r"r#getlists   zFieldStorage.getlistcCs*|jdkrtdttdd|jDS)zDictionary style keys() method.Nz not indexablecss|] }|jVqdS)N)rM)rrr"r"r# sz$FieldStorage.keys..)ryrset)rqr"r"r#rs zFieldStorage.keyscs*|jdkrtdtfdd|jDS)z%Dictionary style __contains__ method.Nz not indexablec3s|]}|jkVqdS)N)rM)rr)r]r"r#rsz,FieldStorage.__contains__..)ryrany)rqr]r")r]r# __contains__s zFieldStorage.__contains__cCs t|jS)z Dictionary style len(x) support.)rbr)rqr"r"r#__len__szFieldStorage.__len__cCs|jdkrtdt|jS)NzCannot be converted to bool.)ryrbool)rqr"r"r#__bool__s zFieldStorage.__bool__c Cs|jj|j}t|ts0td|jt|jf|j|j |j }|j rT|d|j 7}t j j||j|j|j |j |j|jd}dd|D|_|jdS)z+Internal: read data in query string format.z%s should return bytes, got %sr2)r*rrr/cSsg|]\}}t||qSr")r )rr]rpr"r"r#rsz0FieldStorage.read_urlencoded..N)r@r<rr7rXr;rzrtr=r*rrr?r r rBrCrr/ry skip_lines)rqrGqueryr"r"r#rs  zFieldStorage.read_urlencodedc CsB|j}t|std|fg|_|jrftjj|j|j|j |j |j |j |j d}|jjdd|D|jpp|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| sBP|jt| 7_| j| j|j |j | j} d | kr| d =||j| |||||j|j|j |j ||j d } |dk r|d 8}| jr|t| j8}|d krtd |j| j7_|jj| | j s.|j|j!ko&d knr Pq W|j"dS)z/Internal: read a part that is itself multipart.z&Invalid boundary in multipart form: %r)r*rrr/css|]\}}t||VqdS)N)r )rr]rpr"r"r#rsz*FieldStorage.read_multi..z%s should return bytes, got %ss--NrJzcontent-length)r/r3rzMax number of fields exceeded)#rrPr;ryrr?r r rBrCr*rrr/extendFieldStorageClass __class__r@rRr7rXrzrtrrbrcrZfeedr=r(rrUrrr)rqrArBrCZibrklassZ first_linerparserZhdr_textrYrZpartr"r"r#rsj               (zFieldStorage.read_multicCs4|jdkr|j|jn|j|jjddS)zInternal: read an atomic part.rN)r read_binaryr read_linesr{r)rqr"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 %sr3NrN) make_filer{rr@r<minbufsizer7rXr;rzrtrrbrr&)rqZtodorYr"r"r#rs    zFieldStorage.read_binarycCs@|jrt|_|_nt|_|_|jr4|jn|jdS)z0Internal: read lines until EOF or outerboundary.N)rrr{_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eof)rqr"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) rtellrbrr{rr&rr=r*r)rqr\rYr"r"r#Z__writes    zFieldStorage.__writecCs>x8|jjd}|jt|7_|s,d|_P|j|qWdS)zInternal: read lines until EOF.r3NirN)r@rRrrbr_FieldStorage__write)rqr\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--rJTrr3r s NrHrLFirNrOrNrN) rrr@rRrrbrrSrTendswithr) rq next_boundary last_boundaryZdelimlast_line_lfendZ_readr\ strippedlineZodelimr"r"r#r6sP          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--Tr3rrLirN)rrr@rRrrbrrc)rqrrrr\rr"r"r#rgs&  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*)rqr"r"r#r}s zFieldStorage.make_file)N)Ni )!rtrurvrwosrArrrrrrsrrrrrrrrrrrrrrrrrrrrrrr"r"r"r#r ls@*"   D   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#rfsztest..fcSs |dS)Nr")rfr"r"r#gsztest..gz9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

2N) printr4stdoutstderrr rrrrrrr:)rAformrfrr"r"r#rs4    cCsx|dkrtj\}}}ddl}ttd|j|||j||}tdtjdj|ddtj|df~dS)Nrz+

Traceback (most recent call last):

z
%s%s
rr3rNrN) r4exc_info tracebackr format_tbformat_exception_onlyhtmlrrV)rzrptbrrryr"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)rArr]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
: )rezzz
z
N)rrrrrreprrz)rrr]rpr"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:

)rr4r>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 insteadrH) stacklevelr2z&z>r_z")rrIrl)rdZquoter"r"r#r1s     cCs(ddl}t|trd}nd}|j||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rer7rXmatch)rdrZ _vb_patternr"r"r#rP=s  rP__main__)rrN)rrN)NNNN)N)1rw __version__iorrr collectionsrr4rZ urllib.parser?Z email.parserrZ email.messagerwarningsrrrr__all__rrr$r rr)rr:rAr r r rrgrr r rrrrrrrrrPrtr"r"r"r#sb     # E  c 7'   /