Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: nntplib.py
"""An NNTP client class based on:
[0] Fix | Delete
- RFC 977: Network News Transfer Protocol
[1] Fix | Delete
- RFC 2980: Common NNTP Extensions
[2] Fix | Delete
- RFC 3977: Network News Transfer Protocol (version 2)
[3] Fix | Delete
[4] Fix | Delete
Example:
[5] Fix | Delete
[6] Fix | Delete
>>> from nntplib import NNTP
[7] Fix | Delete
>>> s = NNTP('news')
[8] Fix | Delete
>>> resp, count, first, last, name = s.group('comp.lang.python')
[9] Fix | Delete
>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
[10] Fix | Delete
Group comp.lang.python has 51 articles, range 5770 to 5821
[11] Fix | Delete
>>> resp, subs = s.xhdr('subject', '{0}-{1}'.format(first, last))
[12] Fix | Delete
>>> resp = s.quit()
[13] Fix | Delete
>>>
[14] Fix | Delete
[15] Fix | Delete
Here 'resp' is the server response line.
[16] Fix | Delete
Error responses are turned into exceptions.
[17] Fix | Delete
[18] Fix | Delete
To post an article from a file:
[19] Fix | Delete
>>> f = open(filename, 'rb') # file containing article, including header
[20] Fix | Delete
>>> resp = s.post(f)
[21] Fix | Delete
>>>
[22] Fix | Delete
[23] Fix | Delete
For descriptions of all methods, read the comments in the code below.
[24] Fix | Delete
Note that all arguments and return values representing article numbers
[25] Fix | Delete
are strings, not numbers, since they are rarely used for calculations.
[26] Fix | Delete
"""
[27] Fix | Delete
[28] Fix | Delete
# RFC 977 by Brian Kantor and Phil Lapsley.
[29] Fix | Delete
# xover, xgtitle, xpath, date methods by Kevan Heydon
[30] Fix | Delete
[31] Fix | Delete
# Incompatible changes from the 2.x nntplib:
[32] Fix | Delete
# - all commands are encoded as UTF-8 data (using the "surrogateescape"
[33] Fix | Delete
# error handler), except for raw message data (POST, IHAVE)
[34] Fix | Delete
# - all responses are decoded as UTF-8 data (using the "surrogateescape"
[35] Fix | Delete
# error handler), except for raw message data (ARTICLE, HEAD, BODY)
[36] Fix | Delete
# - the `file` argument to various methods is keyword-only
[37] Fix | Delete
#
[38] Fix | Delete
# - NNTP.date() returns a datetime object
[39] Fix | Delete
# - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object,
[40] Fix | Delete
# rather than a pair of (date, time) strings.
[41] Fix | Delete
# - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples
[42] Fix | Delete
# - NNTP.descriptions() returns a dict mapping group names to descriptions
[43] Fix | Delete
# - NNTP.xover() returns a list of dicts mapping field names (header or metadata)
[44] Fix | Delete
# to field values; each dict representing a message overview.
[45] Fix | Delete
# - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo)
[46] Fix | Delete
# tuple.
[47] Fix | Delete
# - the "internal" methods have been marked private (they now start with
[48] Fix | Delete
# an underscore)
[49] Fix | Delete
[50] Fix | Delete
# Other changes from the 2.x/3.1 nntplib:
[51] Fix | Delete
# - automatic querying of capabilities at connect
[52] Fix | Delete
# - New method NNTP.getcapabilities()
[53] Fix | Delete
# - New method NNTP.over()
[54] Fix | Delete
# - New helper function decode_header()
[55] Fix | Delete
# - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and
[56] Fix | Delete
# arbitrary iterables yielding lines.
[57] Fix | Delete
# - An extensive test suite :-)
[58] Fix | Delete
[59] Fix | Delete
# TODO:
[60] Fix | Delete
# - return structured data (GroupInfo etc.) everywhere
[61] Fix | Delete
# - support HDR
[62] Fix | Delete
[63] Fix | Delete
# Imports
[64] Fix | Delete
import re
[65] Fix | Delete
import socket
[66] Fix | Delete
import collections
[67] Fix | Delete
import datetime
[68] Fix | Delete
import sys
[69] Fix | Delete
[70] Fix | Delete
try:
[71] Fix | Delete
import ssl
[72] Fix | Delete
except ImportError:
[73] Fix | Delete
_have_ssl = False
[74] Fix | Delete
else:
[75] Fix | Delete
_have_ssl = True
[76] Fix | Delete
[77] Fix | Delete
from email.header import decode_header as _email_decode_header
[78] Fix | Delete
from socket import _GLOBAL_DEFAULT_TIMEOUT
[79] Fix | Delete
[80] Fix | Delete
__all__ = ["NNTP",
[81] Fix | Delete
"NNTPError", "NNTPReplyError", "NNTPTemporaryError",
[82] Fix | Delete
"NNTPPermanentError", "NNTPProtocolError", "NNTPDataError",
[83] Fix | Delete
"decode_header",
[84] Fix | Delete
]
[85] Fix | Delete
[86] Fix | Delete
# maximal line length when calling readline(). This is to prevent
[87] Fix | Delete
# reading arbitrary length lines. RFC 3977 limits NNTP line length to
[88] Fix | Delete
# 512 characters, including CRLF. We have selected 2048 just to be on
[89] Fix | Delete
# the safe side.
[90] Fix | Delete
_MAXLINE = 2048
[91] Fix | Delete
[92] Fix | Delete
[93] Fix | Delete
# Exceptions raised when an error or invalid response is received
[94] Fix | Delete
class NNTPError(Exception):
[95] Fix | Delete
"""Base class for all nntplib exceptions"""
[96] Fix | Delete
def __init__(self, *args):
[97] Fix | Delete
Exception.__init__(self, *args)
[98] Fix | Delete
try:
[99] Fix | Delete
self.response = args[0]
[100] Fix | Delete
except IndexError:
[101] Fix | Delete
self.response = 'No response given'
[102] Fix | Delete
[103] Fix | Delete
class NNTPReplyError(NNTPError):
[104] Fix | Delete
"""Unexpected [123]xx reply"""
[105] Fix | Delete
pass
[106] Fix | Delete
[107] Fix | Delete
class NNTPTemporaryError(NNTPError):
[108] Fix | Delete
"""4xx errors"""
[109] Fix | Delete
pass
[110] Fix | Delete
[111] Fix | Delete
class NNTPPermanentError(NNTPError):
[112] Fix | Delete
"""5xx errors"""
[113] Fix | Delete
pass
[114] Fix | Delete
[115] Fix | Delete
class NNTPProtocolError(NNTPError):
[116] Fix | Delete
"""Response does not begin with [1-5]"""
[117] Fix | Delete
pass
[118] Fix | Delete
[119] Fix | Delete
class NNTPDataError(NNTPError):
[120] Fix | Delete
"""Error in response data"""
[121] Fix | Delete
pass
[122] Fix | Delete
[123] Fix | Delete
[124] Fix | Delete
# Standard port used by NNTP servers
[125] Fix | Delete
NNTP_PORT = 119
[126] Fix | Delete
NNTP_SSL_PORT = 563
[127] Fix | Delete
[128] Fix | Delete
# Response numbers that are followed by additional text (e.g. article)
[129] Fix | Delete
_LONGRESP = {
[130] Fix | Delete
'100', # HELP
[131] Fix | Delete
'101', # CAPABILITIES
[132] Fix | Delete
'211', # LISTGROUP (also not multi-line with GROUP)
[133] Fix | Delete
'215', # LIST
[134] Fix | Delete
'220', # ARTICLE
[135] Fix | Delete
'221', # HEAD, XHDR
[136] Fix | Delete
'222', # BODY
[137] Fix | Delete
'224', # OVER, XOVER
[138] Fix | Delete
'225', # HDR
[139] Fix | Delete
'230', # NEWNEWS
[140] Fix | Delete
'231', # NEWGROUPS
[141] Fix | Delete
'282', # XGTITLE
[142] Fix | Delete
}
[143] Fix | Delete
[144] Fix | Delete
# Default decoded value for LIST OVERVIEW.FMT if not supported
[145] Fix | Delete
_DEFAULT_OVERVIEW_FMT = [
[146] Fix | Delete
"subject", "from", "date", "message-id", "references", ":bytes", ":lines"]
[147] Fix | Delete
[148] Fix | Delete
# Alternative names allowed in LIST OVERVIEW.FMT response
[149] Fix | Delete
_OVERVIEW_FMT_ALTERNATIVES = {
[150] Fix | Delete
'bytes': ':bytes',
[151] Fix | Delete
'lines': ':lines',
[152] Fix | Delete
}
[153] Fix | Delete
[154] Fix | Delete
# Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
[155] Fix | Delete
_CRLF = b'\r\n'
[156] Fix | Delete
[157] Fix | Delete
GroupInfo = collections.namedtuple('GroupInfo',
[158] Fix | Delete
['group', 'last', 'first', 'flag'])
[159] Fix | Delete
[160] Fix | Delete
ArticleInfo = collections.namedtuple('ArticleInfo',
[161] Fix | Delete
['number', 'message_id', 'lines'])
[162] Fix | Delete
[163] Fix | Delete
[164] Fix | Delete
# Helper function(s)
[165] Fix | Delete
def decode_header(header_str):
[166] Fix | Delete
"""Takes a unicode string representing a munged header value
[167] Fix | Delete
and decodes it as a (possibly non-ASCII) readable value."""
[168] Fix | Delete
parts = []
[169] Fix | Delete
for v, enc in _email_decode_header(header_str):
[170] Fix | Delete
if isinstance(v, bytes):
[171] Fix | Delete
parts.append(v.decode(enc or 'ascii'))
[172] Fix | Delete
else:
[173] Fix | Delete
parts.append(v)
[174] Fix | Delete
return ''.join(parts)
[175] Fix | Delete
[176] Fix | Delete
def _parse_overview_fmt(lines):
[177] Fix | Delete
"""Parse a list of string representing the response to LIST OVERVIEW.FMT
[178] Fix | Delete
and return a list of header/metadata names.
[179] Fix | Delete
Raises NNTPDataError if the response is not compliant
[180] Fix | Delete
(cf. RFC 3977, section 8.4)."""
[181] Fix | Delete
fmt = []
[182] Fix | Delete
for line in lines:
[183] Fix | Delete
if line[0] == ':':
[184] Fix | Delete
# Metadata name (e.g. ":bytes")
[185] Fix | Delete
name, _, suffix = line[1:].partition(':')
[186] Fix | Delete
name = ':' + name
[187] Fix | Delete
else:
[188] Fix | Delete
# Header name (e.g. "Subject:" or "Xref:full")
[189] Fix | Delete
name, _, suffix = line.partition(':')
[190] Fix | Delete
name = name.lower()
[191] Fix | Delete
name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name)
[192] Fix | Delete
# Should we do something with the suffix?
[193] Fix | Delete
fmt.append(name)
[194] Fix | Delete
defaults = _DEFAULT_OVERVIEW_FMT
[195] Fix | Delete
if len(fmt) < len(defaults):
[196] Fix | Delete
raise NNTPDataError("LIST OVERVIEW.FMT response too short")
[197] Fix | Delete
if fmt[:len(defaults)] != defaults:
[198] Fix | Delete
raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields")
[199] Fix | Delete
return fmt
[200] Fix | Delete
[201] Fix | Delete
def _parse_overview(lines, fmt, data_process_func=None):
[202] Fix | Delete
"""Parse the response to an OVER or XOVER command according to the
[203] Fix | Delete
overview format `fmt`."""
[204] Fix | Delete
n_defaults = len(_DEFAULT_OVERVIEW_FMT)
[205] Fix | Delete
overview = []
[206] Fix | Delete
for line in lines:
[207] Fix | Delete
fields = {}
[208] Fix | Delete
article_number, *tokens = line.split('\t')
[209] Fix | Delete
article_number = int(article_number)
[210] Fix | Delete
for i, token in enumerate(tokens):
[211] Fix | Delete
if i >= len(fmt):
[212] Fix | Delete
# XXX should we raise an error? Some servers might not
[213] Fix | Delete
# support LIST OVERVIEW.FMT and still return additional
[214] Fix | Delete
# headers.
[215] Fix | Delete
continue
[216] Fix | Delete
field_name = fmt[i]
[217] Fix | Delete
is_metadata = field_name.startswith(':')
[218] Fix | Delete
if i >= n_defaults and not is_metadata:
[219] Fix | Delete
# Non-default header names are included in full in the response
[220] Fix | Delete
# (unless the field is totally empty)
[221] Fix | Delete
h = field_name + ": "
[222] Fix | Delete
if token and token[:len(h)].lower() != h:
[223] Fix | Delete
raise NNTPDataError("OVER/XOVER response doesn't include "
[224] Fix | Delete
"names of additional headers")
[225] Fix | Delete
token = token[len(h):] if token else None
[226] Fix | Delete
fields[fmt[i]] = token
[227] Fix | Delete
overview.append((article_number, fields))
[228] Fix | Delete
return overview
[229] Fix | Delete
[230] Fix | Delete
def _parse_datetime(date_str, time_str=None):
[231] Fix | Delete
"""Parse a pair of (date, time) strings, and return a datetime object.
[232] Fix | Delete
If only the date is given, it is assumed to be date and time
[233] Fix | Delete
concatenated together (e.g. response to the DATE command).
[234] Fix | Delete
"""
[235] Fix | Delete
if time_str is None:
[236] Fix | Delete
time_str = date_str[-6:]
[237] Fix | Delete
date_str = date_str[:-6]
[238] Fix | Delete
hours = int(time_str[:2])
[239] Fix | Delete
minutes = int(time_str[2:4])
[240] Fix | Delete
seconds = int(time_str[4:])
[241] Fix | Delete
year = int(date_str[:-4])
[242] Fix | Delete
month = int(date_str[-4:-2])
[243] Fix | Delete
day = int(date_str[-2:])
[244] Fix | Delete
# RFC 3977 doesn't say how to interpret 2-char years. Assume that
[245] Fix | Delete
# there are no dates before 1970 on Usenet.
[246] Fix | Delete
if year < 70:
[247] Fix | Delete
year += 2000
[248] Fix | Delete
elif year < 100:
[249] Fix | Delete
year += 1900
[250] Fix | Delete
return datetime.datetime(year, month, day, hours, minutes, seconds)
[251] Fix | Delete
[252] Fix | Delete
def _unparse_datetime(dt, legacy=False):
[253] Fix | Delete
"""Format a date or datetime object as a pair of (date, time) strings
[254] Fix | Delete
in the format required by the NEWNEWS and NEWGROUPS commands. If a
[255] Fix | Delete
date object is passed, the time is assumed to be midnight (00h00).
[256] Fix | Delete
[257] Fix | Delete
The returned representation depends on the legacy flag:
[258] Fix | Delete
* if legacy is False (the default):
[259] Fix | Delete
date has the YYYYMMDD format and time the HHMMSS format
[260] Fix | Delete
* if legacy is True:
[261] Fix | Delete
date has the YYMMDD format and time the HHMMSS format.
[262] Fix | Delete
RFC 3977 compliant servers should understand both formats; therefore,
[263] Fix | Delete
legacy is only needed when talking to old servers.
[264] Fix | Delete
"""
[265] Fix | Delete
if not isinstance(dt, datetime.datetime):
[266] Fix | Delete
time_str = "000000"
[267] Fix | Delete
else:
[268] Fix | Delete
time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt)
[269] Fix | Delete
y = dt.year
[270] Fix | Delete
if legacy:
[271] Fix | Delete
y = y % 100
[272] Fix | Delete
date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt)
[273] Fix | Delete
else:
[274] Fix | Delete
date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt)
[275] Fix | Delete
return date_str, time_str
[276] Fix | Delete
[277] Fix | Delete
[278] Fix | Delete
if _have_ssl:
[279] Fix | Delete
[280] Fix | Delete
def _encrypt_on(sock, context, hostname):
[281] Fix | Delete
"""Wrap a socket in SSL/TLS. Arguments:
[282] Fix | Delete
- sock: Socket to wrap
[283] Fix | Delete
- context: SSL context to use for the encrypted connection
[284] Fix | Delete
Returns:
[285] Fix | Delete
- sock: New, encrypted socket.
[286] Fix | Delete
"""
[287] Fix | Delete
# Generate a default SSL context if none was passed.
[288] Fix | Delete
if context is None:
[289] Fix | Delete
context = ssl._create_stdlib_context()
[290] Fix | Delete
return context.wrap_socket(sock, server_hostname=hostname)
[291] Fix | Delete
[292] Fix | Delete
[293] Fix | Delete
# The classes themselves
[294] Fix | Delete
class NNTP:
[295] Fix | Delete
# UTF-8 is the character set for all NNTP commands and responses: they
[296] Fix | Delete
# are automatically encoded (when sending) and decoded (and receiving)
[297] Fix | Delete
# by this class.
[298] Fix | Delete
# However, some multi-line data blocks can contain arbitrary bytes (for
[299] Fix | Delete
# example, latin-1 or utf-16 data in the body of a message). Commands
[300] Fix | Delete
# taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message
[301] Fix | Delete
# data will therefore only accept and produce bytes objects.
[302] Fix | Delete
# Furthermore, since there could be non-compliant servers out there,
[303] Fix | Delete
# we use 'surrogateescape' as the error handler for fault tolerance
[304] Fix | Delete
# and easy round-tripping. This could be useful for some applications
[305] Fix | Delete
# (e.g. NNTP gateways).
[306] Fix | Delete
[307] Fix | Delete
encoding = 'utf-8'
[308] Fix | Delete
errors = 'surrogateescape'
[309] Fix | Delete
[310] Fix | Delete
def __init__(self, host, port=NNTP_PORT, user=None, password=None,
[311] Fix | Delete
readermode=None, usenetrc=False,
[312] Fix | Delete
timeout=_GLOBAL_DEFAULT_TIMEOUT):
[313] Fix | Delete
"""Initialize an instance. Arguments:
[314] Fix | Delete
- host: hostname to connect to
[315] Fix | Delete
- port: port to connect to (default the standard NNTP port)
[316] Fix | Delete
- user: username to authenticate with
[317] Fix | Delete
- password: password to use with username
[318] Fix | Delete
- readermode: if true, send 'mode reader' command after
[319] Fix | Delete
connecting.
[320] Fix | Delete
- usenetrc: allow loading username and password from ~/.netrc file
[321] Fix | Delete
if not specified explicitly
[322] Fix | Delete
- timeout: timeout (in seconds) used for socket connections
[323] Fix | Delete
[324] Fix | Delete
readermode is sometimes necessary if you are connecting to an
[325] Fix | Delete
NNTP server on the local machine and intend to call
[326] Fix | Delete
reader-specific commands, such as `group'. If you get
[327] Fix | Delete
unexpected NNTPPermanentErrors, you might need to set
[328] Fix | Delete
readermode.
[329] Fix | Delete
"""
[330] Fix | Delete
self.host = host
[331] Fix | Delete
self.port = port
[332] Fix | Delete
self.sock = self._create_socket(timeout)
[333] Fix | Delete
self.file = None
[334] Fix | Delete
try:
[335] Fix | Delete
self.file = self.sock.makefile("rwb")
[336] Fix | Delete
self._base_init(readermode)
[337] Fix | Delete
if user or usenetrc:
[338] Fix | Delete
self.login(user, password, usenetrc)
[339] Fix | Delete
except:
[340] Fix | Delete
if self.file:
[341] Fix | Delete
self.file.close()
[342] Fix | Delete
self.sock.close()
[343] Fix | Delete
raise
[344] Fix | Delete
[345] Fix | Delete
def _base_init(self, readermode):
[346] Fix | Delete
"""Partial initialization for the NNTP protocol.
[347] Fix | Delete
This instance method is extracted for supporting the test code.
[348] Fix | Delete
"""
[349] Fix | Delete
self.debugging = 0
[350] Fix | Delete
self.welcome = self._getresp()
[351] Fix | Delete
[352] Fix | Delete
# Inquire about capabilities (RFC 3977).
[353] Fix | Delete
self._caps = None
[354] Fix | Delete
self.getcapabilities()
[355] Fix | Delete
[356] Fix | Delete
# 'MODE READER' is sometimes necessary to enable 'reader' mode.
[357] Fix | Delete
# However, the order in which 'MODE READER' and 'AUTHINFO' need to
[358] Fix | Delete
# arrive differs between some NNTP servers. If _setreadermode() fails
[359] Fix | Delete
# with an authorization failed error, it will set this to True;
[360] Fix | Delete
# the login() routine will interpret that as a request to try again
[361] Fix | Delete
# after performing its normal function.
[362] Fix | Delete
# Enable only if we're not already in READER mode anyway.
[363] Fix | Delete
self.readermode_afterauth = False
[364] Fix | Delete
if readermode and 'READER' not in self._caps:
[365] Fix | Delete
self._setreadermode()
[366] Fix | Delete
if not self.readermode_afterauth:
[367] Fix | Delete
# Capabilities might have changed after MODE READER
[368] Fix | Delete
self._caps = None
[369] Fix | Delete
self.getcapabilities()
[370] Fix | Delete
[371] Fix | Delete
# RFC 4642 2.2.2: Both the client and the server MUST know if there is
[372] Fix | Delete
# a TLS session active. A client MUST NOT attempt to start a TLS
[373] Fix | Delete
# session if a TLS session is already active.
[374] Fix | Delete
self.tls_on = False
[375] Fix | Delete
[376] Fix | Delete
# Log in and encryption setup order is left to subclasses.
[377] Fix | Delete
self.authenticated = False
[378] Fix | Delete
[379] Fix | Delete
def __enter__(self):
[380] Fix | Delete
return self
[381] Fix | Delete
[382] Fix | Delete
def __exit__(self, *args):
[383] Fix | Delete
is_connected = lambda: hasattr(self, "file")
[384] Fix | Delete
if is_connected():
[385] Fix | Delete
try:
[386] Fix | Delete
self.quit()
[387] Fix | Delete
except (OSError, EOFError):
[388] Fix | Delete
pass
[389] Fix | Delete
finally:
[390] Fix | Delete
if is_connected():
[391] Fix | Delete
self._close()
[392] Fix | Delete
[393] Fix | Delete
def _create_socket(self, timeout):
[394] Fix | Delete
if timeout is not None and not timeout:
[395] Fix | Delete
raise ValueError('Non-blocking socket (timeout=0) is not supported')
[396] Fix | Delete
sys.audit("nntplib.connect", self, self.host, self.port)
[397] Fix | Delete
return socket.create_connection((self.host, self.port), timeout)
[398] Fix | Delete
[399] Fix | Delete
def getwelcome(self):
[400] Fix | Delete
"""Get the welcome message from the server
[401] Fix | Delete
(this is read and squirreled away by __init__()).
[402] Fix | Delete
If the response code is 200, posting is allowed;
[403] Fix | Delete
if it 201, posting is not allowed."""
[404] Fix | Delete
[405] Fix | Delete
if self.debugging: print('*welcome*', repr(self.welcome))
[406] Fix | Delete
return self.welcome
[407] Fix | Delete
[408] Fix | Delete
def getcapabilities(self):
[409] Fix | Delete
"""Get the server capabilities, as read by __init__().
[410] Fix | Delete
If the CAPABILITIES command is not supported, an empty dict is
[411] Fix | Delete
returned."""
[412] Fix | Delete
if self._caps is None:
[413] Fix | Delete
self.nntp_version = 1
[414] Fix | Delete
self.nntp_implementation = None
[415] Fix | Delete
try:
[416] Fix | Delete
resp, caps = self.capabilities()
[417] Fix | Delete
except (NNTPPermanentError, NNTPTemporaryError):
[418] Fix | Delete
# Server doesn't support capabilities
[419] Fix | Delete
self._caps = {}
[420] Fix | Delete
else:
[421] Fix | Delete
self._caps = caps
[422] Fix | Delete
if 'VERSION' in caps:
[423] Fix | Delete
# The server can advertise several supported versions,
[424] Fix | Delete
# choose the highest.
[425] Fix | Delete
self.nntp_version = max(map(int, caps['VERSION']))
[426] Fix | Delete
if 'IMPLEMENTATION' in caps:
[427] Fix | Delete
self.nntp_implementation = ' '.join(caps['IMPLEMENTATION'])
[428] Fix | Delete
return self._caps
[429] Fix | Delete
[430] Fix | Delete
def set_debuglevel(self, level):
[431] Fix | Delete
"""Set the debugging level. Argument 'level' means:
[432] Fix | Delete
0: no debugging output (default)
[433] Fix | Delete
1: print commands and responses but not body text etc.
[434] Fix | Delete
2: also print raw lines read and sent before stripping CR/LF"""
[435] Fix | Delete
[436] Fix | Delete
self.debugging = level
[437] Fix | Delete
debug = set_debuglevel
[438] Fix | Delete
[439] Fix | Delete
def _putline(self, line):
[440] Fix | Delete
"""Internal: send one line to the server, appending CRLF.
[441] Fix | Delete
The `line` must be a bytes-like object."""
[442] Fix | Delete
sys.audit("nntplib.putline", self, line)
[443] Fix | Delete
line = line + _CRLF
[444] Fix | Delete
if self.debugging > 1: print('*put*', repr(line))
[445] Fix | Delete
self.file.write(line)
[446] Fix | Delete
self.file.flush()
[447] Fix | Delete
[448] Fix | Delete
def _putcmd(self, line):
[449] Fix | Delete
"""Internal: send one command to the server (through _putline()).
[450] Fix | Delete
The `line` must be a unicode string."""
[451] Fix | Delete
if self.debugging: print('*cmd*', repr(line))
[452] Fix | Delete
line = line.encode(self.encoding, self.errors)
[453] Fix | Delete
self._putline(line)
[454] Fix | Delete
[455] Fix | Delete
def _getline(self, strip_crlf=True):
[456] Fix | Delete
"""Internal: return one line from the server, stripping _CRLF.
[457] Fix | Delete
Raise EOFError if the connection is closed.
[458] Fix | Delete
Returns a bytes object."""
[459] Fix | Delete
line = self.file.readline(_MAXLINE +1)
[460] Fix | Delete
if len(line) > _MAXLINE:
[461] Fix | Delete
raise NNTPDataError('line too long')
[462] Fix | Delete
if self.debugging > 1:
[463] Fix | Delete
print('*get*', repr(line))
[464] Fix | Delete
if not line: raise EOFError
[465] Fix | Delete
if strip_crlf:
[466] Fix | Delete
if line[-2:] == _CRLF:
[467] Fix | Delete
line = line[:-2]
[468] Fix | Delete
elif line[-1:] in _CRLF:
[469] Fix | Delete
line = line[:-1]
[470] Fix | Delete
return line
[471] Fix | Delete
[472] Fix | Delete
def _getresp(self):
[473] Fix | Delete
"""Internal: get a response from the server.
[474] Fix | Delete
Raise various errors if the response indicates an error.
[475] Fix | Delete
Returns a unicode string."""
[476] Fix | Delete
resp = self._getline()
[477] Fix | Delete
if self.debugging: print('*resp*', repr(resp))
[478] Fix | Delete
resp = resp.decode(self.encoding, self.errors)
[479] Fix | Delete
c = resp[:1]
[480] Fix | Delete
if c == '4':
[481] Fix | Delete
raise NNTPTemporaryError(resp)
[482] Fix | Delete
if c == '5':
[483] Fix | Delete
raise NNTPPermanentError(resp)
[484] Fix | Delete
if c not in '123':
[485] Fix | Delete
raise NNTPProtocolError(resp)
[486] Fix | Delete
return resp
[487] Fix | Delete
[488] Fix | Delete
def _getlongresp(self, file=None):
[489] Fix | Delete
"""Internal: get a response plus following text from the server.
[490] Fix | Delete
Raise various errors if the response indicates an error.
[491] Fix | Delete
[492] Fix | Delete
Returns a (response, lines) tuple where `response` is a unicode
[493] Fix | Delete
string and `lines` is a list of bytes objects.
[494] Fix | Delete
If `file` is a file-like object, it must be open in binary mode.
[495] Fix | Delete
"""
[496] Fix | Delete
[497] Fix | Delete
openedFile = None
[498] Fix | Delete
try:
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function