gdZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlZddlZddlZddlZgdZej*ed d adad Zd ZdZdZeadade j>dddfdZ d"dZ!dZ"dZ#GddZ$GddZ%e j>fdZ&d#dZ'e j>fdZ(dZ)dZ*dZ+dZ,d Z-ed!k(re&yy)$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) )removectjdtdtrts t tddatstantat|y#t $rY'wxYw)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 */opt/alt/python312/lib64/python3.12/cgi.pyinitlogr,AsZ0 MMK$4u #9E M    sA A$#A$c:tj||zdzy)z=Write a log message to the log file. See initlog() for docs. N)r#write)fmtargss r+r(r(fs KKD4 cy)z9Dummy function, assigned to log when logging is disabled.Nr)s r+r&r&jsr2cLdatrtjdatay)zClose the log file.rN)r"r#closer,r'r4r2r+closelogr7nsG   Cr2&c|tj}t|dr |j}nd}t |t r |j }d|vrd|d<|ddk(rt|d\}}|dk(rt||| S|d k(rIt|d }tr|tkDr td |j|j|} nd } d|vr| r| dz} | |dz} n0tjddr| r| dz} | tjdz} | |d<n8d|vr|d} n.tjddrtjd} nd } | |d<tj j#| ||||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 YYr*;;"m$ YY w &$) ! F*#GN$;< u ) )"2u B B 9 9'"234G'F* !BCC!((2BB W $S2gn--B XXab\S2chhqk!B"$ 7 " ^ $ 88AB<!BB"$ << %6*2i ! IIr2c"|djd}dj|}t}|j| |d|d<t ||||ddi|}|D cic]} | |j | c} S#t$rY>wxYwcc} w) 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>)rMformatrset_typeKeyErrorr getlist) rQrVrr]r>rZrUr\fsks r+r r sZ ''0H . 5 5h ?EiG U $)*:$; ! b'HV!6*i AB&( )bArzz!} b ))     *sA=!B = B B c#K|dddk(r|dd}|jd}|dkDro|jdd||jdd|z dzrE|jd|dz}|dkDr+|jdd||jdd|z dzrE|dkr t|}|d|}|j||d}|dddk(ryyw)NrC;r"\"r)findcountlenstrip)sendfs r+ _parseparamros BQ%3, abEffSkAg17733/!''%C2HHAM&&cAg&CAg17733/!''%C2HHAM 7a&C dsGggi cdG BQ%3,sBC 4C  C ctd|z}|j}i}|D]}|jd}|dk\s|d|jj }||dzdj}t |dk\r;|d|dcxk(rdk(r*nn'|dd}|j d d j d d}|||<||fS) zfParse a Content-type like header. Return the main content-type and a dictionary of options. re=rNrCrrfz\\\rg)ro__next__rhrklowerrjreplace)linepartskeyrVpinamevalues r+r r s d #E .. C E  FF3K 6Ra5;;=&&(DacdGMMOE5zQ58uRy#?C#?a  fd3;;E3GE$K :r2c<eZdZdZdZdZdZdZiZdZ iZ iZ dZ dZ y)r z=Like FieldStorage, for use when no file uploads are possible.Nc ||_||_y)z&Constructor from field name and value.Nr|r}selfr|r}s r+__init__zMiniFieldStorage.__init__s  r2c<d|jd|jdS)z Return printable representation.zMiniFieldStorage(, )rrs r+__repr__zMiniFieldStorage.__repr__s-1YY CCr2)__name__ __module__ __qualname____doc__filenamelisttypefile type_options dispositiondisposition_optionsr\rrr4r2r+r r s;GH D D DLKG Dr2r c eZdZdZdddej dddddddf dZd Zd Zd Z d Z d Z dZ dZ d"dZd"dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd Zd!Z y)#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. Nr2rutf-8rvr8c 6d} ||_||_| |_| |_d|vr|dj } d|_| dk(s| dk(rhd|vr|d} n)t jddrt jd} nd} | jtjd} t| }|d d i}|3i}| d k(rd |d <d |vr|d |d <d|vr |d|_d |vr*|d |d<n!t|ttfs td||_| t j"j$|_nLt|t(r|j$|_n*t+|dr t+|ds td||_||_| |_t|t0s!tdt3|j4z||_d|_||_di}}d|j vrt=|j d\}}||_||_ d|_!d|vr |d|_!d|_"d|vr |d|_"|jDdu|_#d |j vrt=|j d \}}n|j6s| d k7rdi}}nd i}}||_||_$d|vr/|dj|j,|j.|_%nd|_%d}d|j vr3 tM|j d}tPr|tPkDr tOd||_)|j: |dk\r||_dx|_*|_+d|_,|d k(r|j[y|dddk(r|j]|||y|j_y#tN$rYwxYw)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-dispositionr|rz text/plainrZr2rrrA z multipart/)0rSrTmax_num_fieldsr>upper qs_on_postrDrNencodergetpreferredencodingrrGrr TypeErrorr\rErHrQrrFrr]bytesrr outerboundary bytes_readlimitr rrr|r _binary_filer innerboundaryrIrKrJlengthrrdoneread_urlencoded read_multi read_single)rrQr\rrRrSrTrrr]rr>methodrXcdisprVrUclens r+rzFieldStorage.__init__Js^!2,," w &-.446F U?f.(^,!"XXa[6668:KLBB)>@ ?G*M'(*1.*A'(")."97*,34D,E()w'(:;!899 :ii&&DG M *iiDGB'GB ,C 9::DG   -/A"=1::;< <* 2u DLL 0' 5J(KLLE5 #(  U?f DI  !*-DM MM5 T\\ )' ^(DELE5   6V#3'5E>5E !  !&z!2!9!9$--:>++"GD "%D  t|| + 4<<(89:$- !BCC :: $!)DJ $$ DI 7 7  " 3BZ< ' OOG%6 G      s#N NNcX |jjy#t$rYywxYwN)rr6AttributeErrorrs r+__del__zFieldStorage.__del__s'  IIOO    s  ))c|Srr4rs r+ __enter__zFieldStorage.__enter__s r2c8|jjyr)rr6)rr1s r+__exit__zFieldStorage.__exit__s r2cVd|jd|jd|jdS)z"Return a printable representation.z FieldStorage(rr)r|rr}rs r+rzFieldStorage.__repr__s! 4==$**6 6r2c4t|jSr)iterkeysrs r+__iter__zFieldStorage.__iter__sDIIK  r2c|dk7r t||jrR|jjd|jj}|jjd|S|j|j}|Sd}|S)Nr}r)rrseekrLrrs r+ __getattr__zFieldStorage.__getattr__sz 7? & & 99 IINN1 IINN$E IINN1   YY "IIE E r2c|j tdg}|jD]#}|j|k(s|j|%|s t |t |dk(r|dS|S)zDictionary style indexing. not indexablerCr)rrr|appendr`rj)rryfounditems r+ __getitem__zFieldStorage.__getitem__sg 99 O, ,IIDyyCd!33-  u:?8OLr2c||vr;||}t|tr|Dcgc]}|jc}S|jS|Scc}w)z8Dictionary style get() method, including 'value' lookup.rGrr})rrydefaultr}xs r+getvaluezFieldStorage.getvaluesI $;IE%&)./A//{{"N 0sAcn||vr0||}t|tr|djS|jS|S)z! Return the first value received.rr)rryrr}s r+getfirstzFieldStorage.getfirst)s9 $;IE%&Qx~~%{{"Nr2c||vr<||}t|tr|Dcgc]}|jc}S|jgSgScc}w)z Return list of received values.r)rryr}rs r+razFieldStorage.getlist4sK $;IE%&)./A// }$I 0sAcz|j tdttd|jDS)zDictionary style keys() method.rc34K|]}|jywrr|).0rs r+ z$FieldStorage.keys..Cs8id is)rrsetrs r+rzFieldStorage.keys?s1 99 O, ,C8dii8899r2cn|j tdtfd|jDS)z%Dictionary style __contains__ method.rc3<K|]}|jk(ywrr)rrrys r+rz,FieldStorage.__contains__..Is: 499# s)rrany)rrys `r+ __contains__zFieldStorage.__contains__Es- 99 O, ,: :::r2c4t|jS)z Dictionary style len(x) support.)rjrrs r+__len__zFieldStorage.__len__Ks499;r2cZ|j tdt|jS)NzCannot be converted to bool.)rrboolrs r+__bool__zFieldStorage.__bool__Os& 99 :; ;DIIr2c |jj|j}t|ts-t |jdt |j|j|j|j}|jr|d|jzz }tjj||j|j |j|j|j"|j$}|Dcgc]\}}t'||c}}|_|j+ycc}}w)z+Internal: read data in query string format. should return bytes, got r8rr]rr>N)rQrLrrGrrKrrrMrr]rrOr parse_qslrSrTrr>r r skip_lines)rrXqueryryr}s r+rzFieldStorage.read_urlencodedTs WW\\$++ &"e$ $b):):<= = YYt}}dkk 2 ?? #' 'B && &&(;(;]]4;;..$..'JEJJEjc5%c51EJ  KsD>c ||j}t|std|g|_|jrt j j|j|j|j|j|j|j|j}|jjd|D|jxs |j }|j"j%}t'|t(s-t|j"dt+|j,|xj.t1|z c_|j3d|jzk7r]|r[|j"j%}|xj.t1|z c_|j3d|jzk7r|r[|j}||t1|jz} t5} d} |j"j%} | | z } | j3sn1| snq|xj.t1| z c_| j7| j9|j|j| j;} d| vr| d=|j<dn|j<|j.z } ||j"| ||||| |j|j||j }|9|d z}|jr|t1|jz}|d kr td |xj.|j.z c_|jj?||j@s"|j.|jBcxk\rd kDrnnn|jEy) z/Internal: read a part that is itself multipart.z$Invalid boundary in multipart form: rc3:K|]\}}t||ywr)r )rryr}s r+rz*FieldStorage.read_multi..qsREjc5-c59Esr--Nr2rrCrzMax number of fields exceeded)#rvalid_boundaryrKrrrOr rrSrTrr]rr>extendFieldStorageClass __class__rQrrGrrrrrjrkrfeedrMr6rrrrr)rrRrSrTibrklass first_linerparserhdr_textdatar\rparts r+rzFieldStorage.read_multifs    b!MN N ??LL**!7!79L9Lt{{#22dnn+NE II  RER R&&8$..WW%%' *e, $j)9)B)BDE E 3z?*!ed.@.@&@A))+J OOs: .O!ed.@.@&@A ,,  % c$))n ,N\FHww'')D zz|   OOs8} ,O KK t{{C DllnG 7*,- JJ.DZZ$//1 '2w8I' ^T^^UD)!#99"c$))n4N!A%$%DEE OOt .O II  T "yyDOOt{{>Q>GH r2c|jdk\r!|j|jn|j|jj dy)zInternal: read an atomic part.rN)r read_binaryr read_linesrrrs r+rzFieldStorage.read_singles> ;;!      OO  OO  qr2i c|j|_|j}|dk\r|dkDr|jj t ||j }t|ts-t|jdt|j|xjt|z c_ |sd|_y|jj||t|z }|dkDryyy)zInternal: read binary data.rrrrN) make_filerrrQrLminbufsizerGrrKrrrrjrr/)rtodors r+rzFieldStorage.read_binarysNN$ {{ 19(ww||Cdll$;<!$.$(,d1D1D&FGG3t9, "DI %c$i'( r2c|jrtx|_|_nt x|_|_|j r|j y|jy)z0Internal: read lines until EOF or outerboundary.N)rrr_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eofrs r+rzFieldStorage.read_linessL   &-i /DI &.j 0DI     , , .  " " $r2c|jz|jjt|zdkDrQ|j|_|jj }|jj |d|_|jr|jj |y|jj |j|j|jy)z line is always bytes, not stringNi) rtellrjrrrr/rrMrr])rrwrs r+__writezFieldStorage.__writes ;; "{{!CI-4 NN, {{++- %"    IIOOD ! IIOODKK t{{C Dr2c |jjd}|xjt|z c_|sd|_y|j |U)zInternal: read lines until EOF.rrN)rQrrrjr_FieldStorage__write)rrws r+rzFieldStorage.read_lines_to_eofsI77##E*D OOs4y (O  LL  r2c~d|jz}|dz}d}d}d} |jd|jcxkr|kry|jjd}|xjt |z c_|t |z }|sd|_y|d k(r||z}d}|jdr%|r#|j}||k(ry||k(rd|_y|}|jd r d }|dd }d}n:|jd r d }|dd}d}n|jd r d }|dd}d }nd}d }|j||z#)zInternal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons. rr2TrrCNrrr s  F) rrrQrrrjr startswithrstripendswithr) r next_boundary last_boundarydelimlast_line_lfend_readrw strippedlineodelims r+rz(FieldStorage.read_lines_to_outerboundarysi  2 22 %- zz%!tzz*BU*B+C77##E*D OOs4y (O SY E ~t|u%/#{{} =0=0 !DIF}}W%CRy"&u%CRy"&u%CRy"'"' LL$ 'Mr2cx|jr |jryd|jz}|dz}d} |jjd}|xjt |z c_|sd|_y|j dr%|r#|j}||k(ry||k(rd|_y|j d})z5Internal: skip lines until outer boundary if defined.NrTrrrrCr)rrrQrrrjr rk)rr r rrwrs r+rzFieldStorage.skip_liness!!TYY  2 22 %- 77##E*D OOs4y (O }}U##zz| =0=0 !DI"mmE2Or2c|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_file3s<0   ))%0 0))$$8 8r2r)!rrrrosrRrrrrrrrrrrrarrrrrrrrrrrrrrrrr4r2r+r r s(RCqgi $cJ 6 !     : ;    CJG(" % E0(d3,8r2r ctdttjt_ t }t t t|t|td}|fd}td|tdda t }t t t|t|y#tYQxYw#tYyxYw)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/htmlctdy)Nz,testing print_exception() -- italics?)execr4r2r+rnztest..ffs ? @r2c|yrr4)rns r+gztest..ghs Cr2z9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

2N) printrDstdoutstderrr rrrrrrrJ)rRformrnrs r+rrUs #$ GCJ~4g A  IJ  67F~4gsAC 4C C C*c P|tj\}}}ddl}ttd|j |||j ||z}tdt jdj|dddt j|dd~y)Nrz+

Traceback (most recent call last):

z
rrrzz
) rDexc_info tracebackr format_tbformat_exception_onlyhtmlescapejoin)rr}tbrr$rs r+rr|s |,,.eR G 78   r5 )  * *4 7 8D  BGGD"I&' DH   r2c t|j}ttdtd|D]9}tdtj|dtj||;tdty)z#Dump the shell environment as HTML.z

Shell Environment:





N)sortedrrr'r()rRrrys r+rrsa ',,. !D G '( &M fdkk#& GCL0IJ 'N Gr2c t|j}ttd|s tdtd|D]}tdtj|zdzd||}tdtjt t |zd ztd tjt |ztd ty ) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.r,r-: )rmzzr.r/N)r0rrr'r(reprr)r!rryr}s r+rrs $))+ D G #$  "# &M ft{{3''#-37S  edkk$tE{"344v=> ft{{4;//0   'N Gr2c 8ttd tj}ttj|ty#t $r<}tdtjt |Yd}~tyd}~wwxYw)z#Dump the current directory as HTML.z#

Current Working Directory:

zOSError:N)rrgetcwdr'r(r%str)pwdmsgs r+rrsk G /0 iik dkk# G 1 j$++c#h/00 G 1sA B(BBcttdtttjty)Nz

Command Line Arguments:

)rrDrNr4r2r+rrs% G ,- G #((O Gr2ctdy)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)rr4r2r+rrs ' 'r2cXddl}t|trd}nd}|j||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rerGrmatch)rlr= _vb_patterns r+rrs* !U, + 88K ##r2__main__)rrvr8)NNNN).r __version__iorrrcollections.abcrrDr urllib.parserO email.parserr email.messagerr'rrr__all__ _deprecatedrr"r#r,r(r&r7r'rJrRr r ror r r rrrrrrrrr4r2r+rIs * 0/# #!  " Xf-  #J!   2::cCIL*6 0DD2p8p8l%N  **     )^$ zFr2