Advertisement
Guest User

Untitled

a guest
May 19th, 2018
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 43.78 KB | None | 0 0
  1. # RFC 977 by Brian Kantor and Phil Lapsley.
  2. # xover, xgtitle, xpath, date methods by Kevan Heydon
  3.  
  4. # Incompatible changes from the 2.x nntplib:
  5. # - all commands are encoded as UTF-8 data (using the "surrogateescape"
  6. # error handler), except for raw message data (POST, IHAVE)
  7. # - all responses are decoded as UTF-8 data (using the "surrogateescape"
  8. # error handler), except for raw message data (ARTICLE, HEAD, BODY)
  9. # - the `file` argument to various methods is keyword-only
  10. #
  11. # - NNTP.date() returns a datetime object
  12. # - NNTP.newgroups() and NNTP.newnews() take a datetime (or date) object,
  13. # rather than a pair of (date, time) strings.
  14. # - NNTP.newgroups() and NNTP.list() return a list of GroupInfo named tuples
  15. # - NNTP.descriptions() returns a dict mapping group names to descriptions
  16. # - NNTP.xover() returns a list of dicts mapping field names (header or metadata)
  17. # to field values; each dict representing a message overview.
  18. # - NNTP.article(), NNTP.head() and NNTP.body() return a (response, ArticleInfo)
  19. # tuple.
  20. # - the "internal" methods have been marked private (they now start with
  21. # an underscore)
  22.  
  23. # Other changes from the 2.x/3.1 nntplib:
  24. # - automatic querying of capabilities at connect
  25. # - New method NNTP.getcapabilities()
  26. # - New method NNTP.over()
  27. # - New helper function decode_header()
  28. # - NNTP.post() and NNTP.ihave() accept file objects, bytes-like objects and
  29. # arbitrary iterables yielding lines.
  30. # - An extensive test suite :-)
  31.  
  32. # TODO:
  33. # - return structured data (GroupInfo etc.) everywhere
  34. # - support HDR
  35.  
  36. # Imports
  37. import re
  38. import socket
  39. import collections
  40. import datetime
  41. import warnings
  42. import asyncio
  43. from asyncio import sslproto
  44. from asyncio import StreamReader, StreamWriter, StreamReaderProtocol
  45.  
  46. try:
  47. import ssl
  48. except ImportError:
  49. _have_ssl = False
  50. else:
  51. _have_ssl = True
  52.  
  53. from email.header import decode_header as _email_decode_header
  54. from socket import _GLOBAL_DEFAULT_TIMEOUT
  55.  
  56.  
  57. __all__ = ["NNTP",
  58. "NNTPError", "NNTPReplyError", "NNTPTemporaryError",
  59. "NNTPPermanentError", "NNTPProtocolError", "NNTPDataError",
  60. "decode_header",
  61. ]
  62.  
  63. # maximal line length when calling readline(). This is to prevent
  64. # reading arbitrary length lines. RFC 3977 limits NNTP line length to
  65. # 512 characters, including CRLF. We have selected 2048 just to be on
  66. # the safe side.
  67. _MAXLINE = 2048
  68.  
  69.  
  70. # Exceptions raised when an error or invalid response is received
  71. class NNTPError(Exception):
  72. """Base class for all nntplib exceptions"""
  73. def __init__(self, *args):
  74. Exception.__init__(self, *args)
  75. try:
  76. self.response = args[0]
  77. except IndexError:
  78. self.response = 'No response given'
  79.  
  80. class NNTPReplyError(NNTPError):
  81. """Unexpected [123]xx reply"""
  82. pass
  83.  
  84. class NNTPTemporaryError(NNTPError):
  85. """4xx errors"""
  86. pass
  87.  
  88. class NNTPPermanentError(NNTPError):
  89. """5xx errors"""
  90. pass
  91.  
  92. class NNTPProtocolError(NNTPError):
  93. """Response does not begin with [1-5]"""
  94. pass
  95.  
  96. class NNTPDataError(NNTPError):
  97. """Error in response data"""
  98. pass
  99.  
  100.  
  101. # Standard port used by NNTP servers
  102. NNTP_PORT = 119
  103. NNTP_SSL_PORT = 563
  104.  
  105. # Response numbers that are followed by additional text (e.g. article)
  106. _LONGRESP = {
  107. '100', # HELP
  108. '101', # CAPABILITIES
  109. '211', # LISTGROUP (also not multi-line with GROUP)
  110. '215', # LIST
  111. '220', # ARTICLE
  112. '221', # HEAD, XHDR
  113. '222', # BODY
  114. '224', # OVER, XOVER
  115. '225', # HDR
  116. '230', # NEWNEWS
  117. '231', # NEWGROUPS
  118. '282', # XGTITLE
  119. }
  120.  
  121. # Default decoded value for LIST OVERVIEW.FMT if not supported
  122. _DEFAULT_OVERVIEW_FMT = [
  123. "subject", "from", "date", "message-id", "references", ":bytes", ":lines"]
  124.  
  125. # Alternative names allowed in LIST OVERVIEW.FMT response
  126. _OVERVIEW_FMT_ALTERNATIVES = {
  127. 'bytes': ':bytes',
  128. 'lines': ':lines',
  129. }
  130.  
  131. # Line terminators (we always output CRLF, but accept any of CRLF, CR, LF)
  132. _CRLF = b'\r\n'
  133.  
  134. GroupInfo = collections.namedtuple('GroupInfo',
  135. ['group', 'last', 'first', 'flag'])
  136.  
  137. ArticleInfo = collections.namedtuple('ArticleInfo',
  138. ['number', 'message_id', 'lines'])
  139.  
  140.  
  141. # Helper function(s)
  142. def decode_header(header_str):
  143. """Takes a unicode string representing a munged header value
  144. and decodes it as a (possibly non-ASCII) readable value."""
  145. parts = []
  146. for v, enc in _email_decode_header(header_str):
  147. if isinstance(v, bytes):
  148. parts.append(v.decode(enc or 'ascii'))
  149. else:
  150. parts.append(v)
  151. return ''.join(parts)
  152.  
  153. def _parse_overview_fmt(lines):
  154. """Parse a list of string representing the response to LIST OVERVIEW.FMT
  155. and return a list of header/metadata names.
  156. Raises NNTPDataError if the response is not compliant
  157. (cf. RFC 3977, section 8.4)."""
  158. fmt = []
  159. for line in lines:
  160. if line[0] == ':':
  161. # Metadata name (e.g. ":bytes")
  162. name, _, suffix = line[1:].partition(':')
  163. name = ':' + name
  164. else:
  165. # Header name (e.g. "Subject:" or "Xref:full")
  166. name, _, suffix = line.partition(':')
  167. name = name.lower()
  168. name = _OVERVIEW_FMT_ALTERNATIVES.get(name, name)
  169. # Should we do something with the suffix?
  170. fmt.append(name)
  171. defaults = _DEFAULT_OVERVIEW_FMT
  172. if len(fmt) < len(defaults):
  173. raise NNTPDataError("LIST OVERVIEW.FMT response too short")
  174. if fmt[:len(defaults)] != defaults:
  175. raise NNTPDataError("LIST OVERVIEW.FMT redefines default fields")
  176. return fmt
  177.  
  178. def _parse_overview(lines, fmt, data_process_func=None):
  179. """Parse the response to an OVER or XOVER command according to the
  180. overview format `fmt`."""
  181. n_defaults = len(_DEFAULT_OVERVIEW_FMT)
  182. overview = []
  183. for line in lines:
  184. fields = {}
  185. article_number, *tokens = line.split('\t')
  186. article_number = int(article_number)
  187. for i, token in enumerate(tokens):
  188. if i >= len(fmt):
  189. # XXX should we raise an error? Some servers might not
  190. # support LIST OVERVIEW.FMT and still return additional
  191. # headers.
  192. continue
  193. field_name = fmt[i]
  194. is_metadata = field_name.startswith(':')
  195. if i >= n_defaults and not is_metadata:
  196. # Non-default header names are included in full in the response
  197. # (unless the field is totally empty)
  198. h = field_name + ": "
  199. if token and token[:len(h)].lower() != h:
  200. raise NNTPDataError("OVER/XOVER response doesn't include "
  201. "names of additional headers")
  202. token = token[len(h):] if token else None
  203. fields[fmt[i]] = token
  204. overview.append((article_number, fields))
  205. return overview
  206.  
  207. def _parse_datetime(date_str, time_str=None):
  208. """Parse a pair of (date, time) strings, and return a datetime object.
  209. If only the date is given, it is assumed to be date and time
  210. concatenated together (e.g. response to the DATE command).
  211. """
  212. if time_str is None:
  213. time_str = date_str[-6:]
  214. date_str = date_str[:-6]
  215. hours = int(time_str[:2])
  216. minutes = int(time_str[2:4])
  217. seconds = int(time_str[4:])
  218. year = int(date_str[:-4])
  219. month = int(date_str[-4:-2])
  220. day = int(date_str[-2:])
  221. # RFC 3977 doesn't say how to interpret 2-char years. Assume that
  222. # there are no dates before 1970 on Usenet.
  223. if year < 70:
  224. year += 2000
  225. elif year < 100:
  226. year += 1900
  227. return datetime.datetime(year, month, day, hours, minutes, seconds)
  228.  
  229. def _unparse_datetime(dt, legacy=False):
  230. """Format a date or datetime object as a pair of (date, time) strings
  231. in the format required by the NEWNEWS and NEWGROUPS commands. If a
  232. date object is passed, the time is assumed to be midnight (00h00).
  233.  
  234. The returned representation depends on the legacy flag:
  235. * if legacy is False (the default):
  236. date has the YYYYMMDD format and time the HHMMSS format
  237. * if legacy is True:
  238. date has the YYMMDD format and time the HHMMSS format.
  239. RFC 3977 compliant servers should understand both formats; therefore,
  240. legacy is only needed when talking to old servers.
  241. """
  242. if not isinstance(dt, datetime.datetime):
  243. time_str = "000000"
  244. else:
  245. time_str = "{0.hour:02d}{0.minute:02d}{0.second:02d}".format(dt)
  246. y = dt.year
  247. if legacy:
  248. y = y % 100
  249. date_str = "{0:02d}{1.month:02d}{1.day:02d}".format(y, dt)
  250. else:
  251. date_str = "{0:04d}{1.month:02d}{1.day:02d}".format(y, dt)
  252. return date_str, time_str
  253.  
  254.  
  255. if _have_ssl:
  256.  
  257. def _encrypt_on(transport, context, hostname):
  258. """Wrap a socket in SSL/TLS. Arguments:
  259. - sock: Socket to wrap
  260. - context: SSL context to use for the encrypted connection
  261. Returns:
  262. - sock: New, encrypted socket.
  263. """
  264. # Generate a default SSL context if none was passed.
  265. if context is None:
  266. context = ssl._create_stdlib_context()
  267. return context.wrap_socket(sock, server_hostname=hostname)
  268.  
  269.  
  270. # The classes themselves
  271. class _NNTPBase:
  272. # UTF-8 is the character set for all NNTP commands and responses: they
  273. # are automatically encoded (when sending) and decoded (and receiving)
  274. # by this class.
  275. # However, some multi-line data blocks can contain arbitrary bytes (for
  276. # example, latin-1 or utf-16 data in the body of a message). Commands
  277. # taking (POST, IHAVE) or returning (HEAD, BODY, ARTICLE) raw message
  278. # data will therefore only accept and produce bytes objects.
  279. # Furthermore, since there could be non-compliant servers out there,
  280. # we use 'surrogateescape' as the error handler for fault tolerance
  281. # and easy round-tripping. This could be useful for some applications
  282. # (e.g. NNTP gateways).
  283.  
  284. encoding = 'utf-8'
  285. errors = 'surrogateescape'
  286.  
  287. @classmethod
  288. async def create(cls, reader, writer, host,
  289. readermode=None, timeout=_GLOBAL_DEFAULT_TIMEOUT):
  290. """Initialize an instance. Arguments:
  291. - file: file-like object (open for read/write in binary mode)
  292. - host: hostname of the server
  293. - readermode: if true, send 'mode reader' command after
  294. connecting.
  295. - timeout: timeout (in seconds) used for socket connections
  296.  
  297. readermode is sometimes necessary if you are connecting to an
  298. NNTP server on the local machine and intend to call
  299. reader-specific commands, such as `group'. If you get
  300. unexpected NNTPPermanentErrors, you might need to set
  301. readermode.
  302. """
  303. self = _NNTPBase()
  304.  
  305. self.host = host
  306. self.reader = reader
  307. self.writer = writer
  308. self.debugging = 0
  309. self.welcome = await self._getresp()
  310.  
  311. # Inquire about capabilities (RFC 3977).
  312. self._caps = None
  313. await self.getcapabilities()
  314.  
  315. # 'MODE READER' is sometimes necessary to enable 'reader' mode.
  316. # However, the order in which 'MODE READER' and 'AUTHINFO' need to
  317. # arrive differs between some NNTP servers. If _setreadermode() fails
  318. # with an authorization failed error, it will set this to True;
  319. # the login() routine will interpret that as a request to try again
  320. # after performing its normal function.
  321. # Enable only if we're not already in READER mode anyway.
  322. self.readermode_afterauth = False
  323. if readermode and 'READER' not in self._caps:
  324. await self._setreadermode()
  325. if not self.readermode_afterauth:
  326. # Capabilities might have changed after MODE READER
  327. self._caps = None
  328. await self.getcapabilities()
  329.  
  330. # RFC 4642 2.2.2: Both the client and the server MUST know if there is
  331. # a TLS session active. A client MUST NOT attempt to start a TLS
  332. # session if a TLS session is already active.
  333. self.tls_on = False
  334.  
  335. # Log in and encryption setup order is left to subclasses.
  336. self.authenticated = False
  337.  
  338. return self
  339.  
  340. def __enter__(self):
  341. return self
  342.  
  343. def __exit__(self, *args):
  344. is_connected = lambda: hasattr(self, "writer")
  345. if is_connected():
  346. try:
  347. self.quit()
  348. except (OSError, EOFError):
  349. pass
  350. finally:
  351. if is_connected():
  352. self._close()
  353.  
  354. async def getwelcome(self):
  355. """Get the welcome message from the server
  356. (this is read and squirreled away by __init__()).
  357. If the response code is 200, posting is allowed;
  358. if it 201, posting is not allowed."""
  359.  
  360. if self.debugging: print('*welcome*', repr(await self.welcome))
  361. return await self.welcome
  362.  
  363. async def getcapabilities(self):
  364. """Get the server capabilities, as read by __init__().
  365. If the CAPABILITIES command is not supported, an empty dict is
  366. returned."""
  367. if self._caps is None:
  368. self.nntp_version = 1
  369. self.nntp_implementation = None
  370. try:
  371. resp, caps = await self.capabilities()
  372. except (NNTPPermanentError, NNTPTemporaryError):
  373. # Server doesn't support capabilities
  374. self._caps = {}
  375. else:
  376. self._caps = caps
  377. if 'VERSION' in caps:
  378. # The server can advertise several supported versions,
  379. # choose the highest.
  380. self.nntp_version = max(map(int, caps['VERSION']))
  381. if 'IMPLEMENTATION' in caps:
  382. self.nntp_implementation = ' '.join(caps['IMPLEMENTATION'])
  383. return self._caps
  384.  
  385. def set_debuglevel(self, level):
  386. """Set the debugging level. Argument 'level' means:
  387. 0: no debugging output (default)
  388. 1: print commands and responses but not body text etc.
  389. 2: also print raw lines read and sent before stripping CR/LF"""
  390.  
  391. self.debugging = level
  392. debug = set_debuglevel
  393.  
  394. async def _putline(self, line):
  395. """Internal: send one line to the server, appending CRLF.
  396. The `line` must be a bytes-like object."""
  397. line = line + _CRLF
  398. if self.debugging > 1: print('*put*', repr(line))
  399. self.writer.write(line)
  400. await self.writer.drain()
  401.  
  402. async def _putcmd(self, line):
  403. """Internal: send one command to the server (through _putline()).
  404. The `line` must be a unicode string."""
  405. if self.debugging: print('*cmd*', repr(line))
  406. line = line.encode(self.encoding, self.errors)
  407. await self._putline(line)
  408.  
  409. async def _getline(self, strip_crlf=True):
  410. """Internal: return one line from the server, stripping _CRLF.
  411. Raise EOFError if the connection is closed.
  412. Returns a bytes object."""
  413. line = await self.reader.readline()
  414. if len(line) > _MAXLINE:
  415. raise NNTPDataError('line too long')
  416. if self.debugging > 1:
  417. print('*get*', repr(line))
  418. if not line: raise EOFError
  419. if strip_crlf:
  420. if line[-2:] == _CRLF:
  421. line = line[:-2]
  422. elif line[-1:] in _CRLF:
  423. line = line[:-1]
  424. return line
  425.  
  426. async def _getresp(self):
  427. """Internal: get a response from the server.
  428. Raise various errors if the response indicates an error.
  429. Returns a unicode string."""
  430. resp = await self._getline()
  431. if self.debugging: print('*resp*', repr(resp))
  432. resp = resp.decode(self.encoding, self.errors)
  433. c = resp[:1]
  434. if c == '4':
  435. raise NNTPTemporaryError(resp)
  436. if c == '5':
  437. raise NNTPPermanentError(resp)
  438. if c not in '123':
  439. raise NNTPProtocolError(resp)
  440. return resp
  441.  
  442. async def _getlongresp(self, file=None):
  443. """Internal: get a response plus following text from the server.
  444. Raise various errors if the response indicates an error.
  445.  
  446. Returns a (response, lines) tuple where `response` is a unicode
  447. string and `lines` is a list of bytes objects.
  448. If `file` is a file-like object, it must be open in binary mode.
  449. """
  450.  
  451. openedFile = None
  452. try:
  453. # If a string was passed then open a file with that name
  454. if isinstance(file, (str, bytes)):
  455. openedFile = file = open(file, "wb")
  456.  
  457. resp = await self._getresp()
  458. if resp[:3] not in _LONGRESP:
  459. pass #raise NNTPReplyError(resp)
  460.  
  461. lines = []
  462. if file is not None:
  463. # XXX lines = None instead?
  464. terminators = (b'.' + _CRLF, b'.\n')
  465. while 1:
  466. line = await self._getline(False)
  467. if line in terminators:
  468. break
  469. if line.startswith(b'..'):
  470. line = line[1:]
  471. file.write(line)
  472. else:
  473. terminator = b'.'
  474. while 1:
  475. line = await self._getline()
  476. if line == terminator:
  477. break
  478. if line.startswith(b'..'):
  479. line = line[1:]
  480. lines.append(line)
  481. finally:
  482. # If this method created the file, then it must close it
  483. if openedFile:
  484. openedFile.close()
  485.  
  486. return resp, lines
  487.  
  488. async def _shortcmd(self, line):
  489. """Internal: send a command and get the response.
  490. Same return value as _getresp()."""
  491. await self._putcmd(line)
  492. return await self._getresp()
  493.  
  494. async def _longcmd(self, line, file=None):
  495. """Internal: send a command and get the response plus following text.
  496. Same return value as _getlongresp()."""
  497. await self._putcmd(line)
  498. return await self._getlongresp(file)
  499.  
  500. async def _longcmdstring(self, line, file=None):
  501. """Internal: send a command and get the response plus following text.
  502. Same as _longcmd() and _getlongresp(), except that the returned `lines`
  503. are unicode strings rather than bytes objects.
  504. """
  505. await self._putcmd(line)
  506. resp, list = await self._getlongresp(file)
  507. return resp, [line.decode(self.encoding, self.errors)
  508. for line in list]
  509.  
  510. async def _getoverviewfmt(self):
  511. """Internal: get the overview format. Queries the server if not
  512. already done, else returns the cached value."""
  513. try:
  514. return self._cachedoverviewfmt
  515. except AttributeError:
  516. pass
  517. try:
  518. resp, lines = await self._longcmdstring("LIST OVERVIEW.FMT")
  519. except NNTPPermanentError:
  520. # Not supported by server?
  521. fmt = _DEFAULT_OVERVIEW_FMT[:]
  522. else:
  523. fmt = _parse_overview_fmt(lines)
  524. self._cachedoverviewfmt = fmt
  525. return fmt
  526.  
  527. def _grouplist(self, lines):
  528. # Parse lines into "group last first flag"
  529. return [GroupInfo(*line.split()) for line in lines]
  530.  
  531. async def capabilities(self):
  532. """Process a CAPABILITIES command. Not supported by all servers.
  533. Return:
  534. - resp: server response if successful
  535. - caps: a dictionary mapping capability names to lists of tokens
  536. (for example {'VERSION': ['2'], 'OVER': [], LIST: ['ACTIVE', 'HEADERS'] })
  537. """
  538. caps = {}
  539. resp, lines = await self._longcmdstring("CAPABILITIES")
  540. for line in lines:
  541. name, *tokens = line.split()
  542. caps[name] = tokens
  543. return resp, caps
  544.  
  545. async def newgroups(self, date, *, file=None):
  546. """Process a NEWGROUPS command. Arguments:
  547. - date: a date or datetime object
  548. Return:
  549. - resp: server response if successful
  550. - list: list of newsgroup names
  551. """
  552. if not isinstance(date, (datetime.date, datetime.date)):
  553. raise TypeError(
  554. "the date parameter must be a date or datetime object, "
  555. "not '{:40}'".format(date.__class__.__name__))
  556. date_str, time_str = _unparse_datetime(date, self.nntp_version < 2)
  557. cmd = 'NEWGROUPS {0} {1}'.format(date_str, time_str)
  558. resp, lines = await self._longcmdstring(cmd, file)
  559. return resp, self._grouplist(lines)
  560.  
  561. async def newnews(self, group, date, *, file=None):
  562. """Process a NEWNEWS command. Arguments:
  563. - group: group name or '*'
  564. - date: a date or datetime object
  565. Return:
  566. - resp: server response if successful
  567. - list: list of message ids
  568. """
  569. if not isinstance(date, (datetime.date, datetime.date)):
  570. raise TypeError(
  571. "the date parameter must be a date or datetime object, "
  572. "not '{:40}'".format(date.__class__.__name__))
  573. date_str, time_str = _unparse_datetime(date, self.nntp_version < 2)
  574. cmd = 'NEWNEWS {0} {1} {2}'.format(group, date_str, time_str)
  575. return await self._longcmdstring(cmd, file)
  576.  
  577. async def list(self, group_pattern=None, *, file=None):
  578. """Process a LIST or LIST ACTIVE command. Arguments:
  579. - group_pattern: a pattern indicating which groups to query
  580. - file: Filename string or file object to store the result in
  581. Returns:
  582. - resp: server response if successful
  583. - list: list of (group, last, first, flag) (strings)
  584. """
  585. if group_pattern is not None:
  586. command = 'LIST ACTIVE ' + group_pattern
  587. else:
  588. command = 'LIST'
  589. resp, lines = await self._longcmdstring(command, file)
  590. return resp, self._grouplist(lines)
  591.  
  592. async def _getdescriptions(self, group_pattern, return_all):
  593. line_pat = re.compile('^(?P<group>[^ \t]+)[ \t]+(.*)$')
  594. # Try the more std (acc. to RFC2980) LIST NEWSGROUPS first
  595. resp, lines = await self._longcmdstring('LIST NEWSGROUPS ' + group_pattern)
  596. if not resp.startswith('215'):
  597. # Now the deprecated XGTITLE. This either raises an error
  598. # or succeeds with the same output structure as LIST
  599. # NEWSGROUPS.
  600. resp, lines = await self._longcmdstring('XGTITLE ' + group_pattern)
  601. groups = {}
  602. for raw_line in lines:
  603. match = line_pat.search(raw_line.strip())
  604. if match:
  605. name, desc = match.group(1, 2)
  606. if not return_all:
  607. return desc
  608. groups[name] = desc
  609. if return_all:
  610. return resp, groups
  611. else:
  612. # Nothing found
  613. return ''
  614.  
  615. async def description(self, group):
  616. """Get a description for a single group. If more than one
  617. group matches ('group' is a pattern), return the first. If no
  618. group matches, return an empty string.
  619.  
  620. This elides the response code from the server, since it can
  621. only be '215' or '285' (for xgtitle) anyway. If the response
  622. code is needed, use the 'descriptions' method.
  623.  
  624. NOTE: This neither checks for a wildcard in 'group' nor does
  625. it check whether the group actually exists."""
  626. return await self._getdescriptions(group, False)
  627.  
  628. async def descriptions(self, group_pattern):
  629. """Get descriptions for a range of groups."""
  630. return await self._getdescriptions(group_pattern, True)
  631.  
  632. async def group(self, name):
  633. """Process a GROUP command. Argument:
  634. - group: the group name
  635. Returns:
  636. - resp: server response if successful
  637. - count: number of articles
  638. - first: first article number
  639. - last: last article number
  640. - name: the group name
  641. """
  642. resp = await self._shortcmd('GROUP ' + name)
  643. if not resp.startswith('211'):
  644. raise NNTPReplyError(resp)
  645. words = resp.split()
  646. count = first = last = 0
  647. n = len(words)
  648. if n > 1:
  649. count = words[1]
  650. if n > 2:
  651. first = words[2]
  652. if n > 3:
  653. last = words[3]
  654. if n > 4:
  655. name = words[4].lower()
  656. return resp, int(count), int(first), int(last), name
  657.  
  658. async def help(self, *, file=None):
  659. """Process a HELP command. Argument:
  660. - file: Filename string or file object to store the result in
  661. Returns:
  662. - resp: server response if successful
  663. - list: list of strings returned by the server in response to the
  664. HELP command
  665. """
  666. return await self._longcmdstring('HELP', file)
  667.  
  668. def _statparse(self, resp):
  669. """Internal: parse the response line of a STAT, NEXT, LAST,
  670. ARTICLE, HEAD or BODY command."""
  671. if not resp.startswith('22'):
  672. raise NNTPReplyError(resp)
  673. words = resp.split()
  674. art_num = int(words[1])
  675. message_id = words[2]
  676. return resp, art_num, message_id
  677.  
  678. async def _statcmd(self, line):
  679. """Internal: process a STAT, NEXT or LAST command."""
  680. resp = await self._shortcmd(line)
  681. return self._statparse(resp)
  682.  
  683. async def stat(self, message_spec=None):
  684. """Process a STAT command. Argument:
  685. - message_spec: article number or message id (if not specified,
  686. the current article is selected)
  687. Returns:
  688. - resp: server response if successful
  689. - art_num: the article number
  690. - message_id: the message id
  691. """
  692. if message_spec:
  693. return await self._statcmd('STAT {0}'.format(message_spec))
  694. else:
  695. return await self._statcmd('STAT')
  696.  
  697. async def next(self):
  698. """Process a NEXT command. No arguments. Return as for STAT."""
  699. return await self._statcmd('NEXT')
  700.  
  701. async def last(self):
  702. """Process a LAST command. No arguments. Return as for STAT."""
  703. return await self._statcmd('LAST')
  704.  
  705. async def _artcmd(self, line, file=None):
  706. """Internal: process a HEAD, BODY or ARTICLE command."""
  707. resp, lines = await self._longcmd(line, file)
  708. resp, art_num, message_id = self._statparse(resp)
  709. return resp, ArticleInfo(art_num, message_id, lines)
  710.  
  711. async def head(self, message_spec=None, *, file=None):
  712. """Process a HEAD command. Argument:
  713. - message_spec: article number or message id
  714. - file: filename string or file object to store the headers in
  715. Returns:
  716. - resp: server response if successful
  717. - ArticleInfo: (article number, message id, list of header lines)
  718. """
  719. if message_spec is not None:
  720. cmd = 'HEAD {0}'.format(message_spec)
  721. else:
  722. cmd = 'HEAD'
  723. return await self._artcmd(cmd, file)
  724.  
  725. async def body(self, message_spec=None, *, file=None):
  726. """Process a BODY command. Argument:
  727. - message_spec: article number or message id
  728. - file: filename string or file object to store the body in
  729. Returns:
  730. - resp: server response if successful
  731. - ArticleInfo: (article number, message id, list of body lines)
  732. """
  733. if message_spec is not None:
  734. cmd = 'BODY {0}'.format(message_spec)
  735. else:
  736. cmd = 'BODY'
  737. return await self._artcmd(cmd, file)
  738.  
  739. async def article(self, message_spec=None, *, file=None):
  740. """Process an ARTICLE command. Argument:
  741. - message_spec: article number or message id
  742. - file: filename string or file object to store the article in
  743. Returns:
  744. - resp: server response if successful
  745. - ArticleInfo: (article number, message id, list of article lines)
  746. """
  747. if message_spec is not None:
  748. cmd = 'ARTICLE {0}'.format(message_spec)
  749. else:
  750. cmd = 'ARTICLE'
  751. return await self._artcmd(cmd, file)
  752.  
  753. async def slave(self):
  754. """Process a SLAVE command. Returns:
  755. - resp: server response if successful
  756. """
  757. return await self._shortcmd('SLAVE')
  758.  
  759. async def xhdr(self, hdr, str, *, file=None):
  760. """Process an XHDR command (optional server extension). Arguments:
  761. - hdr: the header type (e.g. 'subject')
  762. - str: an article nr, a message id, or a range nr1-nr2
  763. - file: Filename string or file object to store the result in
  764. Returns:
  765. - resp: server response if successful
  766. - list: list of (nr, value) strings
  767. """
  768. pat = re.compile('^([0-9]+) ?(.*)\n?')
  769. resp, lines = await self._longcmdstring('XHDR {0} {1}'.format(hdr, str), file)
  770. def remove_number(line):
  771. m = pat.match(line)
  772. return m.group(1, 2) if m else line
  773. return resp, [remove_number(line) for line in lines]
  774.  
  775. async def xover(self, start, end, *, file=None):
  776. """Process an XOVER command (optional server extension) Arguments:
  777. - start: start of range
  778. - end: end of range
  779. - file: Filename string or file object to store the result in
  780. Returns:
  781. - resp: server response if successful
  782. - list: list of dicts containing the response fields
  783. """
  784. resp, lines = await self._longcmdstring('XOVER {0}-{1}'.format(start, end),
  785. file)
  786. fmt = await self._getoverviewfmt()
  787. return resp, _parse_overview(lines, fmt)
  788.  
  789. async def over(self, message_spec, *, file=None):
  790. """Process an OVER command. If the command isn't supported, fall
  791. back to XOVER. Arguments:
  792. - message_spec:
  793. - either a message id, indicating the article to fetch
  794. information about
  795. - or a (start, end) tuple, indicating a range of article numbers;
  796. if end is None, information up to the newest message will be
  797. retrieved
  798. - or None, indicating the current article number must be used
  799. - file: Filename string or file object to store the result in
  800. Returns:
  801. - resp: server response if successful
  802. - list: list of dicts containing the response fields
  803.  
  804. NOTE: the "message id" form isn't supported by XOVER
  805. """
  806. cmd = 'OVER' if 'OVER' in self._caps else 'XOVER'
  807. if isinstance(message_spec, (tuple, list)):
  808. start, end = message_spec
  809. cmd += ' {0}-{1}'.format(start, end or '')
  810. elif message_spec is not None:
  811. cmd = cmd + ' ' + message_spec
  812. resp, lines = await self._longcmdstring(cmd, file)
  813. fmt = await self._getoverviewfmt()
  814. return resp, _parse_overview(lines, fmt)
  815.  
  816. async def xgtitle(self, group, *, file=None):
  817. """Process an XGTITLE command (optional server extension) Arguments:
  818. - group: group name wildcard (i.e. news.*)
  819. Returns:
  820. - resp: server response if successful
  821. - list: list of (name,title) strings"""
  822. warnings.warn("The XGTITLE extension is not actively used, "
  823. "use descriptions() instead",
  824. DeprecationWarning, 2)
  825. line_pat = re.compile('^([^ \t]+)[ \t]+(.*)$')
  826. resp, raw_lines = await self._longcmdstring('XGTITLE ' + group, file)
  827. lines = []
  828. for raw_line in raw_lines:
  829. match = line_pat.search(raw_line.strip())
  830. if match:
  831. lines.append(match.group(1, 2))
  832. return resp, lines
  833.  
  834. async def xpath(self, id):
  835. """Process an XPATH command (optional server extension) Arguments:
  836. - id: Message id of article
  837. Returns:
  838. resp: server response if successful
  839. path: directory path to article
  840. """
  841. warnings.warn("The XPATH extension is not actively used",
  842. DeprecationWarning, 2)
  843.  
  844. resp = await self._shortcmd('XPATH {0}'.format(id))
  845. if not resp.startswith('223'):
  846. raise NNTPReplyError(resp)
  847. try:
  848. [resp_num, path] = resp.split()
  849. except ValueError:
  850. raise NNTPReplyError(resp)
  851. else:
  852. return resp, path
  853.  
  854. async def date(self):
  855. """Process the DATE command.
  856. Returns:
  857. - resp: server response if successful
  858. - date: datetime object
  859. """
  860. resp = await self._shortcmd("DATE")
  861. if not resp.startswith('111'):
  862. raise NNTPReplyError(resp)
  863. elem = resp.split()
  864. if len(elem) != 2:
  865. raise NNTPDataError(resp)
  866. date = elem[1]
  867. if len(date) != 14:
  868. raise NNTPDataError(resp)
  869. return resp, _parse_datetime(date, None)
  870.  
  871. async def _post(self, command, f):
  872. resp = await self._shortcmd(command)
  873. # Raises a specific exception if posting is not allowed
  874. if not resp.startswith('3'):
  875. raise NNTPReplyError(resp)
  876. if isinstance(f, (bytes, bytearray)):
  877. f = f.splitlines()
  878. # We don't use _putline() because:
  879. # - we don't want additional CRLF if the file or iterable is already
  880. # in the right format
  881. # - we don't want a spurious flush() after each line is written
  882. for line in f:
  883. if not line.endswith(_CRLF):
  884. line = line.rstrip(b"\r\n") + _CRLF
  885. if line.startswith(b'.'):
  886. line = b'.' + line
  887. await self.writer.write(line)
  888. self.writer.write(b".\r\n")
  889. await self.writer.drain()
  890. return await self._getresp()
  891.  
  892. async def post(self, data):
  893. """Process a POST command. Arguments:
  894. - data: bytes object, iterable or file containing the article
  895. Returns:
  896. - resp: server response if successful"""
  897. return await self._post('POST', data)
  898.  
  899. async def ihave(self, message_id, data):
  900. """Process an IHAVE command. Arguments:
  901. - message_id: message-id of the article
  902. - data: file containing the article
  903. Returns:
  904. - resp: server response if successful
  905. Note that if the server refuses the article an exception is raised."""
  906. return await self._post('IHAVE {0}'.format(message_id), data)
  907.  
  908. def _close(self):
  909. self.writer.close()
  910. del self.writer
  911. del self.reader
  912.  
  913. async def quit(self):
  914. """Process a QUIT command and close the socket. Returns:
  915. - resp: server response if successful"""
  916. try:
  917. resp = await self._shortcmd('QUIT')
  918. finally:
  919. self._close()
  920. return resp
  921.  
  922. async def login(self, user=None, password=None, usenetrc=True):
  923. if self.authenticated:
  924. raise ValueError("Already logged in.")
  925. if not user and not usenetrc:
  926. raise ValueError(
  927. "At least one of `user` and `usenetrc` must be specified")
  928. # If no login/password was specified but netrc was requested,
  929. # try to get them from ~/.netrc
  930. # Presume that if .netrc has an entry, NNRP authentication is required.
  931. try:
  932. if usenetrc and not user:
  933. import netrc
  934. credentials = netrc.netrc()
  935. auth = credentials.authenticators(self.host)
  936. if auth:
  937. user = auth[0]
  938. password = auth[2]
  939. except OSError:
  940. pass
  941. # Perform NNTP authentication if needed.
  942. if not user:
  943. return
  944. resp = await self._shortcmd('authinfo user ' + user)
  945. if resp.startswith('381'):
  946. if not password:
  947. raise NNTPReplyError(resp)
  948. else:
  949. resp = await self._shortcmd('authinfo pass ' + password)
  950. if not resp.startswith('281'):
  951. raise NNTPPermanentError(resp)
  952. # Capabilities might have changed after login
  953. self._caps = None
  954. await self.getcapabilities()
  955. # Attempt to send mode reader if it was requested after login.
  956. # Only do so if we're not in reader mode already.
  957. if self.readermode_afterauth and 'READER' not in self._caps:
  958. await self._setreadermode()
  959. # Capabilities might have changed after MODE READER
  960. self._caps = None
  961. await self.getcapabilities()
  962.  
  963. async def _setreadermode(self):
  964. try:
  965. self.welcome = await self._shortcmd('mode reader')
  966. except NNTPPermanentError:
  967. # Error 5xx, probably 'not implemented'
  968. pass
  969. except NNTPTemporaryError as e:
  970. if e.response.startswith('480'):
  971. # Need authorization before 'mode reader'
  972. self.readermode_afterauth = True
  973. else:
  974. raise
  975.  
  976. if _have_ssl:
  977. async def starttls(self, context=None):
  978. """Process a STARTTLS command. Arguments:
  979. - context: SSL context to use for the encrypted connection
  980. """
  981. # Per RFC 4642, STARTTLS MUST NOT be sent after authentication or if
  982. # a TLS session already exists.
  983. if self.tls_on:
  984. raise ValueError("TLS is already enabled.")
  985. if self.authenticated:
  986. raise ValueError("TLS cannot be started after authentication.")
  987. resp = await self._shortcmd('STARTTLS')
  988. if resp.startswith('382'):
  989. if context is None:
  990. context = ssl._create_stdlib_context()
  991.  
  992. waiter = self.loop.create_future()
  993. self.reader = StreamReader(limit=2 ** 16, loop=self.loop)
  994. self.protocol = StreamReaderProtocol(self.reader, loop=self.loop)
  995. ssl_protocol = sslproto.SSLProtocol(
  996. self.loop, self.protocol, context, waiter,
  997. False, self.host)
  998. self.transport.set_protocol(ssl_protocol)
  999. ssl_protocol.connection_made(self.transport)
  1000. await waiter
  1001. self.transport = ssl_protocol._app_transport
  1002. self.writer = StreamWriter(self.transport, self.protocol, self.reader, self.loop)
  1003.  
  1004. self.tls_on = True
  1005. # Capabilities may change after TLS starts up, so ask for them
  1006. # again.
  1007. self._caps = None
  1008. await self.getcapabilities()
  1009. else:
  1010. raise NNTPError("TLS failed to start.")
  1011.  
  1012.  
  1013. class AIO_NNTP(_NNTPBase):
  1014.  
  1015. @classmethod
  1016. async def create(cls, host, port=NNTP_PORT, user=None, password=None,
  1017. readermode=None, usenetrc=False,
  1018. timeout=_GLOBAL_DEFAULT_TIMEOUT):
  1019. """Initialize an instance. Arguments:
  1020. - host: hostname to connect to
  1021. - port: port to connect to (default the standard NNTP port)
  1022. - user: username to authenticate with
  1023. - password: password to use with username
  1024. - readermode: if true, send 'mode reader' command after
  1025. connecting.
  1026. - usenetrc: allow loading username and password from ~/.netrc file
  1027. if not specified explicitly
  1028. - timeout: timeout (in seconds) used for socket connections
  1029.  
  1030. readermode is sometimes necessary if you are connecting to an
  1031. NNTP server on the local machine and intend to call
  1032. reader-specific commands, such as `group'. If you get
  1033. unexpected NNTPPermanentErrors, you might need to set
  1034. readermode.
  1035. """
  1036. loop = asyncio.get_event_loop()
  1037. reader = StreamReader(limit=2**16, loop=loop)
  1038. protocol = StreamReaderProtocol(reader, loop=loop)
  1039. transport, _ = await loop.create_connection(
  1040. lambda: protocol, host, port)
  1041. writer = StreamWriter(transport, protocol, reader, loop)
  1042. try:
  1043. self = await _NNTPBase.create(reader, writer, host,
  1044. readermode, timeout)
  1045. self.host = host
  1046. self.reader, self.writer = reader, writer
  1047. self.transport = transport
  1048. self.loop = loop
  1049. self.protocol = protocol
  1050. if user or usenetrc:
  1051. await self.login(user, password, usenetrc)
  1052. except:
  1053. if writer:
  1054. writer.close()
  1055. raise
  1056. return self
  1057.  
  1058. def _close(self):
  1059. try:
  1060. _NNTPBase._close(self)
  1061. finally:
  1062. self.writer.close()
  1063.  
  1064.  
  1065. if _have_ssl:
  1066. class AIO_NNTP_SSL(_NNTPBase):
  1067.  
  1068. @classmethod
  1069. async def create(cls, host, port=NNTP_SSL_PORT,
  1070. user=None, password=None, ssl_context=None,
  1071. readermode=None, usenetrc=False,
  1072. timeout=_GLOBAL_DEFAULT_TIMEOUT):
  1073. """This works identically to NNTP.__init__, except for the change
  1074. in default port and the `ssl_context` argument for SSL connections.
  1075. """
  1076.  
  1077. loop = asyncio.get_event_loop()
  1078. reader = StreamReader(limit=2 ** 16, loop=loop)
  1079. protocol = StreamReaderProtocol(reader, loop=loop)
  1080.  
  1081. try:
  1082. if ssl_context is None:
  1083. ssl_context = ssl._create_stdlib_context()
  1084. transport, _ = await loop.create_connection(
  1085. lambda: protocol, host, port, ssl=ssl_context)
  1086. writer = StreamWriter(transport, protocol, reader, loop)
  1087.  
  1088. self = await _NNTPBase.create(reader, writer, host,
  1089. readermode, timeout)
  1090. self.host = host
  1091. self.reader, self.writer = reader, writer
  1092. self.transport = transport
  1093. self.loop = loop
  1094. self.protocol = protocol
  1095.  
  1096. if user or usenetrc:
  1097. await self.login(user, password, usenetrc)
  1098. except:
  1099. if writer:
  1100. writer.close()
  1101. raise
  1102. return self
  1103.  
  1104. def _close(self):
  1105. try:
  1106. _NNTPBase._close(self)
  1107. finally:
  1108. self.writer.close()
  1109.  
  1110. __all__.append("NNTP_SSL")
  1111.  
  1112.  
  1113. # Test retrieval when run as a script.
  1114. if __name__ == '__main__':
  1115. import argparse
  1116.  
  1117. parser = argparse.ArgumentParser(description="""\
  1118. nntplib built-in demo - display the latest articles in a newsgroup""")
  1119. parser.add_argument('-g', '--group', default='gmane.comp.python.general',
  1120. help='group to fetch messages from (default: %(default)s)')
  1121. parser.add_argument('-s', '--server', default='news.gmane.org',
  1122. help='NNTP server hostname (default: %(default)s)')
  1123. parser.add_argument('-p', '--port', default=-1, type=int,
  1124. help='NNTP port number (default: %s / %s)' % (NNTP_PORT, NNTP_SSL_PORT))
  1125. parser.add_argument('-n', '--nb-articles', default=10, type=int,
  1126. help='number of articles to fetch (default: %(default)s)')
  1127. parser.add_argument('-S', '--ssl', action='store_true', default=False,
  1128. help='use NNTP over SSL')
  1129. args = parser.parse_args()
  1130.  
  1131. port = args.port
  1132. if not args.ssl:
  1133. if port == -1:
  1134. port = NNTP_PORT
  1135. s = asyncio.get_event_loop().run_until_complete(AIO_NNTP.create(host=args.server, port=port))
  1136. else:
  1137. if port == -1:
  1138. port = NNTP_SSL_PORT
  1139. s = asyncio.get_event_loop().run_until_complete(AIO_NNTP_SSL.create(host=args.server, port=port))
  1140.  
  1141. caps = asyncio.get_event_loop().run_until_complete(s.getcapabilities())
  1142. if 'STARTTLS' in caps:
  1143. asyncio.get_event_loop().run_until_complete(s.starttls())
  1144. resp, count, first, last, name = asyncio.get_event_loop().run_until_complete(s.group(args.group))
  1145. print('Group', name, 'has', count, 'articles, range', first, 'to', last)
  1146.  
  1147. def cut(s, lim):
  1148. if len(s) > lim:
  1149. s = s[:lim - 4] + "..."
  1150. return s
  1151.  
  1152. first = str(int(last) - args.nb_articles + 1)
  1153. resp, overviews = asyncio.get_event_loop().run_until_complete(s.xover(first, last))
  1154. for artnum, over in overviews:
  1155. author = decode_header(over['from']).split('<', 1)[0]
  1156. subject = decode_header(over['subject'])
  1157. lines = int(over[':lines'])
  1158. print("{:7} {:20} {:42} ({})".format(
  1159. artnum, cut(author, 20), cut(subject, 42), lines)
  1160. )
  1161.  
  1162. asyncio.get_event_loop().run_until_complete(s.quit())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement