YfΌ@sOdZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlmZddlZddlZddlZd d d d d dddddddddgZdadaddZddZddZddZeadade jddd d Zddd!d Z ddd"d Z!d#dZ"d$d%Z#d&dZ$Gd'd d Z%Gd(d d Z&e jd)d*Z'ddddd+dZ(e jd,dZ)d-dZ*d.dZ+d/dZ,d0dZ-dd1dZ.d2d3Z/e0d4krKe'dS)5zSupport 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_headerprint_exception print_environ print_formprint_directoryprint_argumentsprint_environ_usageescapec GsXtr5t r5yttdaWntk r4YnXtsDtantat|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!(/opt/alt/python35/lib64/python3.5/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]srcGsdS)z9Dummy function, assigned to log when logging is disabled.Nr!)r r!r!r"rasrcCs&datrtjdatadS)zClose the log file.rN)rrcloser#rr!r!r!r"closeloges  r(c Cs|dkrtj}t|dr0|j}nd}t|trN|j}d|krdd|d<|ddkrlt|d\}}|dkrt||S|d krt |d }t r|t krt d |j |j |}nd }d |kr+|r|d}||d }n4tjddr_|rN|d}|tjd}||d rCZhttprIZnextpartZlastpartZpartdict terminatorbytesdataheadersrDlineslinekeyZparamsrJr!r!r"rs|                    ccsx|dddkr|dd}|jd}xR|dkr|jdd||jdd|dr|jd|d}q;W|dkrt|}|d|}|jV||d}qWdS)Nr1;r"z\"rF)findcountlenstrip)sendfr!r!r" _parseparam-s;   rdcCstd|}|j}i}x|D]}|jd}|dkr)|d|jj}||ddj}t|dkr|d|d kodknr|dd }|jdd jd d}|||rr4r)errorsrUrwrq outerboundary bytes_readlimitrrzr{rJru _binary_filery innerboundaryr7r9r8lengthrvrxdoneread_urlencoded read_multi read_single)rnr>rWrr?r@rArr)rmethodrEZcdisprCrBZclenr!r!r"ros+                                               zFieldStorage.__init__c Cs*y|jjWntk r%YnXdS)N)rxr'AttributeError)rnr!r!r"__del__3s zFieldStorage.__del__cCs|S)Nr!)rnr!r!r" __enter__9szFieldStorage.__enter__cGs|jjdS)N)rxr')rnr&r!r!r"__exit__<szFieldStorage.__exit__cCsd|j|j|jfS)z"Return a printable representation.zFieldStorage(%r, %r, %r))rJrurm)rnr!r!r"rp?szFieldStorage.__repr__cCst|jS)N)iterkeys)rnr!r!r"__iter__DszFieldStorage.__iter__cCsx|dkrt||jrS|jjd|jj}|jjdn!|jdk rn|j}nd}|S)Nrmr)rrxseekr:rv)rnrJrmr!r!r" __getattr__Gs    zFieldStorage.__getattr__cCs|jdkrtdg}x-|jD]"}|j|kr+|j|q+W|sct|t|dkr}|dS|SdS)zDictionary style indexing.Nz not indexabler1r)rvrrJrRKeyErrorr_)rnrZfounditemr!r!r" __getitem__Ts  zFieldStorage.__getitem__cCsH||kr@||}t|tr6dd|DS|jSn|SdS)z8Dictionary style get() method, including 'value' lookup.cSsg|]}|jqSr!)rm).0xr!r!r" gs z)FieldStorage.getvalue..N)r5rvrm)rnrZdefaultrmr!r!r"getvaluebs    zFieldStorage.getvaluecCsB||kr:||}t|tr0|djS|jSn|SdS)z! Return the first value received.rN)r5rvrm)rnrZrrmr!r!r"getfirstms     zFieldStorage.getfirstcCsK||krC||}t|tr6dd|DS|jgSngSdS)z Return list of received values.cSsg|]}|jqSr!)rm)rrr!r!r"r}s z(FieldStorage.getlist..N)r5rvrm)rnrZrmr!r!r"getlistxs    zFieldStorage.getlistcCs;|jdkrtdttdd|jDS)zDictionary style keys() method.Nz not indexablecss|]}|jVqdS)N)rJ)rrr!r!r" sz$FieldStorage.keys..)rvrset)rnr!r!r"rs zFieldStorage.keyscs;|jdkrtdtfdd|jDS)z%Dictionary style __contains__ method.Nz not indexablec3s|]}|jkVqdS)N)rJ)rr)rZr!r"rsz,FieldStorage.__contains__..)rvrany)rnrZr!)rZr" __contains__s zFieldStorage.__contains__cCst|jS)z Dictionary style len(x) support.)r_r)rnr!r!r"__len__szFieldStorage.__len__cCs(|jdkrtdt|jS)NzCannot be converted to bool.)rvrbool)rnr!r!r"__bool__s zFieldStorage.__bool__cCs|jj|j}t|tsFtd|jt|jf|j|j |j }|j rx|d|j 7}g|_ t jj||j|jd|j d|j }x-|D]%\}}|j jt||qW|jdS)z+Internal: read data in query string format.z%s should return bytes, got %sr0r)rN)r>r:rr5rUr9rwrqr;r)rrrvr=r r r@rArRr skip_lines)rnrEqueryrZrmr!r!r"rs   zFieldStorage.read_urlencodedc Cs~|j}t|s(td|fg|_|jrtjj|j|j|j d|j d|j }x-|D]%\}}|jj t ||qtW|jp|j}|jj} t| tstd|jt| jf|jt| 7_xG| jd|jkrM| rM|jj} |jt| 7_qWxt} d} x*|jj} | | 7} | jscPqcW| sP|jt| 7_| j| j|j |j | j} d| kr| d=||j| |||||j|j|j |j }|j|j7_|jj ||jsk|j|jkofdknrQPqQW|j d S) z/Internal: read a part that is itself multipart.z&Invalid boundary in multipart form: %rr)rz%s should return bytes, got %ss--rHzcontent-lengthrN)!rrMr9rvrr=r r r@rAr)rrRr FieldStorageClass __class__r>rOr5rUrwrqrr_r`rZfeedr;r'rrrr)rnr?r@rAZibrrZrmklassZ first_lineparserZhdr_textrVrWpartr!r!r"rsV          +zFieldStorage.read_multicCsD|jdkr&|j|jn |j|jjddS)zInternal: read an atomic part.rN)r read_binaryr read_linesrxr)rnr!r!r"rs    zFieldStorage.read_singleicCs|j|_|j}|dkrx|dkr|jjt||j}t|tst d|jt |j f|j t |7_ |sd|_P|jj||t |}q'WdS)zInternal: read binary data.rz%s should return bytes, got %sr1NrK) make_filerxrr>r:minbufsizer5rUr9rwrqrr_rr%)rnZtodorVr!r!r"rs   zFieldStorage.read_binarycCsV|jrt|_|_nt|_|_|jrH|jn |jdS)z0Internal: read lines until EOF or outerboundary.N)rrrx_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eof)rnr!r!r"rs    zFieldStorage.read_linescCs|jdk re|jjt|dkre|j|_|jj}|jj|d|_|jr|jj|n"|jj|j|j |j dS)z line is always bytes, not stringNi) rtellr_rrxrr%rr;r)r)rnrYrVr!r!r"Z__writes  zFieldStorage.__writecCsOxH|jjd}|jt|7_|s:d|_P|j|qWdS)zInternal: read lines until EOF.r1NirK)r>rOrr_r_FieldStorage__write)rnrYr!r!r"rs zFieldStorage.read_lines_to_eofc Csd|j}|d}d}d}d}xh||jkr<P|jjd }|jt|7_|t|7}|sd|_P|dkr||}d}|jdr|r|j}||krP||krd|_P|}|j drd}|d d}d}nh|j d rEd }|d d}d}n:|j drsd}|d d}d }n d}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--rHTrr1rs s NrFs FirKrLrKrK) rrr>rOrr_rrPrQendswithr) rn next_boundary last_boundaryZdelimlast_line_lfendZ_readrY strippedlineZodelimr!r!r"r!sP            z(FieldStorage.read_lines_to_outerboundarycCs|j s|jrdSd|j}|d}d}x|jjd}|jt|7_|snd|_P|jdr|r|j}||krP||krd|_P|jd}q7WdS) z5Internal: skip lines until outer boundary if defined.Ns--Tr1rs irK)rrr>rOrr_rr`)rnrrrrYrr!r!r"rRs&       zFieldStorage.skip_linescCs6|jrtjdStjdd|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)newliner$N)rtempfileZ TemporaryFiler))rnr!r!r"rhs   zFieldStorage.make_filei )!rqrrrsrtosr?rorrrrprrrrrrrrrrrrrrrrrrrrrrr!r!r!r"r js< *               6    1 cCstdttjt_ybt}ttt|t|t dd}|dd}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/htmlcSstddS)Nz,testing print_exception() -- italics?)execr!r!r!r"rcsztest..fcSs |dS)Nr!)rcr!r!r"gsztest..gz9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

2N) printr2stdoutstderrr rrrrrrr8)r?formrcrr!r!r"tests4            rcCs|dkr!tj\}}}ddl}ttd|j|||j||}tdtjdj|ddtj|df~dS)Nrz+

Traceback (most recent call last):

z
%s%s
rr1rKrK) r2exc_info tracebackr format_tbformat_exception_onlyhtmlrrS)rwrmtbrrrvr!r!r"rs   cCs|t|j}ttdtdx7|D]/}tdtj|dtj||q4WtdtdS)z#Dump the shell environment as HTML.z

Shell Environment:

z
z
z
z
N)sortedrrrr)r?rrZr!r!r"rs   - cCst|j}ttd|s3tdtdx}|D]u}tdtj|ddd||}tdtjtt|d td tjt|qDWtd td S) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.z

z
:rb zzz
z
N)rrrrrreprrw)rrrZrmr!r!r"rs    ! '! cCsttdytj}WnAtk rd}z!tdtjt|WYdd}~XnXttj|tdS)z#Dump the current directory as HTML.z#

Current Working Directory:

zOSError:N)rrgetcwdrrrstr)pwdmsgr!r!r"rs /cCs0ttdtttjtdS)Nz

Command Line Arguments:

)rr2r<r!r!r!r"rs   cCstddS)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'cCsetdtdd|jdd}|jdd}|jdd }|ra|jd d }|S) zDeprecated API.z1cgi.escape is deprecated, use html.escape instead stacklevelrFr0z&z>r\z")rrGri)raZquoter!r!r"rs cCs:ddl}t|tr$d}nd}|j||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rer5rUmatch)rarZ _vb_patternr!r!r"rM(s   rM__main__)1rt __version__iorrr collectionsrr2rZ urllib.parser=Z email.parserrZ email.messagerwarningsrrrr__all__rrr#rrr(rr8r?r r r rrdrr r rrrrrrrrrMrqr!r!r!r"s\            #   E d "'   /