\dtdZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlZddlZddlZddlZgdZejed d adad Zd ZdZdZeadade jdddfdZ d$dZ!dZ"dZ#GddZ$GddZ%e jfdZ&d%dZ'e jfdZ(dZ)dZ*d Z+d!Z,d"Z-ed#kr e&dSdS)&aSupport module for CGI (Common Gateway Interface) scripts. This module defines a number of utilities for use by CGI scripts written in Python. The global variable maxlen can be set to an integer indicating the maximum size of a POST request. POST requests larger than this size will result in a ValueError being raised during parsing. The default value of this variable is 0, meaning the request size is unlimited. z2.6)StringIOBytesIO TextIOWrapper)MappingN) FeedParser)Message) MiniFieldStorage FieldStorageparseparse_multipart parse_headertestprint_exception print_environ print_formprint_directoryprint_argumentsprint_environ_usage) )removectjdtdtr0ts) t tddan#t $rYnwxYwtstantat|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). z7cgi.log() is deprecated as of 3.10. Use logging instead) stacklevelalocale)encodingN) warningswarnDeprecationWarninglogfilelogfpopenOSErrornologlogdologallargss ..\python\lib\cgi.pyinitlogr,As0 MK$4444u #999EE    D  MMMMsA AAcFt||zdzdS)z=Write a log message to the log file. See initlog() for docs. N)r#write)fmtargss r+r(r(fs" KKD4     cdS)z9Dummy function, assigned to log when logging is disabled.Nr)s r+r&r&jsDr2c\datrtdatadS)zClose the log file.rN)r"r#closer,r'r4r2r+closelogr7ns,G   CCCr2&c:| tj}t|dr|j}nd}t |t r|j}d|vrd|d<|ddkrt|d\}}|dkrt||| S|d kr_t|d }tr|tkrtd | | |} nd } d|vr| r| dz} | |dz} n0tjddr| r| dz} | tjdz} | |d<n;d|vr |d} n.tjddrtjd} nd } | |d<tj| ||||S)aParse a query in the environment or from a file (default stdin) Arguments, all optional: fp : file pointer; default: sys.stdin.buffer 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. separator: str. The symbol to use for separating the query arguments. Defaults to &. Nrzlatin-1REQUEST_METHODGETPOST CONTENT_TYPEzmultipart/form-data) separator!application/x-www-form-urlencodedCONTENT_LENGTHMaximum content length exceededr QUERY_STRINGr8)rr>)sysstdinhasattrr isinstancerbufferr r intmaxlen ValueErrorreaddecodeargvurllibr parse_qs) fpenvironkeep_blank_valuesstrict_parsingr>rctypepdictclengthqss r+r r s0 z Yr*;"m$$ Y w & &$) ! F**#GN$;<< u ) ) )"2u BBB B 9 9 9'"2344G D'F** !BCCC!!((22BBB W $ $ S2gn--BB Xabb\ " S2chqk!B"$ 7 " " ^ $ 8ABB< !BBB"$ < %6*2i ! I IIr2utf-8replacec.|dd}d|}t}|| |d|d<n#t$rYnwxYwt ||||ddi|fd DS) aParse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header encoding, errors: request encoding and error handler, passed to FieldStorage Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings. boundaryasciiz multipart/form-data; boundary={}zCONTENT-LENGTHzContent-Lengthr:r<)headersrerrorsrRr>c<i|]}||Sr4)getlist).0kfss r+ z#parse_multipart..s% ) ) )Arzz!}} ) ) )r2)rMformatrset_typeKeyErrorr ) rQrVrr_r>r\rUr^rds @r+r r sZ ''00H . 5 5h ? ?EiiG U $)*:$; !!      b'HV!6*i A A AB ) ) ) )b ) ) ))s A"" A/.A/c#K|dddkr|dd}|d}|dkr|dd||dd|z dzrQ|d|dz}|dkr2|dd||dd|z dzQ|dkrt|}|d|}|V||d}|dddkdSdS)NrC;r"\"r)findcountlenstrip)sendfs r+ _parseparamrts BQB%3,, abbEffSkkAgg17733//!''%C2H2HHAMg&&cAg&&CAgg17733//!''%C2H2HHAMg 77a&&C dsdGggii cddG BQB%3,,,,,,r2ctd|z}|}i}|D]}|d}|dkr|d|}||dzd}t |dkrP|d|dcxkrdkr7nn4|dd}|d d d d}|||<||fS) zfParse a Content-type like header. Return the main content-type and a dictionary of options. rj=rNrCrrkz\\\rl)rt__next__rmrplowerrorZ)linepartskeyrVpinamevalues r+r r s d # #E ..  C E    FF3KK 66RaR5;;==&&((DacddGMMOOE5zzQ58uRy#?#?#?#?C#?#?#?#?#?ad  fd33;;E3GGE$K :r2c>eZdZdZdZdZdZdZiZdZ iZ iZ dZ dZ dS)r z=Like FieldStorage, for use when no file uploads are possible.Nc"||_||_dS)z&Constructor from field name and value.Nrrselfrrs r+__init__zMiniFieldStorage.__init__s  r2c(d|jd|jdS)z Return printable representation.zMiniFieldStorage(, )rrs r+__repr__zMiniFieldStorage.__repr__s-1YYY CCr2)__name__ __module__ __qualname____doc__filenamelisttypefile type_options dispositiondisposition_optionsr^rrr4r2r+r r shGGH D D DLKG DDDDDr2r c eZdZdZdddejdddddddf dZd Zd Zd Z d Z d Z dZ dZ d"dZd"dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd Zd!Z dS)#r 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. Nr2rrYrZr8c d} ||_||_| |_| |_d|vr|d} d|_| dks| dkrrd|vr |d} n)t jddrt jd} nd} | tj d} t| }|d d i}|=i}| d krd |d <d |vr |d |d <d|vr |d|_d |vr |d |d<n+t|ttfstd||_|t jj|_nXt|t(r |j|_n6t+|drt+|dstd||_||_| |_t|t0s$tdt3|jz||_d|_||_di}}d|jvrt=|jd\}}||_||_ d|_!d|vr |d|_!d|_"d|vr |d|_"|j"du|_#d |jvrt=|jd \}}n|js| d krdi}}nd i}}||_||_$d|vr,|d|j|j|_%nd|_%d}d|jvrM tM|jd}n#tN$rYnwxYwtPr|tPkrtOd||_)|j |dkr||_dx|_*|_+d|_,|d kr|-dS|dddkr|.|||dS|/dS)a$Constructor. 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) max_num_fields: int. If set, then __init__ throws a ValueError if there are more than n fields read by parse_qsl(). r;r:NHEADrBrCrsurrogateescapez content-typer?r<r=r@content-lengthz?headers must be mapping or an instance of email.message.MessagerLreadlinezfp must be file pointerz#outerboundary must be bytes, not %srzcontent-dispositionrrz text/plainr\r2rwrA z multipart/)0rSrTmax_num_fieldsr>upper qs_on_postrDrNencodergetpreferredencodingrrGrr TypeErrorr^rErHrQrrFrr_bytesrr outerboundary bytes_readlimitr rrrr _binary_filer innerboundaryrIrKrJlengthrrdoneread_urlencoded read_multi read_single)rrQr^rrRrSrTrrr_rr>methodrXcdisprVrUclens r+rzFieldStorage.__init__Js|^!2,," w & &-.4466F U??f..((^,!"" Xa[6688:KLLBB)>@ ?G*M'((*1.*A'((")."97**,34D,E()w'(:;; 9!8999 :i&DGG M * * iDGGB'' ;GB ,C,C ; 9:::DG   -// <A"=11:;<< <* 2u DL 0 0' 5J(KLLLE5 #(  U??f DI   !*-DM M5 T\ ) )' ^(DEELE55   C6V#3#3'5EE>5E !   !&z!2!9!9$-:>+"G"GD  "%D  t| + + 4<(89::     D$-- !BCCC : $!))DJ $$ DI 7 7 7  " " " " " 3B3Z< ' ' OOG%6 G G G G G        sL L,+L,c\ |jdS#t$rYdSwxYwN)rr6AttributeErrorrs r+__del__zFieldStorage.__del__sA  IOO         DD s  ++c|Srr4rs r+ __enter__zFieldStorage.__enter__s r2c8|jdSr)rr6)rr1s r+__exit__zFieldStorage.__exit__s r2c8d|jd|jd|jdS)z"Return a printable representation.z FieldStorage(rr)rrrrs r+rzFieldStorage.__repr__s) 4===$***6 6r2cDt|Sr)iterkeysrs r+__iter__zFieldStorage.__iter__sDIIKK   r2c|dkrt||jrN|jd|j}|jdn|j|j}nd}|S)Nrr)rrseekrLrrs r+ __getattr__zFieldStorage.__getattr__sz 7?? && & 9  INN1   INN$$E INN1     Y "IEEE r2c|jtdg}|jD]"}|j|kr||#|st |t |dkr|dS|S)zDictionary style indexing.N not indexablerCr)rrrappendrhro)rr}founditems r+ __getitem__zFieldStorage.__getitem__s~ 9 O,, ,I 4 4DyCd!3!3!3 3--  u::??8OLr2cn||vr0||}t|tr d|DS|jS|S)z8Dictionary style get() method, including 'value' lookup.cg|] }|j Sr4rrbxs r+ z)FieldStorage.getvalue..#///A///r2rGrrrr}defaultrs r+getvaluezFieldStorage.getvaluesG $;;IE%&& #//////{"Nr2cp||vr1||}t|tr |djS|jS|S)z! Return the first value received.rrrs r+getfirstzFieldStorage.getfirst)s? $;;IE%&& #Qx~%{"Nr2cp||vr1||}t|tr d|DS|jgSgS)z Return list of received values.cg|] }|j Sr4rrs r+rz(FieldStorage.getlist..9rr2r)rr}rs r+razFieldStorage.getlist4sI $;;IE%&& %////// }$Ir2c|jtdttd|jDS)zDictionary style keys() method.Nrc3$K|] }|jV dSrr)rbrs r+ z$FieldStorage.keys..Cs$88d 888888r2)rrsetrs r+rzFieldStorage.keys?s? 9 O,, ,C88di88888999r2cp|jtdtfd|jDS)z%Dictionary style __contains__ method.Nrc3.K|]}|jkVdSrr)rbrr}s r+rz,FieldStorage.__contains__..Is*::49#::::::r2)rrany)rr}s `r+ __contains__zFieldStorage.__contains__Es> 9 O,, ,:::: ::::::r2cDt|S)z Dictionary style len(x) support.)rorrs r+__len__zFieldStorage.__len__Ks499;;r2cV|jtdt|jS)NzCannot be converted to bool.)rrboolrs r+__bool__zFieldStorage.__bool__Os' 9 :;; ;DIr2c |j|j}t|ts+t |jdt |j||j |j }|j r |d|j zz }tj ||j|j|j |j |j|j}d|D|_|dS)z+Internal: read data in query string format. should return bytes, got r8rr_rr>c4g|]\}}t||Sr4r rbr}rs r+rz0FieldStorage.read_urlencoded..as'JJJjc5%c511JJJr2N)rQrLrrGrrKrrrMrr_rrOr parse_qslrSrTrr>r skip_lines)rrXquerys r+rzFieldStorage.read_urlencodedTs W\\$+ & &"e$$ = $b):):<== = YYt}dk 2 2 ? ( #' 'B && &(;]4;.$.'JJKJEJJJ  r2c |j}t|std|g|_|jrmt j|j|j|j |j |j |j |j }|jd|D|jp|j}|j}t'|t(s+t|jdt+|j|xjt1|z c_|d|jzkrZ|rX|j}|xjt1|z c_|d|jzkr|X|j }||t1|jz} t5} d} |j} | | z } | sn4| sn9|xjt1| z c_| | |j |j | } d | vr| d =|jdn|j|jz } ||j| ||||| |j |j ||j }|8|d z}|jr|t1|jz}|d krtd |xj|jz c_|j||j s|j|j!cxkrd krnnn|"dS) z/Internal: read a part that is itself multipart.z$Invalid boundary in multipart form: rc3<K|]\}}t||VdSrrrs r+rz*FieldStorage.read_multi..qs1RRjc5-c599RRRRRRr2r--NTr2rrCrzMax number of fields exceeded)#rvalid_boundaryrKrrrOr rrSrTrr_rr>extendFieldStorageClass __class__rQrrGrrrrrorprfeedrMr6rrrrr)rrRrSrTibrklass first_linerparserhdr_textdatar^rparts r+rzFieldStorage.read_multifs  b!! O*MNN N ? SL**!79Lt{#2dn+NNE I  RRERRR R R R&8$.W%%'' *e,, E $j)9)9)B)BDEE E 3z??*!!ed.@&@AAB))++J OOs: .OO!!ed.@&@AAB ,  % c$)nn ,N# \\FH w''))D zz||     OOs8}} ,OO KK t{CC D D DllnnG 7**,- J.DDZ$/1 5'2w8I' ^T^UUD)!#95"c$)nn4N!A%%$%DEEE OOt .OO I  T " " "y DOt{>>>>Q>>>>>G# H r2c|jdkr)||n||jddS)zInternal: read an atomic part.rN)r read_binaryr read_linesrrrs r+rzFieldStorage.read_singles^ ;!         OO     OO    qr2i c||_|j}|dkr|dkr|jt ||j}t|ts+t|jdt|j |xj t|z c_ |s d|_dS|j||t|z }|dkdSdSdS)zInternal: read binary data.rrrwN) make_filerrrQrLminbufsizerGrrKrrrrorr/)rtodors r+rzFieldStorage.read_binarysNN$$ { 199((w||Cdl$;$;<<!$..G$(,d1D1D&FGGG3t99, "DIE %%%c$ii'(((( 9(r2c|jrtx|_|_nt x|_|_|jr|dS|dS)z0Internal: read lines until EOF or outerboundary.N)rrr_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eofrs r+rzFieldStorage.read_linessn   1&-ii /DI &.jj 0DI   %  , , . . . . .  " " $ $ $ $ $r2c|j|jt|zdkrS||_|j}|j|d|_|jr|j|dS|j||j |j dS)z line is always bytes, not stringNi) rtellrorrrr/rrMrr_)rr{rs r+__writezFieldStorage.__writes ; "{!!CII-44 NN,, {++-- %%%"   E IOOD ! ! ! ! ! IOODKK t{CC D D D D Dr2c |jd}|xjt|z c_|s d|_dS||X)zInternal: read lines until EOF.rCrwN)rQrrror_FieldStorage__write)rr{s r+r zFieldStorage.read_lines_to_eofs] 7##E**D OOs4yy (OO   LL     r2cd|jz}|dz}d}d}d} |jd|jcxkr|krnndS|jd}|xjt |z c_|t |z }|s d|_dS|d kr||z}d}|dr-|r+|}||krdS||kr d|_dS|}| d rd }|dd }d}nL| d rd }|dd}d}n(| d rd }|dd}d }nd}d }| ||zM)zInternal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons. rr2TrrCNrrw s  F) rrrQrrror startswithrstripendswithr) r next_boundary last_boundarydelimlast_line_lfend_readr{ strippedlineodelims r+rz(FieldStorage.read_lines_to_outerboundarys  22 %- & (z%!tz*B*B*B*BU*B*B*B*B*B7##E**D OOs4yy (OO SYY E  ~~t|u%% / #{{}} =00E=00 !DIEF}}W%% (CRCy"&u%% (CRCy"&u%% (CRCy"'"' LL$ ' ' 'M& (r2cz|jr|jrdSd|jz}|dz}d} |jd}|xjt |z c_|s d|_dS|dr-|r+|}||krdS||kr d|_dS|d})z5Internal: skip lines until outer boundary if defined.NrTrrwrCr)rrrQrrrorrp)rrrrr{rs r+rzFieldStorage.skip_liness! TY  F 22 %-  37##E**D OOs4yy (OO  }}U##  #zz|| =00E=00 !DIE"mmE22O 3r2cp|jrtjdStjd|jdS)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.)rnewline)rtempfile TemporaryFilerrs r+rzFieldStorage.make_file3sC0   8)%00 0)$$888 8r2r)!rrrrosrRrrrrrrrrrrrarrrrrrrrrrrrr rrrr4r2r+r r s((RCqgi $ccccJ 666 !!!                 ::: ;;;      CCCJG(((" % % % E E E0(0(0(d333,88888r2r chtdttjt_ t }t t t|t|td}|fd}td|n#tYnxYwtdda t }t t t|t|dS#tYdSxYw)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/htmlc$tddS)Nz,testing print_exception() -- italics?)execr4r2r+rsztest..ffs ? @ @ @ @ @r2c|dSrr4)rss r+gztest..ghs ACCCCCr2z9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

2N) printrDstdoutstderrr rrrrrrrJ)rRformrsr(s r+rrUsO #$$$ GGGCJ~~4g A A A     IJJJ  6777F~~4gsA7B--B?ADD1c |tj\}}}ddl}ttd||||||z}tdt jd|dddt j|dd~dS)Nrz+

Traceback (most recent call last):

z
rrwzz
) rDexc_info tracebackr* format_tbformat_exception_onlyhtmlescapejoin)rrtbrr0rs r+rr|s |,..eR GGG 7888   r5 ) )  * *4 7 7 8D E BGGD"I&&'''' DH     r2c \t|}ttdtd|D]>}tdtj|dtj||?tdtdS)z#Dump the shell environment as HTML.z

Shell Environment:





N)sortedrr*r3r4)rRrr}s r+rrs ',,.. ! !D GGG '((( &MMMKK fdk#&& GCL0I0IJJJJ 'NNN GGGGGr2c Lt|}ttd|stdtd|D]}tdtj|zdzd||}tdtjt t |zd ztd tjt |ztd td S) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.r8r9: )rrzzr:r;N)r<rr*r3r4reprr)r-rr}rs r+rrs $))++  D GGG #$$$ $ "### &MMM11 ft{3'''#-37777S  edk$tE{{"3"3444v=>>> ft{4;;///0000 'NNN GGGGGr2c Tttd tj}ttj|nF#t $r9}tdtjt |Yd}~nd}~wwxYwtdS)z#Dump the current directory as HTML.z#

Current Working Directory:

zOSError:N)r*r#getcwdr3r4r%str)pwdmsgs r+rrs GGG /000 ikk dk# 111 j$+c#hh//000000001 GGGGGsA B/BBcttdtttjtdS)Nz

Command Line Arguments:

)r*rDrNr4r2r+rrs= GGG ,--- GGG #(OOO GGGGGr2c$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)r*r4r2r+rrs# ' '''''r2cjddl}t|trd}nd}|||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rerGrmatch)rqrI _vb_patterns r+rrs= III!U,, + 88K # ##r2__main__)rYrZr8)NNNN).r __version__iorrrcollections.abcrrDr# urllib.parserO email.parserr email.messagerr3rr!r__all__ _deprecatedrr"r#r,r(r&r7r'rJrRr r rtr r r rrrrrrrrr4r2r+rUs  * 0/////////###### ######!!!!!!  " " " Xf----  ###J!!!     2:cCICICICIL****6   0DDDDDDDD2p8p8p8p8p8p8p8p8l%%%%N     *              )))^$$$ zDFFFFFr2