o w[e? @s>dZddlZddlZddlZddlZddlZzddlZWn ey'dZYnwdZddl m Z ddlm Z gdZ dZGd d d eZGd d d eZGd ddeZGdddeZGdddeZGdddeZdZdZhdZgdZdddZdZedgdZedgd Zd!d"Z d#d$ZdZd%d&Z dZd'd(Z!d[d)d*Z"erd+d,Z#Gd-d.d.Z$erGd/d0d0e$Z%e &d0e'd1krddl(Z(e(j)d2d3Z*e*j+d4d5d6d7d8e*j+d9d:d;dd?e,d@eefdAe*j+dBdCdDe,dEdAe*j+dFdGdHddIdJe*-Z.e.j/Z/e.jse/d?kreZ/e$e.j0e/dKZ1ne/d?kr&eZ/e%e.j0e/dKZ1e12Z3dLe3vr:e14e15e.j5\Z6Z7Z8Z9Z:e;dMe:dNe7dOe8dPe9dQdRZdSZ8e1?e8e9\Z6Z@e@D]-\ZAZBe eBdTCdUdSdZDe eBdVZEe,eBdZFe;dWGeAe>> 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. NFT) decode_header)_GLOBAL_DEFAULT_TIMEOUT)NNTP NNTPErrorNNTPReplyErrorNNTPTemporaryErrorNNTPPermanentErrorNNTPProtocolError NNTPDataErrorric@seZdZdZddZdS)rz%Base class for all nntplib exceptionscGs>tj|g|Rz|d|_WdStyd|_YdSw)NrzNo response given) Exception__init__response IndexError)selfargsr/usr/lib/python3.10/nntplib.pyr bs   zNNTPError.__init__N)__name__ __module__ __qualname____doc__r rrrrr`s rc@eZdZdZdS)rzUnexpected [123]xx replyNrrrrrrrrrirc@r)rz 4xx errorsNrrrrrrmrrc@r)rz 5xx errorsNrrrrrrqrrc@r)r z"Response does not begin with [1-5]Nrrrrrr urr c@r)r zError in response dataNrrrrrr yrr wi3> 100101211215220221222224225230231282)subjectfromdatez message-id references:bytes:linesr+r,)byteslines GroupInfo)grouplastfirstflag ArticleInfo)number message_idr.cCsJg}t|D]\}}t|tr|||pdq||qd|S)zvTakes a unicode string representing a munged header value and decodes it as a (possibly non-ASCII) readable value.ascii)_email_decode_header isinstancer-appenddecodejoin) header_strpartsvencrrrrs    rcCsg}|D]0}|ddkr|ddd\}}}d|}n|d\}}}|}t||}||qt}t|t|krCtd|dt||krQtd|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_ALTERNATIVESgetr<_DEFAULT_OVERVIEW_FMTlenr )r.fmtlinename_suffixdefaultsrrr_parse_overview_fmts    rQcCstt}g}|D]]}i}|d^}}t|}t|D]B\} } | t|kr&q|| } | d} | |krW| sW| d} | rK| dt| | krKtd| rU| t| dnd} | ||| <q|||fq|S)zZParse the response to an OVER or XOVER command according to the overview format `fmt`. rCz: Nz?OVER/XOVER response doesn't include names of additional headers) rJrIsplitint enumerate startswithrFr r<)r.rKdata_process_func n_defaultsoverviewrLfieldsarticle_numbertokensitoken field_name is_metadatahrrr_parse_overviews&   rbcCs|dur|dd}|dd}t|dd}t|dd}t|dd}t|dd}t|dd}t|dd}|dkrI|d7}n|d krQ|d 7}t||||||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)rTdatetime)date_strtime_strhoursminutessecondsyearmonthdayrrr_parse_datetimes   rrcCsVt|tjs d}nd|}|j}|r!|d}d||}||fSd||}||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}rhz{0:02d}{1.month:02d}{1.day:02d}z{0:04d}{1.month:02d}{1.day:02d})r;riformatro)dtlegacyrkyrjrrr_unparse_datetimes    rxcCs|durt}|j||dS)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. N)server_hostname)ssl_create_stdlib_context wrap_socket)sockcontexthostnamerrr _encrypt_onsrc@s eZdZdZdZeddddefddZddZd d Z d d Z d dZ ddZ ddZ ddZeZddZddZdiddZddZdjddZd d!Zdjd"d#Zdjd$d%Zd&d'Zd(d)Zd*d+Zdd,d-d.Zdd,d/d0Zdjdd,d1d2Zd3d4Zd5d6Zd7d8Z d9d:Z!dd,d;d<Z"d=d>Z#d?d@Z$djdAdBZ%dCdDZ&dEdFZ'djdGdHZ(djdd,dIdJZ)djdd,dKdLZ*djdd,dMdNZ+dOdPZ,dd,dQdRZ-dd,dSdTZ.dd,dUdVZ/dWdXZ0dYdZZ1d[d\Z2d]d^Z3d_d`Z4dadbZ5dkdcddZ6dedfZ7e8rdjdgdhZ9dSdS)lrzutf-8surrogateescapeNFcCs|||_||_|||_d|_z|jd|_|||s |r*||||WdSWdS|jr8|j|j)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_socketr}filemakefile _base_initloginclose)rrruserpassword readermodeusenetrctimeoutrrrr 8s    z NNTP.__init__cCs^d|_||_d|_|d|_|r'd|jvr'||js'd|_|d|_d|_dS)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)rrrrrr[s   zNNTP._base_initcCs|SNrrrrr __enter__}szNNTP.__enter__c sffdd}|r1zzWn ttfyYnwW|r&dSdS|r0wwdS)Ncs tdS)Nr)hasattrrrrrs zNNTP.__exit__..)quitOSErrorEOFError_close)rr is_connectedrrr__exit__s    z NNTP.__exit__cCs<|dur |s tdtd||j|jt|j|jf|S)Nz0Non-blocking socket (timeout=0) is not supportedznntplib.connect) ValueErrorsysauditrrsocketcreate_connection)rrrrrrs zNNTP._create_socketcCs|jr tdt|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*)rprintreprrrrrr getwelcomeszNNTP.getwelcomec Cs|jdurAd|_d|_z|\}}Wnttfy#i|_Y|jSw||_d|vr5ttt|d|_d|vrAd |d|_|jS)zGet the server capabilities, as read by __init__(). If the CAPABILITIES command is not supported, an empty dict is returned.NrDVERSIONIMPLEMENTATION ) r nntp_versionnntp_implementation capabilitiesrrmaxmaprTr>)rrespcapsrrrrs  zNNTP.getcapabilitiescCs ||_dS)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)rlevelrrrset_debuglevels zNNTP.set_debuglevelcCsHtd|||t}|jdkrtdt||j||jdS)zfInternal: send one line to the server, appending CRLF. The `line` must be a bytes-like object.znntplib.putlinerDz*put*N) rr_CRLFrrrrwriteflushrrLrrr_putlines  z NNTP._putlinecCs2|jr tdt|||j|j}||dS)zkInternal: send one command to the server (through _putline()). The `line` must be a unicode string.z*cmd*N)rrrencodeencodingerrorsrrrrr_putcmdsz NNTP._putcmdTcCs|jtd}t|tkrtd|jdkrtdt||s"t|rB|ddt kr4|dd}|S|ddt vrB|dd}|S)zInternal: return one line from the server, stripping _CRLF. Raise EOFError if the connection is closed. Returns a bytes object.rDz line too longz*get*rfN) rreadline_MAXLINErJr rrrrr)r strip_crlfrLrrr_getlines    z NNTP._getlinecCsl|}|jrtdt|||j|j}|dd}|dkr$t||dkr,t||dvr4t ||S)zInternal: get a response from the server. Raise various errors if the response indicates an error. Returns a unicode string.z*resp*NrD45123) rrrrr=rrrrr )rrcrrrrs z NNTP._getrespcCsd}zot|ttfrt|d}}|}|ddtvr!t|g}|durJdtdf} |d}||vr8n| drC|dd}| |q.nd} |}||krVn| dra|dd}| |qMW|rn| ||fS|ry| ww) 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. Nwb.s. rDFs..) r;strr-openr _LONGRESPrrrrVrr<r)rr openedFilerr. terminatorsrL terminatorrrr _getlongrespsF           zNNTP._getlongrespcCs|||S)zWInternal: send a command and get the response. Same return value as _getresp().)rrrrrr _shortcmds zNNTP._shortcmdcCs||||S)zoInternal: send a command and get the response plus following text. Same return value as _getlongresp().rr)rrLrrrr_longcmds  z NNTP._longcmdcs.||\}}|fdd|DfS)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. csg|] }|jjqSr)r=rr.0rLrrr +sz'NNTP._longcmdstring..r)rrLrrlistrrr_longcmdstring$s  zNNTP._longcmdstringcCs`z|jWSty Ynwz |d\}}Wnty&tdd}Ynwt|}||_|S)zqInternal: get the overview format. Queries the server if not already done, else returns the cached value.zLIST OVERVIEW.FMTN)_cachedoverviewfmtAttributeErrorrrrIrQ)rrr.rKrrr_getoverviewfmt.s  zNNTP._getoverviewfmtcCsdd|DS)NcSsg|]}t|qSr)r0rSrrrrrAsz#NNTP._grouplist..r)rr.rrr _grouplist?szNNTP._grouplistcCs8i}|d\}}|D] }|^}}|||<q ||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)rrS)rrrr.rLrMr\rrrrCs   zNNTP.capabilities)rcCsbt|tjtjfstd|jjt||jdk\}}d||}| ||\}}|| |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}'rczNEWGROUPS {0} {1}) r;rir) TypeErrorrt __class__rrxrrr)rr)rrjrkcmdrr.rrr newgroupsQs  zNNTP.newgroupscCsRt|tjtjfstd|jjt||jdk\}}d|||}| ||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 rrczNEWNEWS {0} {1} {2}) r;rir)rrtrrrxrr)rr1r)rrjrkrrrrnewnewsas  z NNTP.newnewscCs4|dur d|}nd}|||\}}|||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) Nz LIST ACTIVE LIST)rr)r group_patternrcommandrr.rrrrqs  z NNTP.listc Cstd}|d|\}}|ds|d|\}}i}|D]}||}|r=|dd\} } |s9| S| || <q |rD||fSdS)Nz^(?P[^ ]+)[ ]+(.*)$zLIST NEWSGROUPS rzXGTITLE rDrcr9)recompilerrVsearchstripr1) rr return_allline_patrr.groupsraw_linematchrMdescrrr_getdescriptionss  zNNTP._getdescriptionscC ||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)rr1rrr descriptions zNNTP.descriptioncCr)z'Get descriptions for a range of groups.Tr)rrrrr descriptionss zNNTP.descriptionscCs|d|}|dst||}d}}}t|}|dkr@|d}|dkr@|d}|dkr@|d}|dkr@|d}|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 rrrDrcrrd)rrVrrSrJrFrT)rrMrwordscountr3r2nrrrr1s   z NNTP.groupcC |d|S)aProcess a HELP command. Argument: - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of strings returned by the server in response to the HELP command HELP)r)rrrrrhelps z NNTP.helpcCs8|ds t||}t|d}|d}|||fS)z_Internal: parse the response line of a STAT, NEXT, LAST, ARTICLE, HEAD or BODY command.22rDrc)rVrrSrT)rrrart_numr7rrr _statparses   zNNTP._statparsecCs||}||S)z/Internal: process a STAT, NEXT or LAST command.)rr)rrLrrrr_statcmds  z NNTP._statcmdcCs|r |d|S|dS)a(Process a STAT command. Argument: - message_spec: article number or message id (if not specified, the current article is selected) Returns: - resp: server response if successful - art_num: the article number - message_id: the message id zSTAT {0}STAT)rrt)r message_specrrrstats  z NNTP.statcC |dS)z;Process a NEXT command. No arguments. Return as for STAT.NEXTrrrrrnext z NNTP.nextcCr)z;Process a LAST command. No arguments. Return as for STAT.LASTr rrrrr2r z NNTP.lastcCs0|||\}}||\}}}|t|||fS)z2Internal: process a HEAD, BODY or ARTICLE command.)rrr5)rrLrrr.rr7rrr_artcmdsz NNTP._artcmdcC$|dur d|}nd}|||S)a0Process a HEAD command. Argument: - message_spec: article number or message id - file: filename string or file object to store the headers in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of header lines) NzHEAD {0}HEADrtr rrrrrrrhead  z NNTP.headcCr)a+Process a BODY command. Argument: - message_spec: article number or message id - file: filename string or file object to store the body in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of body lines) NzBODY {0}BODYrrrrrbodyrz NNTP.bodycCr)a5Process an ARTICLE command. Argument: - message_spec: article number or message id - file: filename string or file object to store the article in Returns: - resp: server response if successful - ArticleInfo: (article number, message id, list of article lines) Nz ARTICLE {0}ARTICLErrrrrarticlerz NNTP.articlecCr)zYProcess a SLAVE command. Returns: - resp: server response if successful SLAVE)rrrrrslave!s z NNTP.slavecsDtd|d|||\}}fdd|fdd|DfS)aiProcess an XHDR command (optional server extension). Arguments: - hdr: the header type (e.g. 'subject') - str: an article nr, a message id, or a range nr1-nr2 - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of (nr, value) strings z^([0-9]+) ?(.*) ?z XHDR {0} {1}cs|}|r |ddS|S)NrDrc)rr1)rLm)patrr remove_number2s z NNTP.xhdr..remove_numbercsg|]}|qSrrr)rrrr5szNNTP.xhdr..)rrrrt)rhdrrrrr.r)rrrxhdr's  z NNTP.xhdrcCs.|d|||\}}|}|t||fS)aFProcess an XOVER command (optional server extension) Arguments: - start: start of range - end: end of range - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of dicts containing the response fields z XOVER {0}-{1})rrtrrb)rstartendrrr.rKrrrxover7s  z NNTP.xoverc Csxd|jvrdnd}t|ttfr|\}}|d||pd7}n |dur)|d|}|||\}}|}|t||fS)aProcess an OVER command. If the command isn't supported, fall back to XOVER. Arguments: - message_spec: - either a message id, indicating the article to fetch information about - or a (start, end) tuple, indicating a range of article numbers; if end is None, information up to the newest message will be retrieved - or None, indicating the current article number must be used - file: Filename string or file object to store the result in Returns: - resp: server response if successful - list: list of dicts containing the response fields NOTE: the "message id" form isn't supported by XOVER OVERXOVERz {0}-{1}r9Nr)rr;tuplerrtrrrb) rrrrrr rr.rKrrroverEs z NNTP.overcCsb|d}|dst||}t|dkrt||d}t|dkr*t||t|dfS)zProcess the DATE command. Returns: - resp: server response if successful - date: datetime object DATE111rcrDN)rrVrrSrJr rr)rrelemr)rrrr)`s    z NNTP.datecCs||}|dst|t|ttfr|}|D]}|ts)| dt}|dr2d|}|j |q|j d|j | S)N3r/rs. )rrVrr;r- bytearray splitlinesendswithrrstriprrrr)rrfrrLrrr_postqs      z NNTP._postcCr)zProcess a POST command. Arguments: - data: bytes object, iterable or file containing the article Returns: - resp: server response if successfulPOST)r0)rdatarrrposts z NNTP.postcCs|d||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})r0rt)rr7r2rrrihavesz NNTP.ihavecCsBz|jr|j|`W|jdSW|jdS|jwr)rrr}rrrrrs z NNTP._closecCs$z |d}W||S|w)zdProcess a QUIT command and close the socket. Returns: - resp: server response if successfulQUIT)rr)rrrrrrs   z NNTP.quitcCs|jrtd|s|stdz|r,|s,ddl}|}||j}|r,|d}|d}Wn ty6Ynw|s;dS|d|}|dr]|sMt||d|}|ds]t |d|_ | |j ryd |j vr{| d|_ | dSdSdS) NzAlready logged in.z7At least one of `user` and `usenetrc` must be specifiedrrczauthinfo user 381zauthinfo pass 281r)rrnetrcauthenticatorsrrrrVrrrrrr)rrrrr8 credentialsauthrrrrrsD     z NNTP.loginc Csbz |d|_WdStyYdSty0}z|jdr$d|_nWYd}~dSd}~ww)Nz mode reader480T)rrrrr rVr)rerrrrs  zNNTP._setreadermodecCsz|jrtd|jrtd|d}|dr9|jt|j||j |_|j d|_d|_d|_ | dSt d) 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.)rrrrrVrrrr}rrrrr)rr~rrrrstarttlss    z NNTP.starttls)Tr)NNT):rrrrr NNTP_PORTrr rrrrrrrdebugrrrrrrrrrrrrrrrrrr1rrrrr r2r rrrrrr!r%r)r0r3r4rrrr _have_sslr@rrrrr(st  #"    .         ) rcs8eZdZedddddeffdd ZfddZZS)NNTP_SSLNFc s"||_t|||||||dS)zThis works identically to NNTP.__init__, except for the change in default port and the `ssl_context` argument for SSL connections. N) ssl_contextsuperr ) rrrrrrErrrrrrr szNNTP_SSL.__init__cs4t|}z t||j|j}W|S|r)rFrrrErr)rrr}rGrrrs zNNTP_SSL._create_socket)rrr NNTP_SSL_PORTrr r __classcell__rrrGrrDs rD__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))defaultrz-sz--serverz news.gmane.ioz+NNTP server hostname (default: %(default)s)z-pz--portrz#NNTP port number (default: %s / %s))rKtyperz-nz --nb-articles z2number of articles to fetch (default: %(default)s)z-Sz--ssl store_truezuse NNTP over SSL)actionrKr)rrr>Grouphaszarticles, rangetocCs$t||kr|d|dd}|S)Nrdz...)rJ)slimrrrcut3s rUrDr(sA         S