i fe@sRdZdZddlmZmZmZddlmZddlZddl 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/e0d4krNe'ndS)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 Gs[tr8t r8yttdaWq8tk r4Yq8XntsGtantat|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/python34/lib64/python3.4/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)datrtjdantadS)zClose the log file.rN)rrcloser#rr!r!r!r"closeloges   r(c Cs|dkrtj}nt|dr3|j}nd}t|trT|j}nd|krmd|drCZhttprIZnextpartZlastpartZpartdictZ terminatorbytesdataheadersrDlineslinekeyZparamsrJr!r!r"rs|                   ccsx|dddkr|dd}|jd}xR|dkr|jdd||jdd|dr|jd|d}q;W|dkrt|}n|d|}|jV||d}qWdS)Nr1;r"z\"rF)findcountlenstrip)sendfr!r!r" _parseparam-s;  rccCstd|}|j}i}x|D]}|jd}|dkr)|d|jj}||ddj}t|dkr|d|d kodknr|dd }|jdd jd d}n|||| d krNdi}} n d i}} ||_| |_"d| kr| dj|j|_#n d|_#d}d|jkryt$|jd}Wnt%k rYnXt&r|t&krt%dqn||_'|jdkr-|r-||_nd|_(|_)d|_*|d kr_|j+n6|dddkr|j,|||n |j-dS)aConstructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin.buffer (not used when the request method is GET) Can be : 1. a TextIOWrapper object 2. an object whose read() and readline() methods return bytes headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in percent-encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. limit : used internally to read parts of multipart/form-data forms, to exit from the reading loop when reached. It is the difference between the form content-length and the number of bytes already read encoding, errors : the encoding and error handler used to decode the binary stream to strings. Must be the same as the charset defined for the page sending the form (content-type : meta http-equiv or header) r+r*NZHEADr/r1rsurrogateescapez!application/x-www-form-urlencodedz content-typer,r-r.zcontent-lengthz?headers must be mapping or an instance of email.message.Messager:rOzfp must be file pointerz#outerboundary must be bytes, not %srzcontent-dispositionrJrtz text/plainrIrHzMaximum content length exceeded z multipart/rK).r@rAupper qs_on_postr2r<encodelocalegetpreferredencodingrr5rr TypeErrorrVr3r6r>rr4r)errorsrTrvrp outerboundary bytes_readlimitrryrzrJrt _binary_filerx innerboundaryr7r9r8lengthrurwdoneread_urlencoded read_multi read_single)rmr>rVrr?r@rArr)rmethodrEZcdisprCrBZclenr!r!r"rns+                                        zFieldStorage.__init__c Cs*y|jjWntk r%YnXdS)N)rwr'AttributeError)rmr!r!r"__del__3s zFieldStorage.__del__cCsd|j|j|jfS)z"Return a printable representation.zFieldStorage(%r, %r, %r))rJrtrl)rmr!r!r"ro9szFieldStorage.__repr__cCst|jS)N)iterkeys)rmr!r!r"__iter__>szFieldStorage.__iter__cCs{|dkrt|n|jrV|jjd|jj}|jjdn!|jdk rq|j}nd}|S)Nrlr)rrwseekr:ru)rmrJrlr!r!r" __getattr__As   zFieldStorage.__getattr__cCs|jdkrtdng}x0|jD]%}|j|kr.|j|q.q.W|slt|nt|dkr|dS|SdS)zDictionary style indexing.Nz not indexabler1r)rurrJrRKeyErrorr^)rmrYfounditemr!r!r" __getitem__NszFieldStorage.__getitem__cCsH||kr@||}t|tr6dd|DS|jSn|SdS)z8Dictionary style get() method, including 'value' lookup.cSsg|]}|jqSr!)rl).0xr!r!r" as z)FieldStorage.getvalue..N)r5rurl)rmrYdefaultrlr!r!r"getvalue\s    zFieldStorage.getvaluecCsB||kr:||}t|tr0|djS|jSn|SdS)z! Return the first value received.rN)r5rurl)rmrYrrlr!r!r"getfirstgs     zFieldStorage.getfirstcCsK||krC||}t|tr6dd|DS|jgSngSdS)z Return list of received values.cSsg|]}|jqSr!)rl)rrr!r!r"rws z(FieldStorage.getlist..N)r5rurl)rmrYrlr!r!r"getlistrs    zFieldStorage.getlistcCs>|jdkrtdnttdd|jDS)zDictionary style keys() method.Nz not indexablecss|]}|jVqdS)N)rJ)rrr!r!r" sz$FieldStorage.keys..)rurset)rmr!r!r"r}szFieldStorage.keyscs>|jdkrtdntfdd|jDS)z%Dictionary style __contains__ method.Nz not indexablec3s|]}|jkVqdS)N)rJ)rr)rYr!r"rsz,FieldStorage.__contains__..)rurany)rmrYr!)rYr" __contains__szFieldStorage.__contains__cCst|jS)z Dictionary style len(x) support.)r^r)rmr!r!r"__len__szFieldStorage.__len__cCs+|jdkrtdnt|jS)NzCannot be converted to bool.)rurbool)rmr!r!r"__bool__szFieldStorage.__bool__cCs|jj|j}t|tsItd|jt|jfn|j|j |j }|j r~|d|j 7}ng|_ 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:rr5rTr9rvrpr;r)rr~rur=r r r@rArRr skip_lines)rmrEqueryrYrlr!r!r"rs   zFieldStorage.read_urlencodedc Cs|j}t|s+td|fng|_|jrtjj|j|j|j d|j d|j }x0|D]%\}}|jj t ||qwWn|jp|j}|jj} t| tstd|jt| jfn|jt| 7_xG| jd|jkrV| rV|jj} |jt| 7_qWx+t} d} x-|jj} | | 7} | jslPqlqlW| sPn|jt| 7_| j| j|j |j | j} d| kr| d=n||j| |||||j|j|j |j }|j|j7_|jj ||js}|j|jkoxdknrZPqZqZW|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)!rrMr9rur~r=r r r@rAr)rrRr FieldStorageClass __class__r>rOr5rTrvrprr^r_rZfeedr;r'rrrr)rmr?r@rAZibrrYrlklassZ first_lineparserZhdr_textrUrVpartr!r!r"rsV            +zFieldStorage.read_multicCsD|jdkr&|j|jn |j|jjddS)zInternal: read an atomic part.rN)r read_binaryr read_linesrwr)rmr!r!r"rs    zFieldStorage.read_singleicCs|j|_|j}|dkrx|dkr|jjt||j}t|tst d|jt |j fn|j t |7_ |sd|_Pn|jj||t |}q'WndS)zInternal: read binary data.rz%s should return bytes, got %sr1NrK) make_filerwrr>r:minbufsizer5rTr9rvrprr^rr%)rmZtodorUr!r!r"rs   zFieldStorage.read_binarycCsV|jrt|_|_nt|_|_|jrH|jn |jdS)z0Internal: read lines until EOF or outerboundary.N)rrrw_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eof)rmr!r!r"rs    zFieldStorage.read_linescCs|jdk rk|jjt|dkrk|j|_|jj}|jj|d|_qkn|jr|jj|n"|jj|j|j |j dS)z line is always bytes, not stringNi) rtellr^rrwrr%rr;r)r)rmrXrUr!r!r"Z__writes zFieldStorage.__writecCsRxK|jjd}|jt|7_|s=d|_Pn|j|qWdS)zInternal: read lines until EOF.r1NirK)r>rOrr^r_FieldStorage__write)rmrXr!r!r"rs zFieldStorage.read_lines_to_eofc Csd|j}|d}d}d}d}xz||jkr?Pn|jjd }|jt|7_|t|7}|sd|_Pn|dkr||}d}n|jdr|r|j}||krPn||krd|_Pqn|}|j dr)d}|d d}d}nh|j d rWd }|d d}d}n:|j drd}|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) rm next_boundary last_boundaryZdelimlast_line_lfendZ_readrX strippedlineZodelimr!r!r"rsP             z(FieldStorage.read_lines_to_outerboundarycCs|j s|jrdSd|j}|d}d}x|jjd}|jt|7_|sqd|_Pn|jdr|r|j}||krPn||krd|_Pqn|jd}q7WdS) z5Internal: skip lines until outer boundary if defined.Ns--Tr1rs irK)rrr>rOrr^rr_)rmrrrrXrr!r!r"rLs&       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))rmr!r!r"rbs   zFieldStorage.make_filei )rprqrrrsosr?rnrrorrrrrrrrrrrrrrrrrrrrrrr!r!r!r"r js8 *             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"rbsztest..fcSs |dS)Nr!)rbr!r!r"gsztest..gz9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

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

Traceback (most recent call last):

z
%s%s
rr1rKrK) r2exc_info tracebackr format_tbformat_exception_onlyhtmlrrS)rvrltbrrrur!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?rrYr!r!r"rs   - cCst|j}ttd|s6tdntdx}|D]u}tdtj|ddd||}tdtjtt|d td tjt|qGWtd td S) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.z

z
:ra zzz
z
N)rrrrrreprrv)rrrYrlr!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'cCshtdtdd|jdd}|jdd}|jdd }|rd|jd d }n|S) zDeprecated API.z1cgi.escape is deprecated, use html.escape instead stacklevelrFr0z&z>r[z")rrGrh)r`Zquoter!r!r"rs cCs:ddl}t|tr$d}nd}|j||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rer5rTmatch)r`rZ _vb_patternr!r!r"rM"s   rM__main__)1rs __version__iorrr collectionsrr2rZ urllib.parser=Z email.parserrZ email.messagerwarningsrrrr__all__rrr#rrr(rr8r?r r r rrcrr r rrrrrrrrrMrpr!r!r!r"s\            #   E d '   /