nntplib.py 40 KB

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