Qf dZddlZddlZddlZddlZddlZddlZ ddlZdZddl m Z ddlm Z gdZejed d ZGd d eZGd deZGddeZGddeZGddeZGddeZdZdZhdZgdZdddZdZej>dgd Z ej>d!gd"Z!d#Z d$Z"dWd%Z#dWd&Z$dXd'Z%erd(Z&Gd)d*Z'erGd+d,e'Z(ejSd,ed-k(rddl*Z*e*jVd./Z,e,j[d0d1d2d34e,j[d5d6d7d84e,j[d9d:d;e.d?e,j[d@dAdBe.dC?e,j[dDdEdFddGHe,j_Z0e0jbZ1e0jse1d;k(reZ1e'e0jde1IZ3ne1d;k(reZ1e(e0jde1IZ3e3jiZ5dJe5vre3jme3joe0jn\Z8Z9Z:Z;Z<e=dKee?e.e;e0jz dPzZ:e3je:e;\Z8ZBeBD]a\ZCZDe eDdQjdRdPdZFe eDdSZGe.eDdZHe=dTjeCe>eFdUe>eGdVeHce3jyy#e $rdZYwxYw)YaAn NNTP client class based on: - RFC 977: Network News Transfer Protocol - RFC 2980: Common NNTP Extensions - RFC 3977: Network News Transfer Protocol (version 2) Example: >>> from nntplib import NNTP >>> s = NNTP('news') >>> resp, count, first, last, name = s.group('comp.lang.python') >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) Group comp.lang.python has 51 articles, range 5770 to 5821 >>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last)) >>> resp = s.quit() >>> Here 'resp' is the server response line. Error responses are turned into exceptions. To post an article from a file: >>> f = open(filename, 'rb') # file containing article, including header >>> resp = s.post(f) >>> For descriptions of all methods, read the comments in the code below. Note that all arguments and return values representing article numbers are strings, not numbers, since they are rarely used for calculations. NTF) decode_header)_GLOBAL_DEFAULT_TIMEOUT)NNTP NNTPErrorNNTPReplyErrorNNTPTemporaryErrorNNTPPermanentErrorNNTPProtocolError NNTPDataErrorr) )removeiceZdZdZdZy)rz%Base class for all nntplib exceptionscrtj|g| |d|_y#t$r d|_YywxYw)NrzNo response given) Exception__init__response IndexError)selfargss ./opt/alt/python312/lib64/python3.12/nntplib.pyrzNNTPError.__init__es;4'$' 0 GDM 0/DM 0s #66N)__name__ __module__ __qualname____doc__rrrrcs /0rrceZdZdZy)rzUnexpected [123]xx replyNrrrrrrrrrls"rrceZdZdZy)rz 4xx errorsNrrrrrrprrceZdZdZy)r z 5xx errorsNrrrrr r tr!rr ceZdZdZy)r z"Response does not begin with [1-5]Nrrrrr r xs,rr ceZdZdZy)r zError in response dataNrrrrr r |s rr wi3> 100101211215220221222224225230231282)subjectfromdatez message-id references:bytes:linesr6r7)byteslines GroupInfo)grouplastfirstflag ArticleInfo)number message_idr9cg}t|D]K\}}t|tr%|j|j |xsd;|j|Mdj |S)zvTakes a unicode string representing a munged header value and decodes it as a (possibly non-ASCII) readable value.ascii)_email_decode_header isinstancer8appenddecodejoin) header_strpartsvencs rrrsZ E&z23 a  LL#.1 2 LLO 3 775>rcg}|D]t}|ddk(r|ddjd\}}}d|z}n|jd\}}}|j}tj||}|j |vt }t |t |kr td|dt ||k7r td|S)zParse a list of string representing the response to LIST OVERVIEW.FMT and return a list of header/metadata names. Raises NNTPDataError if the response is not compliant (cf. RFC 3977, section 8.4).r:Nz$LIST OVERVIEW.FMT response too shortz*LIST OVERVIEW.FMT redefines default fields) partitionlower_OVERVIEW_FMT_ALTERNATIVESgetrH_DEFAULT_OVERVIEW_FMTlenr )r9fmtlinename_suffixdefaultss r_parse_overview_fmtr^s C 7c>"12h005OD!V:D#nnS1OD!Vzz|)--dD9 4%H 3x#h-BCC >CMh&HII Jrctt}g}|D]}i}|jd^}}t|}t |D]|\} } | t|k\r|| } | j d} | |k\rE| sC| dz} | r*| dt| j | k7r td| r| t| dnd} | ||| <~|j||f|S)zZParse the response to an OVER or XOVER command according to the overview format `fmt`. rPz: Nz?OVER/XOVER response doesn't include names of additional headers) rWrVsplitint enumerate startswithrSr rH)r9rXdata_process_func n_defaultsoverviewrYfieldsarticle_numbertokensitoken field_name is_metadatahs r_parse_overviewrps*+JH"&**T"2^,!&)HAuCH}QJ$//4KJ{%U7CF^113q8')FGG*/c!fgT"F3q6N!*" 01+, Orc | |dd}|dd}t|dd}t|dd}t|dd}t|dd}t|dd}t|dd}|dkr|dz }n |d kr|d z }tj||||||S) zParse a pair of (date, time) strings, and return a datetime object. If only the date is given, it is assumed to be date and time concatenated together (e.g. response to the DATE command). NiFidil)rbdatetime)date_strtime_strhoursminutessecondsyearmonthdays r_parse_datetimers BC=CR= ! E(1Q- G(12,G x} D B E hrsm C by        T5#ugw GGrct|tjsd}ndj|}|j}|r|dz}dj||}||fSdj||}||fS)aPFormat a date or datetime object as a pair of (date, time) strings in the format required by the NEWNEWS and NEWGROUPS commands. If a date object is passed, the time is assumed to be midnight (00h00). The returned representation depends on the legacy flag: * if legacy is False (the default): date has the YYYYMMDD format and time the HHMMSS format * if legacy is True: date has the YYMMDD format and time the HHMMSS format. RFC 3977 compliant servers should understand both formats; therefore, legacy is only needed when talking to old servers. 000000z({0.hour:02d}{0.minute:02d}{0.second:02d}rwz{0:02d}{1.month:02d}{1.day:02d}z{0:04d}{1.month:02d}{1.day:02d})rGrxformatr~)dtlegacyrzyrys r_unparse_datetimers| b(++ ,=DDRH A G4;;ArB X 5;;ArB X rcT|tj}|j||S)zWrap a socket in SSL/TLS. Arguments: - sock: Socket to wrap - context: SSL context to use for the encrypted connection Returns: - sock: New, encrypted socket. )server_hostname)ssl_create_stdlib_context wrap_socket)sockcontexthostnames r _encrypt_onrs- ?002G""4"BBrceZdZdZdZeddddefdZdZdZ dZ d Z d Z d Z d ZeZd ZdZd7dZdZd8dZdZd8dZd8dZdZdZdZdddZdddZd8dddZdZdZdZ dZ!ddd Z"d!Z#d"Z$d8d#Z%d$Z&d%Z'd8d&Z(d8ddd'Z)d8ddd(Z*d8ddd)Z+d*Z,ddd+Z-ddd,Z.ddd-Z/d.Z0d/Z1d0Z2d1Z3d2Z4d3Z5d9d4Z6d5Z7e8rd8d6Z9yy):rzutf-8surrogateescapeNFcz||_||_|j||_d|_ |jj d|_|j ||s|r|j|||yy#|jr|jj|jjxYw)a,Initialize an instance. Arguments: - host: hostname to connect to - port: port to connect to (default the standard NNTP port) - user: username to authenticate with - password: password to use with username - readermode: if true, send 'mode reader' command after connecting. - usenetrc: allow loading username and password from ~/.netrc file if not specified explicitly - timeout: timeout (in seconds) used for socket connections readermode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as `group'. If you get unexpected NNTPPermanentErrors, you might need to set readermode. Nrwb) hostport_create_socketrfilemakefile _base_initloginclose)rrruserpassword readermodeusenetrctimeouts rrz NNTP.__init__;s(  ''0    **51DI OOJ 'x 484  yy ! IIOO  s AA77AB:cd|_|j|_d|_|j d|_|rAd|jvr3|j |j sd|_|j d|_d|_y)z~Partial initialization for the NNTP protocol. This instance method is extracted for supporting the test code. rNFREADER) debugging_getrespwelcome_capsgetcapabilitiesreadermode_afterauth_setreadermodetls_on authenticated)rrs rrzNNTP._base_init^s}}   %*! ($**4    !,,! $$&  #rc|SNrrs r __enter__zNNTP.__enter__s rcfd}|r* j|rjyyy#ttf$rY+wxYw#|rjwwxYw)NctdS)Nr)hasattrrsrzNNTP.__exit__..s wtV4r)quitOSErrorEOFError_close)rr is_connecteds` r__exit__z NNTP.__exit__sd4 > "  >KKM" X&   >KKM"s!9A A A  AA(c| |s tdtjd||j|jt j |j|jf|S)Nz0Non-blocking socket (timeout=0) is not supportedznntplib.connect) ValueErrorsysauditrrsocketcreate_connection)rrs rrzNNTP._create_socketsQ  wOP P #T499dii@''DII(>HHrcp|jrtdt|j|jS)zGet the welcome message from the server (this is read and squirreled away by __init__()). If the response code is 200, posting is allowed; if it 201, posting is not allowed.z *welcome*)rprintreprrrs r getwelcomezNNTP.getwelcomes' >>5d4<<.@A||rcn|jwd|_d|_ |j\}}||_d|vr!t t t |d|_d|vrdj|d|_|jS|jS#ttf$ri|_Y|jSwxYw)zGet the server capabilities, as read by __init__(). If the CAPABILITIES command is not supported, an empty dict is returned.NrQVERSIONIMPLEMENTATION ) r nntp_versionnntp_implementation capabilitiesmaxmaprbrJr r)rrespcapss rrzNNTP.getcapabilitiess ::  !D '+D $ P!..0 d " $),CT)_,E(FD%#t+/2xx=M8N/OD,zztzz'(:;  zz sBB43B4c||_y)zSet the debugging level. Argument 'level' means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LFN)r)rlevels rset_debuglevelzNNTP.set_debuglevels rctjd|||tz}|jdkDrt dt ||j j||j jy)zfInternal: send one line to the server, appending CRLF. The `line` must be a bytes-like object.znntplib.putlinerQz*put*N) rr_CRLFrrrrwriteflushrrYs r_putlinez NNTP._putlinesU #T40e| >>A uWd4j9  rc|jrtdt||j|j|j }|j |y)zkInternal: send one command to the server (through _putline()). The `line` must be a unicode string.z*cmd*N)rrrencodeencodingerrorsrrs r_putcmdz NNTP._putcmds< >>5$t*5{{4==$++6 drc&|jjtdz}t|tkDr t d|j dkDrt dt||st|r#|ddtk(r|dd}|S|ddtvr|dd}|S)zInternal: return one line from the server, stripping _CRLF. Raise EOFError if the connection is closed. Returns a bytes object.rQz line too longz*get*ruN) rreadline_MAXLINErWr rrrrr)r strip_crlfrYs r_getlinez NNTP._getlinesyy!!(A+. t9x 0 0 >>A  '4: &8^ BCyE!CRy bce#CRy rc|j}|jrtdt||j |j |j }|dd}|dk(r t||dk(r t||dvr t||S)zInternal: get a response from the server. Raise various errors if the response indicates an error. Returns a unicode string.z*resp*NrQ45123) rrrrrIrrrr r )rrcs rrz NNTP._getresps}} >>54:6{{4==$++6 !H 8$T* * 8$T* * E>#D) ) rcd} t|ttfrt|dx}}|j }|ddt vr t |g}|Jdtzdf} |jd}||vrni|jdr|dd}|j|>d} |j}||k(rn(|jdr|dd}|j|>|r|j||fS#|r|jwwxYw) aPInternal: get a response plus following text from the server. Raise various errors if the response indicates an error. Returns a (response, lines) tuple where `response` is a unicode string and `lines` is a list of bytes objects. If `file` is a file-like object, it must be open in binary mode. Nwbr .s. rQFs..) rGstrr8openr _LONGRESPrrrrdrrHr)rr openedFilerr9 terminatorsrY terminators r _getlongrespzNNTP._getlongresps)  #$e -$(t$44 T==?DBQxy($T**E#e|V4 ==/D{*u-#ABxJJt$ " ==?Dz)u-#ABxLL&   "U{  "s CC33DcD|j||jS)zWInternal: send a command and get the response. Same return value as _getresp().)rrrs r _shortcmdzNNTP._shortcmds T}}rcF|j||j|S)zoInternal: send a command and get the response plus following text. Same return value as _getlongresp().)rr)rrYrs r_longcmdz NNTP._longcmd!s! T  &&rc|j||j|\}}||Dcgc](}|j|j|j*c}fScc}w)zInternal: send a command and get the response plus following text. Same as _longcmd() and _getlongresp(), except that the returned `lines` are unicode strings rather than bytes objects. )rrrIrr)rrYrrlists r_longcmdstringzNNTP._longcmdstring'sd T&&t, d"&("&$kk$--="&(( ((s-Ac |jS#t$rYnwxYw |jd\}}t|}n#t$r t dd}YnwxYw||_|S)zqInternal: get the overview format. Queries the server if not already done, else returns the cached value.zLIST OVERVIEW.FMTN)_cachedoverviewfmtAttributeErrorrr^r rV)rrr9rXs r_getoverviewfmtzNNTP._getoverviewfmt1su ** *    ---.ABKD% &e,C " +'*C + #& s  >AAcT|Dcgc]}t|jc}Scc}wr)r;ra)rr9rYs r _grouplistzNNTP._grouplistBs%5:;UT 4::<(U;;;s%cri}|jd\}}|D]}|j^}}|||<||fS)a!Process a CAPABILITIES command. Not supported by all servers. Return: - resp: server response if successful - caps: a dictionary mapping capability names to lists of tokens (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] }) CAPABILITIES)rra)rrrr9rYrZrjs rrzNNTP.capabilitiesFsK)).9 eD JJLMD6DJTzr)rc^t|tjtjfs.tdj |j j t||jdk\}}dj ||}|j||\}}||j|fS)zProcess a NEWGROUPS command. Arguments: - date: a date or datetime object Return: - resp: server response if successful - list: list of newsgroup names Athe date parameter must be a date or datetime object, not '{:40}'rrzNEWGROUPS {0} {1}) rGrxr4 TypeErrorr __class__rrrrr)rr4rryrzcmdrr9s r newgroupszNNTP.newgroupsTs$ >?$fT^^%<%<=? ?/tT5F5F5JK(!((8<))#t4 eT__U+++rc4t|tjtjfs.tdj |j j t||jdk\}}dj |||}|j||S)zProcess a NEWNEWS command. Arguments: - group: group name or '*' - date: a date or datetime object Return: - resp: server response if successful - list: list of message ids rrrzNEWNEWS {0} {1} {2}) rGrxr4rrrrrrr)rr<r4rryrzrs rnewnewsz NNTP.newnewsds$ >?$fT^^%<%<=? ?/tT5F5F5JK(#**5(HE""3--rcf|d|z}nd}|j||\}}||j|fS)a@Process a LIST or LIST ACTIVE command. Arguments: - group_pattern: a pattern indicating which groups to query - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (group, last, first, flag) (strings) z LIST ACTIVE LIST)rr)r group_patternrcommandrr9s rrz NNTP.listtsC  $$}4GG))'48 eT__U+++rcNtjd}|jd|z\}}|jds|jd|z\}}i}|D]D}|j |j }|s%|j dd\} } |s| cS| || <F|r||fSy)Nz^(?P[^ ]+)[ ]+(.*)$zLIST NEWSGROUPS r)zXGTITLE rQrrrE)recompilerrdsearchstripr<) rr  return_allline_patrr9groupsraw_linematchrZdescs r_getdescriptionszNNTP._getdescriptionss::>?))*<}*LM eu%--j=.HIKD%HOOHNN$45E"[[A. d!K#t  < rc&|j|dS)aGet a description for a single group. If more than one group matches ('group' is a pattern), return the first. If no group matches, return an empty string. This elides the response code from the server, since it can only be '215' or '285' (for xgtitle) anyway. If the response code is needed, use the 'descriptions' method. NOTE: This neither checks for a wildcard in 'group' nor does it check whether the group actually exists.Fr)rr<s r descriptionzNNTP.descriptions$$UE22rc&|j|dS)z'Get descriptions for a range of groups.Tr)rr s r descriptionszNNTP.descriptionss$$]D99rcT|jd|z}|jds t||j}dx}x}}t |}|dkDr1|d}|dkDr'|d}|dkDr|d}|dkDr|dj }|t |t |t ||fS)aProcess a GROUP command. Argument: - group: the group name Returns: - resp: server response if successful - count: number of articles - first: first article number - last: last article number - name: the group name zGROUP r(rrQrrr rs)rrdrrarWrSrb)rrZrwordscountr>r=ns rr<z NNTP.groups~~ho.u% & &     J q5!HE1uaq5 8D1u$Qx~~/SZUSY<.remove_number5s' $A$%1771a= /4 /r)rrrr) rhdrrrrr9rMrYrLs @rxhdrz NNTP.xhdr*s`jj-.)).*?*?S*I4P e 0e% %Aw t9?% %_T4000rc|j|}|jds t|t|tt fr|j }|D]`}|jts|jdtz}|jdrd|z}|jj|b|jjd|jj|jS)N3r:rs. )rrdrrGr8 bytearray splitlinesendswithrrstriprrrr)rrfrrYs r_postz NNTP._postts~~g&s# & & a%+ , A D=='{{7+e3t$d{ IIOOD !  ! }}rc&|jd|S)zProcess a POST command. Arguments: - data: bytes object, iterable or file containing the article Returns: - resp: server response if successfulPOST)re)rdatas rpostz NNTP.posts zz&$''rcD|jdj||S)a Process an IHAVE command. Arguments: - message_id: message-id of the article - data: file containing the article Returns: - resp: server response if successful Note that if the server refuses the article an exception is raised.z IHAVE {0})rer)rrBrhs rihavez NNTP.ihaves zz+,,Z8$??rc |jr|jj|`|jjy#|jjwxYwr)rrrrs rrz NNTP._closes> yy !I IIOO DIIOO s (AA!ct |jd}|j|S#|jwxYw)zdProcess a QUIT command and close the socket. Returns: - resp: server response if successfulQUIT)rr)rrs rrz NNTP.quits0 >>&)D KKM  KKMs%7cl|jr td|s |s td |r=|s;ddl}|j}|j|j}|r |d}|d}|sy|j d|z}|jdr=|s t||j d|z}|jds t|d|_ |j|jr7d |jvr(|jd|_ |jyyy#t $rYwxYw) NzAlready logged in.z7At least one of `user` and `usenetrc` must be specifiedrrrzauthinfo user 381zauthinfo pass 281r)rrnetrcauthenticatorsrrrrdrr rrrr)rrrrrr credentialsauthrs rrz NNTP.logins5   12 2HIK K #kkm "11$))<7D#AwH ~~.56 ??5 !$T**~~&6&ABu-,T22    $ $)C    !DJ  " *D $%   s?D'' D32D3c |jd|_y#t$rYyt$r.}|jj drd|_nYd}~yd}~wwxYw)Nz mode reader480T)rrr rrrdr)res rrzNNTP._setreadermodesT >>-8DL!  ! zz$$U+,0)* s AA$AAc|jr td|jr td|jd}|j dr|j j t|j||j|_|jjd|_d|_d|_ |jytd) zzProcess a STARTTLS command. Arguments: - context: SSL context to use for the encrypted connection zTLS is already enabled.z+TLS cannot be started after authentication.STARTTLS382rTNzTLS failed to start.)rrrrrdrrrrrrrrr)rrrs rstarttlsz NNTP.starttlss {{ !:;;!! !NOO>>*-Du% !' 7DIIF  II..u5 " " $$& 677r)Tr)NNT):rrrrr NNTP_PORTrrrrrrrrrdebugrrrrrrrrrrrrr rrrrr<r&r*r,r0r4r=r9r>rBrErHrOrSrXr4rerirkrrrr _have_sslr|rrrrr+scH F"+$ 50!F #D "I , E" ,\ ' ("< '+, ,0. ,t ,. 3:=4 1)% )%%= 'd ' 'd ' ' '' &*= )- 1*.161"*(@'#R  8rrc8eZdZedddddeffd ZfdZxZS)NNTP_SSLNFc >||_t | |||||||y)zThis works identically to NNTP.__init__, except for the change in default port and the `ssl_context` argument for SSL connections. N) ssl_contextsuperr) rrrrrrrrrrs rrzNNTP_SSL.__init__s) +D  G T4x%w 0rct||} t||j|j}|S#|j xYwr)rrrrrr)rrrrs rrzNNTP_SSL._create_socketsI7)'2D "4)9)9499E    s !5A)rrr NNTP_SSL_PORTrrr __classcell__)rs@rrrs$&3$#e3 0  rr__main__zJ nntplib built-in demo - display the latest articles in a newsgroup)rz-gz--groupzgmane.comp.python.generalz3group to fetch messages from (default: %(default)s))defaultr&z-sz--serverz news.gmane.ioz+NNTP server hostname (default: %(default)s)z-pz--portrzNNTP port number (default: z / ))rtyper&z-nz --nb-articles z2number of articles to fetch (default: %(default)s)z-Sz--ssl store_truezuse NNTP over SSL)actionrr&)rrrzGrouphaszarticles, rangetoc8t||kDr |d|dz dz}|S)Nrsz...)rW)slims rcutr6s& q6C<(37 e#ArrQr3r=rZrrr nb_articlesrS overviewsartnumrXraauthorr2r9rrrrrrsB  I>*  Xg. 0 0 Y        I     O    "K " ";#E G %k$$]%FH 2:H,4  CK 8K 8\ 4. NN: z $X $ $2NOF i1LRT j/JL hFOQ^_a orQS glE02    D 99D 88 2:D dkk - 2: D $++D 1   DT %&WWTZZ%8"D%d '4'8%tL D D,,,q0 1EggeT*OD)! tF|,223:1=Y0DN# %,,c&"os7B'7@  "FFHaUIsK77LL