o ?Og?@s`dZdZddlmZmZmZddlmZddlZddl Z ddl Z ddl m Z ddlmZddlZddlZddlZddlZgdZd adad d Zd d ZddZddZeadade jdddfddZd2ddZddZ ddZ!GdddZ"Gdd d Z#e jfd!d"Z$d3d#d$Z%e jfd%d&Z&d'd(Z'd)d*Z(d+d,Z)d-d.Z*d/d0Z+e,d1kre$dSdS)4zSupport 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) MiniFieldStorage FieldStorageparseparse_multipart parse_headertestprint_exception print_environ print_formprint_directoryprint_argumentsprint_environ_usagecGsXtjdtddtrtsz ttdddaWn tyYnwts$tant at|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) warningswarnDeprecationWarninglogfilelogfpopenOSErrornologlogdologZallargsr%*/opt/alt/python310/lib64/python3.10/cgi.pyinitlog9s  r'cGst||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&r!bsr!cCsdatr tdatadS)zClose the log file.rN)rrcloser'r"r%r%r%r&closelogfs r,&c CsV|durtj}t|dr|j}nd}t|tr|j}d|vr"d|d<|ddkrt|d\}}|dkr;t|||d S|d krXt |d }t rO|t krOt d | | |} nd } d|vrk| rd| d} | |d} ntjddr| rx| d} | tjd} | |d<nd|vr|d} ntjddrtjd} nd } | |d<tjj| ||||dS)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_STRINGr-)rr2)sysstdinhasattrr isinstancerbufferr r intmaxlen ValueErrorreaddecodeargvurllibr Zparse_qs) fpenvironkeep_blank_valuesstrict_parsingr2rctypepdictZclengthqsr%r%r&r ysF           r utf-8replacecsv|dd}d|}t}||z|d|d<Wn ty%Ynwt||||ddi|dfd d 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.r0)headersrerrorsrEr2csi|]}||qSr%)getlist).0kZfsr%r& sz#parse_multipart..)rAformatrZset_typeKeyErrorr )rDrIrrPr2rMrHrOr%rTr&r s    r ccs|dddkrg|dd}|d}|dkrD|dd||dd|drD|d|d}|dkrD|dd||dd|ds(|dkrLt|}|d|}|V||d}|dddks dSdS)Nr7;r"\"r)findcountlenstrip)sendfr%r%r& _parseparams  ((   rbcCstd|}|}i}|D]I}|d}|dkrW|d|}||dd}t|dkrS|d|dkrAdkrSnn|dd}|d d d d}|||<q||fS) zfParse a Content-type like header. Return the main content-type and a dictionary of options. rX=rNr7rrYz\\\rZ)rb__next__r[r^lowerr]rL)linepartskeyrIpinamevaluer%r%r&r s  , r c@s@eZdZdZdZdZdZdZiZdZ iZ iZ ddZ ddZ dS)rz=Like FieldStorage, for use when no file uploads are possible.NcCs||_||_dS)z&Constructor from field name and value.Nrmrnselfrmrnr%r%r&__init__ s zMiniFieldStorage.__init__cCsd|j|jfS)z Return printable representation.zMiniFieldStorage(%r, %r)rorqr%r%r&__repr__szMiniFieldStorage.__repr__)__name__ __module__ __qualname____doc__filenamelisttypefile type_options dispositiondisposition_optionsrOrrrtr%r%r%r&rs rc @seZdZdZdddejdddddddf dd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ d;ddZd;ddZddZddZd d!Zd"d#Zd$d%Zd&d'ZdZd(d)Zd*d+Zd,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6Zd7d8Zd9d:Z dS)lengthrzr|doneread_urlencoded read_multi read_single)rqrDrOrrErFrGrrrPrr2methodrJZcdisprIrHZclenr%r%r&rrBs/                         zFieldStorage.__init__cCs&z|jWdStyYdSwN)r|r+AttributeErrorrsr%r%r&__del__s  zFieldStorage.__del__cCs|Srr%rsr%r%r& __enter__szFieldStorage.__enter__cGs|jdSr)r|r+)rqr*r%r%r&__exit__szFieldStorage.__exit__cCsd|j|j|jfS)z"Return a printable representation.zFieldStorage(%r, %r, %r))rmryrnrsr%r%r&rts zFieldStorage.__repr__cC t|Sr)iterkeysrsr%r%r&__iter__ zFieldStorage.__iter__cCsX|dkrt||jr|jd|j}|jd|S|jdur(|j}|Sd}|S)Nrnr)rr|seekr@rzrpr%r%r& __getattr__s    zFieldStorage.__getattr__cCsZ|jdur tdg}|jD] }|j|kr||q|s!t|t|dkr+|dS|S)zDictionary style indexing.N not indexabler7r)rzrrmappendrWr])rqrjfounditemr%r%r& __getitem__s   zFieldStorage.__getitem__cCs2||vr||}t|trdd|DS|jS|S)z8Dictionary style get() method, including 'value' lookup.cSg|]}|jqSr%rnrRxr%r%r& z)FieldStorage.getvalue..r;rzrnrqrjdefaultrnr%r%r&getvalues  zFieldStorage.getvaluecCs.||vr||}t|tr|djS|jS|S)z! Return the first value received.rrrr%r%r&getfirst!s   zFieldStorage.getfirstcCs4||vr||}t|trdd|DS|jgSgS)z Return list of received values.cSrr%rrr%r%r&r1rz(FieldStorage.getlist..r)rqrjrnr%r%r&rQ,s  zFieldStorage.getlistcCs*|jdur tdttdd|jDS)zDictionary style keys() method.Nrcss|]}|jVqdSrrmrRrr%r%r& ;sz$FieldStorage.keys..)rzrsetrsr%r%r&r7 zFieldStorage.keyscs*|jdur tdtfdd|jDS)z%Dictionary style __contains__ method.Nrc3s|]}|jkVqdSrrrrjr%r&rAsz,FieldStorage.__contains__..)rzrany)rqrjr%rr& __contains__=rzFieldStorage.__contains__cCr)z Dictionary style len(x) support.)r]rrsr%r%r&__len__C zFieldStorage.__len__cCs|jdur tdt|jS)NzCannot be converted to bool.)rzrboolrsr%r%r&__bool__Gs  zFieldStorage.__bool__c Cs|j|j}t|tstd|jt|jf||j |j }|j r*|d|j 7}t j j||j|j|j |j |j|jd}dd|D|_|dS)z+Internal: read data in query string format.%s should return bytes, got %sr-rrPrr2cSsg|] \}}t||qSr%rrRrjrnr%r%r&rYsz0FieldStorage.read_urlencoded..N)rDr@rr;rr?r{rurArrPrrCr parse_qslrFrGrr2rz skip_lines)rqrJqueryr%r%r&rLs   zFieldStorage.read_urlencodedc CsJ|j}t|std|fg|_|jr3tjj|j|j|j |j |j |j |j d}|jdd|D|jp8|j}|j}t|tsOtd|jt|jf|jt|7_|d|jkr||r||j}|jt|7_|d|jkr||sc|j }|dur|t|j8} t} d } |j} | | 7} | snq| sn||jt| 7_| | |j |j | } d | vr| d =|jdurdn|j|j} ||j| ||||| |j |j ||j }|dur|d 8}|jr|t|j8}|d krtd |j|j7_|j||j s|j|j!krd krnnnq|"dS)z/Internal: read a part that is itself multipart.z&Invalid boundary in multipart form: %rrcss|] \}}t||VqdSrrrr%r%r&risz*FieldStorage.read_multi..r--NTrrr7rzMax number of fields exceeded)#rvalid_boundaryr?rzrrCr rrFrGrrPrr2extendFieldStorageClass __class__rDrr;rr{rurr]r^rZfeedrAr+rrrrr)rqrErFrGZibrklassZ first_linerparserZhdr_textdatarOrpartr%r%r&r^s        ( $zFieldStorage.read_multicCs4|jdkr||n||jddS)zInternal: read an atomic part.rN)r read_binaryr read_linesr|rrsr%r%r&rs  zFieldStorage.read_singlei cCs||_|j}|dkrM|dkrO|jt||j}t|ts+t d|jt |j f|j t |7_ |s;d|_dS|j||t |}|dksdSdSdS)zInternal: read binary data.rrrdN) make_filer|rrDr@minbufsizer;rr?r{rurr]rr))rqZtodorr%r%r&rs$     zFieldStorage.read_binarycCsB|jr t|_|_nt|_|_|jr|dS|dS)z0Internal: read lines until EOF or outerboundary.N)rrr|_FieldStorage__filerrread_lines_to_outerboundaryread_lines_to_eofrsr%r%r&rs   zFieldStorage.read_linescCsx|jdur#|jt|dkr#||_|j}|j|d|_|jr.|j|dS|j||j |j dS)z line is always bytes, not stringNi) rtellr]rr|rr)rrArrP)rqrhrr%r%r&Z__writes    zFieldStorage.__writecCs: |jd}|jt|7_|sd|_dS||q)zInternal: read lines until EOF.r7rdN)rDrrr]r_FieldStorage__write)rqrhr%r%r&rs  zFieldStorage.read_lines_to_eofc Cs@d|j}|d}d}d}d} |jdur"d|jkr!|kr"dS|jd}|jt|7_|t|7}|s>d|_dS|d krH||}d}|drb|rb|}||krYdS||krbd|_dS|}| d rtd }|dd }d}n$| d rd }|dd}d}n| d rd }|dd}d }nd}d }| ||q)zInternal: read lines until outerboundary. Data is read as bytes: boundaries and line ends must be converted to bytes for comparisons. rrTrr7Nrrd s  F) rrrDrrr]r startswithrstripendswithr) rq next_boundary last_boundaryZdelimlast_line_lfendZ_readrh strippedlineZodelimr%r%r&rsT         z(FieldStorage.read_lines_to_outerboundarycCs|jr|jrdSd|j}|d}d} |jd}|jt|7_|s*d|_dS|drD|rD|}||kr;dS||krDd|_dS|d}q)z5Internal: skip lines until outer boundary if defined.NrTrrdr7r)rrrDrrr]rr^)rqrrrrhrr%r%r&rs(    zFieldStorage.skip_linescCs"|jrtdStjd|jddS)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)rtempfileZ TemporaryFilerrsr%r%r&r+s  zFieldStorage.make_filer)!rurvrwrxosrErrrrrrtrrrrrrQrrrrrrrrrrrrrrrrr%r%r%r&r sD) &    E   2 r cCstdttjt_z't}ttt|t|t dd}|fdd}td|Wnt Ytdda zt}ttt|t|Wd St Yd 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&ra^rztest..fcSs |dSrr%)rar%r%r&g`s ztest..gz9

What follows is a test, not an actual exception:

z*

Second try with a small maxlen...

2N) printr8stdoutstderrr rrrrrrr>)rEformrarr%r%r&r Ms4   r c Csx|dur t\}}}ddl}ttd||||||}tdtd|ddt|df~dS)Nrz+

Traceback (most recent call last):

z
%s%s
rrd) r8exc_info tracebackr format_tbformat_exception_onlyhtmlescapejoin)r{rntbrrrzr%r%r&rts   rc Cs\t|}ttdtd|D]}tdt|dt||qtdtdS)z#Dump the shell environment as HTML.z

Shell Environment:





N)sortedrrrr)rErrjr%r%r&rs   rcCst|}ttd|stdtd|D]-}tdt|ddd||}tdttt|d td tt|qtd td S) z$Dump the contents of a form as HTML.z

Form Contents:

z

No form fields.rr: )r`zzrrN)rrrrrreprr{)rrrjrnr%r%r&rs  rc Cslttdzt}Wnty)}ztdtt|WYd}~n d}~wwtt|tdS)z#Dump the current directory as HTML.z#

Current Working Directory:

zOSError:N)rrgetcwdr rrstr)pwdmsgr%r%r&rs   rcCs(ttdtttjtdS)Nz

Command Line Arguments:

)rr8rBr%r%r%r&rs   rcCs 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&rrrcCs(ddl}t|tr d}nd}|||S)Nrs^[ -~]{0,200}[!-~]$z^[ -~]{0,200}[!-~]$)rer;rmatch)r_rZ _vb_patternr%r%r&rs   r__main__)rKrLr-)NNNN)-rx __version__iorrrZcollections.abcrr8rZ urllib.parserCZ email.parserrZ email.messagerrrrr__all__rrr'r#r!r,r"r>rEr r rbr rr r rrrrrrrrur%r%r%r&sZ    %  F : '  /